]> code.delx.au - gnu-emacs/blob - doc/lispintro/emacs-lisp-intro.texi
Merge from emacs-24; up to 2012-12-06T01:39:03Z!monnier@iro.umontreal.ca
[gnu-emacs] / doc / lispintro / emacs-lisp-intro.texi
1 \input texinfo @c -*-texinfo-*-
2 @comment %**start of header
3 @setfilename ../../info/eintr
4 @c setfilename emacs-lisp-intro.info
5 @c sethtmlfilename emacs-lisp-intro.html
6 @settitle Programming in Emacs Lisp
7 @syncodeindex vr cp
8 @syncodeindex fn cp
9 @finalout
10
11 @c ---------
12 @c <<<< For hard copy printing, this file is now
13 @c set for smallbook, which works for all sizes
14 @c of paper, and with PostScript figures >>>>
15 @set smallbook
16 @ifset smallbook
17 @smallbook
18 @clear largebook
19 @end ifset
20 @set print-postscript-figures
21 @c set largebook
22 @c clear print-postscript-figures
23 @c ---------
24
25 @comment %**end of header
26
27 @c per rms and peterb, use 10pt fonts for the main text, mostly to
28 @c save on paper cost.
29 @c Do this inside @tex for now, so current makeinfo does not complain.
30 @tex
31 @ifset smallbook
32 @fonttextsize 10
33
34 @end ifset
35 \global\hbadness=6666 % don't worry about not-too-underfull boxes
36 @end tex
37
38 @set edition-number 3.10
39 @set update-date 28 October 2009
40
41 @ignore
42 ## Summary of shell commands to create various output formats:
43
44 pushd /usr/local/src/emacs/lispintro/
45 ## pushd /u/intro/
46
47 ## Info output
48 makeinfo --paragraph-indent=0 --verbose emacs-lisp-intro.texi
49
50 ## ;; (progn (when (bufferp (get-buffer "*info*")) (kill-buffer "*info*")) (info "/usr/local/src/emacs/info/eintr"))
51
52 ## DVI output
53 texi2dvi emacs-lisp-intro.texi
54
55 ## xdvi -margins 24pt -topmargin 4pt -offsets 24pt -geometry 760x1140 -s 5 -useTeXpages -mousemode 1 emacs-lisp-intro.dvi &
56
57 ## HTML output
58 makeinfo --html --no-split --verbose emacs-lisp-intro.texi
59
60 ## galeon emacs-lisp-intro.html
61
62 ## Plain text output
63 makeinfo --fill-column=70 --no-split --paragraph-indent=0 \
64 --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi
65
66 popd
67
68 # as user `root'
69 # insert thumbdrive
70 mtusb # mount -v -t ext3 /dev/sda /mnt
71 cp -v /u/intro/emacs-lisp-intro.texi /mnt/backup/intro/emacs-lisp-intro.texi
72 umtusb # umount -v /mnt
73 # remove thumbdrive
74
75 ## Other shell commands
76
77 pushd /usr/local/src/emacs/lispintro/
78 ## pushd /u/intro/
79
80 ## PDF
81 texi2dvi --pdf emacs-lisp-intro.texi
82 # xpdf emacs-lisp-intro.pdf &
83
84 ## DocBook -- note file extension
85 makeinfo --docbook --no-split --paragraph-indent=0 \
86 --verbose --output=emacs-lisp-intro.docbook emacs-lisp-intro.texi
87
88 ## XML with a Texinfo DTD -- note file extension
89 makeinfo --xml --no-split --paragraph-indent=0 \
90 --verbose --output=emacs-lisp-intro.texinfoxml emacs-lisp-intro.texi
91
92 ## PostScript (needs DVI)
93 # gv emacs-lisp-intro.ps &
94 # Create DVI if we lack it
95 # texi2dvi emacs-lisp-intro.texi
96 dvips emacs-lisp-intro.dvi -o emacs-lisp-intro.ps
97
98 ## RTF (needs HTML)
99 # Use OpenOffice to view RTF
100 # Create HTML if we lack it
101 # makeinfo --no-split --html emacs-lisp-intro.texi
102 /usr/local/src/html2rtf.pl emacs-lisp-intro.html
103
104 ## LaTeX (needs RTF)
105 /usr/bin/rtf2latex emacs-lisp-intro.rtf
106
107 popd
108
109 @end ignore
110
111 @c ================ Included Figures ================
112
113 @c Set print-postscript-figures if you print PostScript figures.
114 @c If you clear this, the ten figures will be printed as ASCII diagrams.
115 @c (This is not relevant to Info, since Info only handles ASCII.)
116 @c Your site may require editing changes to print PostScript; in this
117 @c case, search for `print-postscript-figures' and make appropriate changes.
118
119 @c ================ How to Create an Info file ================
120
121 @c If you have `makeinfo' installed, run the following command
122
123 @c makeinfo emacs-lisp-intro.texi
124
125 @c or, if you want a single, large Info file, and no paragraph indents:
126 @c makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
127
128 @c After creating the Info file, edit your Info `dir' file, if the
129 @c `dircategory' section below does not enable your system to
130 @c install the manual automatically.
131 @c (The `dir' file is often in the `/usr/local/share/info/' directory.)
132
133 @c ================ How to Create an HTML file ================
134
135 @c To convert to HTML format
136 @c makeinfo --html --no-split --verbose emacs-lisp-intro.texi
137
138 @c ================ How to Print a Book in Various Sizes ================
139
140 @c This book can be printed in any of three different sizes.
141 @c In the above header, set @-commands appropriately.
142
143 @c 7 by 9.25 inches:
144 @c @smallbook
145 @c @clear largebook
146
147 @c 8.5 by 11 inches:
148 @c @c smallbook
149 @c @set largebook
150
151 @c European A4 size paper:
152 @c @c smallbook
153 @c @afourpaper
154 @c @set largebook
155
156 @c ================ How to Typeset and Print ================
157
158 @c If you do not include PostScript figures, run either of the
159 @c following command sequences, or similar commands suited to your
160 @c system:
161
162 @c texi2dvi emacs-lisp-intro.texi
163 @c lpr -d emacs-lisp-intro.dvi
164
165 @c or else:
166
167 @c tex emacs-lisp-intro.texi
168 @c texindex emacs-lisp-intro.??
169 @c tex emacs-lisp-intro.texi
170 @c lpr -d emacs-lisp-intro.dvi
171
172 @c If you include the PostScript figures, and you have old software,
173 @c you may need to convert the .dvi file to a .ps file before
174 @c printing. Run either of the following command sequences, or one
175 @c similar:
176 @c
177 @c dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
178 @c
179 @c or else:
180 @c
181 @c postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
182 @c
183
184 @c (Note: if you edit the book so as to change the length of the
185 @c table of contents, you may have to change the value of `pageno' below.)
186
187 @c ================ End of Formatting Sections ================
188
189 @c For next or subsequent edition:
190 @c create function using with-output-to-temp-buffer
191 @c create a major mode, with keymaps
192 @c run an asynchronous process, like grep or diff
193
194 @c For 8.5 by 11 inch format: do not use such a small amount of
195 @c whitespace between paragraphs as smallbook format
196 @ifset largebook
197 @tex
198 \global\parskip 6pt plus 1pt
199 @end tex
200 @end ifset
201
202 @c For all sized formats: print within-book cross
203 @c reference with ``...'' rather than [...]
204
205 @c This works with the texinfo.tex file, version 2003-05-04.08,
206 @c in the Texinfo version 4.6 of the 2003 Jun 13 distribution.
207
208 @tex
209 \if \xrefprintnodename
210 \global\def\xrefprintnodename#1{\unskip, ``#1''}
211 \else
212 \global\def\xrefprintnodename#1{ ``#1''}
213 \fi
214 % \global\def\xrefprintnodename#1{, ``#1''}
215 @end tex
216
217 @c ----------------------------------------------------
218
219 @dircategory GNU Emacs Lisp
220 @direntry
221 * Emacs Lisp Intro: (eintr).
222 A simple introduction to Emacs Lisp programming.
223 @end direntry
224
225 @copying
226 This is an @cite{Introduction to Programming in Emacs Lisp}, for
227 people who are not programmers.
228 @sp 1
229 Edition @value{edition-number}, @value{update-date}
230 @sp 1
231 Copyright @copyright{} 1990--1995, 1997, 2001--2013 Free Software
232 Foundation, Inc.
233 @sp 1
234
235 @iftex
236 Published by the:@*
237
238 GNU Press, @hfill @uref{http://www.fsf.org/campaigns/gnu-press/}@*
239 a division of the @hfill email: @email{sales@@fsf.org}@*
240 Free Software Foundation, Inc. @hfill Tel: +1 (617) 542-5942@*
241 51 Franklin Street, Fifth Floor @hfill Fax: +1 (617) 542-2652@*
242 Boston, MA 02110-1301 USA
243 @end iftex
244
245 @ifnottex
246 Published by the:
247
248 @example
249 GNU Press, http://www.fsf.org/campaigns/gnu-press/
250 a division of the email: sales@@fsf.org
251 Free Software Foundation, Inc. Tel: +1 (617) 542-5942
252 51 Franklin Street, Fifth Floor Fax: +1 (617) 542-2652
253 Boston, MA 02110-1301 USA
254 @end example
255 @end ifnottex
256
257 @sp 1
258 @c Printed copies are available from @uref{http://shop.fsf.org/} for $35 each.@*
259 ISBN 1-882114-43-4
260
261 Permission is granted to copy, distribute and/or modify this document
262 under the terms of the GNU Free Documentation License, Version 1.3 or
263 any later version published by the Free Software Foundation; there
264 being no Invariant Section, with the Front-Cover Texts being ``A GNU
265 Manual'', and with the Back-Cover Texts as in (a) below. A copy of
266 the license is included in the section entitled ``GNU Free
267 Documentation License''.
268
269 (a) The FSF's Back-Cover Text is: ``You have the freedom to
270 copy and modify this GNU manual. Buying copies from the FSF
271 supports it in developing GNU and promoting software freedom.''
272 @end copying
273
274 @c half title; two lines here, so do not use `shorttitlepage'
275 @tex
276 {\begingroup%
277 \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
278 \endgroup}%
279 {\begingroup\hbox{}\vskip 0.25in \chaprm%
280 \centerline{Programming in Emacs Lisp}%
281 \endgroup\page\hbox{}\page}
282 @end tex
283
284 @titlepage
285 @sp 6
286 @center @titlefont{An Introduction to}
287 @sp 2
288 @center @titlefont{Programming in Emacs Lisp}
289 @sp 2
290 @center Revised Third Edition
291 @sp 4
292 @center by Robert J. Chassell
293
294 @page
295 @vskip 0pt plus 1filll
296 @insertcopying
297 @end titlepage
298
299 @iftex
300 @headings off
301 @evenheading @thispage @| @| @thischapter
302 @oddheading @thissection @| @| @thispage
303 @end iftex
304
305 @ifnothtml
306 @c Keep T.O.C. short by tightening up for largebook
307 @ifset largebook
308 @tex
309 \global\parskip 2pt plus 1pt
310 \global\advance\baselineskip by -1pt
311 @end tex
312 @end ifset
313 @end ifnothtml
314
315 @shortcontents
316 @contents
317
318 @ifnottex
319 @node Top
320 @top An Introduction to Programming in Emacs Lisp
321
322 @insertcopying
323
324 This master menu first lists each chapter and index; then it lists
325 every node in every chapter.
326 @end ifnottex
327
328 @c >>>> Set pageno appropriately <<<<
329
330 @c The first page of the Preface is a roman numeral; it is the first
331 @c right handed page after the Table of Contents; hence the following
332 @c setting must be for an odd negative number.
333
334 @c iftex
335 @c global@pageno = -11
336 @c end iftex
337
338 @set COUNT-WORDS count-words-example
339 @c Length of variable name chosen so that things still line up when expanded.
340
341 @menu
342 * Preface:: What to look for.
343 * List Processing:: What is Lisp?
344 * Practicing Evaluation:: Running several programs.
345 * Writing Defuns:: How to write function definitions.
346 * Buffer Walk Through:: Exploring a few buffer-related functions.
347 * More Complex:: A few, even more complex functions.
348 * Narrowing & Widening:: Restricting your and Emacs attention to
349 a region.
350 * car cdr & cons:: Fundamental functions in Lisp.
351 * Cutting & Storing Text:: Removing text and saving it.
352 * List Implementation:: How lists are implemented in the computer.
353 * Yanking:: Pasting stored text.
354 * Loops & Recursion:: How to repeat a process.
355 * Regexp Search:: Regular expression searches.
356 * Counting Words:: A review of repetition and regexps.
357 * Words in a defun:: Counting words in a @code{defun}.
358 * Readying a Graph:: A prototype graph printing function.
359 * Emacs Initialization:: How to write a @file{.emacs} file.
360 * Debugging:: How to run the Emacs Lisp debuggers.
361 * Conclusion:: Now you have the basics.
362 * the-the:: An appendix: how to find reduplicated words.
363 * Kill Ring:: An appendix: how the kill ring works.
364 * Full Graph:: How to create a graph with labeled axes.
365 * Free Software and Free Manuals::
366 * GNU Free Documentation License::
367 * Index::
368 * About the Author::
369
370 @detailmenu
371 --- The Detailed Node Listing ---
372
373 Preface
374
375 * Why:: Why learn Emacs Lisp?
376 * On Reading this Text:: Read, gain familiarity, pick up habits....
377 * Who You Are:: For whom this is written.
378 * Lisp History::
379 * Note for Novices:: You can read this as a novice.
380 * Thank You::
381
382 List Processing
383
384 * Lisp Lists:: What are lists?
385 * Run a Program:: Any list in Lisp is a program ready to run.
386 * Making Errors:: Generating an error message.
387 * Names & Definitions:: Names of symbols and function definitions.
388 * Lisp Interpreter:: What the Lisp interpreter does.
389 * Evaluation:: Running a program.
390 * Variables:: Returning a value from a variable.
391 * Arguments:: Passing information to a function.
392 * set & setq:: Setting the value of a variable.
393 * Summary:: The major points.
394 * Error Message Exercises::
395
396 Lisp Lists
397
398 * Numbers Lists:: List have numbers, other lists, in them.
399 * Lisp Atoms:: Elemental entities.
400 * Whitespace in Lists:: Formatting lists to be readable.
401 * Typing Lists:: How GNU Emacs helps you type lists.
402
403 The Lisp Interpreter
404
405 * Complications:: Variables, Special forms, Lists within.
406 * Byte Compiling:: Specially processing code for speed.
407
408 Evaluation
409
410 * How the Interpreter Acts:: Returns and Side Effects...
411 * Evaluating Inner Lists:: Lists within lists...
412
413 Variables
414
415 * fill-column Example::
416 * Void Function:: The error message for a symbol
417 without a function.
418 * Void Variable:: The error message for a symbol without a value.
419
420 Arguments
421
422 * Data types:: Types of data passed to a function.
423 * Args as Variable or List:: An argument can be the value
424 of a variable or list.
425 * Variable Number of Arguments:: Some functions may take a
426 variable number of arguments.
427 * Wrong Type of Argument:: Passing an argument of the wrong type
428 to a function.
429 * message:: A useful function for sending messages.
430
431 Setting the Value of a Variable
432
433 * Using set:: Setting values.
434 * Using setq:: Setting a quoted value.
435 * Counting:: Using @code{setq} to count.
436
437 Practicing Evaluation
438
439 * How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
440 causes evaluation.
441 * Buffer Names:: Buffers and files are different.
442 * Getting Buffers:: Getting a buffer itself, not merely its name.
443 * Switching Buffers:: How to change to another buffer.
444 * Buffer Size & Locations:: Where point is located and the size of
445 the buffer.
446 * Evaluation Exercise::
447
448 How To Write Function Definitions
449
450 * Primitive Functions::
451 * defun:: The @code{defun} special form.
452 * Install:: Install a function definition.
453 * Interactive:: Making a function interactive.
454 * Interactive Options:: Different options for @code{interactive}.
455 * Permanent Installation:: Installing code permanently.
456 * let:: Creating and initializing local variables.
457 * if:: What if?
458 * else:: If--then--else expressions.
459 * Truth & Falsehood:: What Lisp considers false and true.
460 * save-excursion:: Keeping track of point, mark, and buffer.
461 * Review::
462 * defun Exercises::
463
464 Install a Function Definition
465
466 * Effect of installation::
467 * Change a defun:: How to change a function definition.
468
469 Make a Function Interactive
470
471 * Interactive multiply-by-seven:: An overview.
472 * multiply-by-seven in detail:: The interactive version.
473
474 @code{let}
475
476 * Prevent confusion::
477 * Parts of let Expression::
478 * Sample let Expression::
479 * Uninitialized let Variables::
480
481 The @code{if} Special Form
482
483 * if in more detail::
484 * type-of-animal in detail:: An example of an @code{if} expression.
485
486 Truth and Falsehood in Emacs Lisp
487
488 * nil explained:: @code{nil} has two meanings.
489
490 @code{save-excursion}
491
492 * Point and mark:: A review of various locations.
493 * Template for save-excursion::
494
495 A Few Buffer--Related Functions
496
497 * Finding More:: How to find more information.
498 * simplified-beginning-of-buffer:: Shows @code{goto-char},
499 @code{point-min}, and @code{push-mark}.
500 * mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
501 * append-to-buffer:: Uses @code{save-excursion} and
502 @code{insert-buffer-substring}.
503 * Buffer Related Review:: Review.
504 * Buffer Exercises::
505
506 The Definition of @code{mark-whole-buffer}
507
508 * mark-whole-buffer overview::
509 * Body of mark-whole-buffer:: Only three lines of code.
510
511 The Definition of @code{append-to-buffer}
512
513 * append-to-buffer overview::
514 * append interactive:: A two part interactive expression.
515 * append-to-buffer body:: Incorporates a @code{let} expression.
516 * append save-excursion:: How the @code{save-excursion} works.
517
518 A Few More Complex Functions
519
520 * copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
521 * insert-buffer:: Read-only, and with @code{or}.
522 * beginning-of-buffer:: Shows @code{goto-char},
523 @code{point-min}, and @code{push-mark}.
524 * Second Buffer Related Review::
525 * optional Exercise::
526
527 The Definition of @code{insert-buffer}
528
529 * insert-buffer code::
530 * insert-buffer interactive:: When you can read, but not write.
531 * insert-buffer body:: The body has an @code{or} and a @code{let}.
532 * if & or:: Using an @code{if} instead of an @code{or}.
533 * Insert or:: How the @code{or} expression works.
534 * Insert let:: Two @code{save-excursion} expressions.
535 * New insert-buffer::
536
537 The Interactive Expression in @code{insert-buffer}
538
539 * Read-only buffer:: When a buffer cannot be modified.
540 * b for interactive:: An existing buffer or else its name.
541
542 Complete Definition of @code{beginning-of-buffer}
543
544 * Optional Arguments::
545 * beginning-of-buffer opt arg:: Example with optional argument.
546 * beginning-of-buffer complete::
547
548 @code{beginning-of-buffer} with an Argument
549
550 * Disentangle beginning-of-buffer::
551 * Large buffer case::
552 * Small buffer case::
553
554 Narrowing and Widening
555
556 * Narrowing advantages:: The advantages of narrowing
557 * save-restriction:: The @code{save-restriction} special form.
558 * what-line:: The number of the line that point is on.
559 * narrow Exercise::
560
561 @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
562
563 * Strange Names:: An historical aside: why the strange names?
564 * car & cdr:: Functions for extracting part of a list.
565 * cons:: Constructing a list.
566 * nthcdr:: Calling @code{cdr} repeatedly.
567 * nth::
568 * setcar:: Changing the first element of a list.
569 * setcdr:: Changing the rest of a list.
570 * cons Exercise::
571
572 @code{cons}
573
574 * Build a list::
575 * length:: How to find the length of a list.
576
577 Cutting and Storing Text
578
579 * Storing Text:: Text is stored in a list.
580 * zap-to-char:: Cutting out text up to a character.
581 * kill-region:: Cutting text out of a region.
582 * copy-region-as-kill:: A definition for copying text.
583 * Digression into C:: Minor note on C programming language macros.
584 * defvar:: How to give a variable an initial value.
585 * cons & search-fwd Review::
586 * search Exercises::
587
588 @code{zap-to-char}
589
590 * Complete zap-to-char:: The complete implementation.
591 * zap-to-char interactive:: A three part interactive expression.
592 * zap-to-char body:: A short overview.
593 * search-forward:: How to search for a string.
594 * progn:: The @code{progn} special form.
595 * Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
596
597 @code{kill-region}
598
599 * Complete kill-region:: The function definition.
600 * condition-case:: Dealing with a problem.
601 * Lisp macro::
602
603 @code{copy-region-as-kill}
604
605 * Complete copy-region-as-kill:: The complete function definition.
606 * copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
607
608 The Body of @code{copy-region-as-kill}
609
610 * last-command & this-command::
611 * kill-append function::
612 * kill-new function::
613
614 Initializing a Variable with @code{defvar}
615
616 * See variable current value::
617 * defvar and asterisk::
618
619 How Lists are Implemented
620
621 * Lists diagrammed::
622 * Symbols as Chest:: Exploring a powerful metaphor.
623 * List Exercise::
624
625 Yanking Text Back
626
627 * Kill Ring Overview::
628 * kill-ring-yank-pointer:: The kill ring is a list.
629 * yank nthcdr Exercises:: The @code{kill-ring-yank-pointer} variable.
630
631 Loops and Recursion
632
633 * while:: Causing a stretch of code to repeat.
634 * dolist dotimes::
635 * Recursion:: Causing a function to call itself.
636 * Looping exercise::
637
638 @code{while}
639
640 * Looping with while:: Repeat so long as test returns true.
641 * Loop Example:: A @code{while} loop that uses a list.
642 * print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
643 * Incrementing Loop:: A loop with an incrementing counter.
644 * Incrementing Loop Details::
645 * Decrementing Loop:: A loop with a decrementing counter.
646
647 Details of an Incrementing Loop
648
649 * Incrementing Example:: Counting pebbles in a triangle.
650 * Inc Example parts:: The parts of the function definition.
651 * Inc Example altogether:: Putting the function definition together.
652
653 Loop with a Decrementing Counter
654
655 * Decrementing Example:: More pebbles on the beach.
656 * Dec Example parts:: The parts of the function definition.
657 * Dec Example altogether:: Putting the function definition together.
658
659 Save your time: @code{dolist} and @code{dotimes}
660
661 * dolist::
662 * dotimes::
663
664 Recursion
665
666 * Building Robots:: Same model, different serial number ...
667 * Recursive Definition Parts:: Walk until you stop ...
668 * Recursion with list:: Using a list as the test whether to recurse.
669 * Recursive triangle function::
670 * Recursion with cond::
671 * Recursive Patterns:: Often used templates.
672 * No Deferment:: Don't store up work ...
673 * No deferment solution::
674
675 Recursion in Place of a Counter
676
677 * Recursive Example arg of 1 or 2::
678 * Recursive Example arg of 3 or 4::
679
680 Recursive Patterns
681
682 * Every::
683 * Accumulate::
684 * Keep::
685
686 Regular Expression Searches
687
688 * sentence-end:: The regular expression for @code{sentence-end}.
689 * re-search-forward:: Very similar to @code{search-forward}.
690 * forward-sentence:: A straightforward example of regexp search.
691 * forward-paragraph:: A somewhat complex example.
692 * etags:: How to create your own @file{TAGS} table.
693 * Regexp Review::
694 * re-search Exercises::
695
696 @code{forward-sentence}
697
698 * Complete forward-sentence::
699 * fwd-sentence while loops:: Two @code{while} loops.
700 * fwd-sentence re-search:: A regular expression search.
701
702 @code{forward-paragraph}: a Goldmine of Functions
703
704 * forward-paragraph in brief:: Key parts of the function definition.
705 * fwd-para let:: The @code{let*} expression.
706 * fwd-para while:: The forward motion @code{while} loop.
707
708 Counting: Repetition and Regexps
709
710 * Why Count Words::
711 * @value{COUNT-WORDS}:: Use a regexp, but find a problem.
712 * recursive-count-words:: Start with case of no words in region.
713 * Counting Exercise::
714
715 The @code{@value{COUNT-WORDS}} Function
716
717 * Design @value{COUNT-WORDS}:: The definition using a @code{while} loop.
718 * Whitespace Bug:: The Whitespace Bug in @code{@value{COUNT-WORDS}}.
719
720 Counting Words in a @code{defun}
721
722 * Divide and Conquer::
723 * Words and Symbols:: What to count?
724 * Syntax:: What constitutes a word or symbol?
725 * count-words-in-defun:: Very like @code{@value{COUNT-WORDS}}.
726 * Several defuns:: Counting several defuns in a file.
727 * Find a File:: Do you want to look at a file?
728 * lengths-list-file:: A list of the lengths of many definitions.
729 * Several files:: Counting in definitions in different files.
730 * Several files recursively:: Recursively counting in different files.
731 * Prepare the data:: Prepare the data for display in a graph.
732
733 Count Words in @code{defuns} in Different Files
734
735 * lengths-list-many-files:: Return a list of the lengths of defuns.
736 * append:: Attach one list to another.
737
738 Prepare the Data for Display in a Graph
739
740 * Data for Display in Detail::
741 * Sorting:: Sorting lists.
742 * Files List:: Making a list of files.
743 * Counting function definitions::
744
745 Readying a Graph
746
747 * Columns of a graph::
748 * graph-body-print:: How to print the body of a graph.
749 * recursive-graph-body-print::
750 * Printed Axes::
751 * Line Graph Exercise::
752
753 Your @file{.emacs} File
754
755 * Default Configuration::
756 * Site-wide Init:: You can write site-wide init files.
757 * defcustom:: Emacs will write code for you.
758 * Beginning a .emacs File:: How to write a @code{.emacs file}.
759 * Text and Auto-fill:: Automatically wrap lines.
760 * Mail Aliases:: Use abbreviations for email addresses.
761 * Indent Tabs Mode:: Don't use tabs with @TeX{}
762 * Keybindings:: Create some personal keybindings.
763 * Keymaps:: More about key binding.
764 * Loading Files:: Load (i.e., evaluate) files automatically.
765 * Autoload:: Make functions available.
766 * Simple Extension:: Define a function; bind it to a key.
767 * X11 Colors:: Colors in X.
768 * Miscellaneous::
769 * Mode Line:: How to customize your mode line.
770
771 Debugging
772
773 * debug:: How to use the built-in debugger.
774 * debug-on-entry:: Start debugging when you call a function.
775 * debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
776 * edebug:: How to use Edebug, a source level debugger.
777 * Debugging Exercises::
778
779 Handling the Kill Ring
780
781 * What the Kill Ring Does::
782 * current-kill::
783 * yank:: Paste a copy of a clipped element.
784 * yank-pop:: Insert element pointed to.
785 * ring file::
786
787 The @code{current-kill} Function
788
789 * Code for current-kill::
790 * Understanding current-kill::
791
792 @code{current-kill} in Outline
793
794 * Body of current-kill::
795 * Digression concerning error:: How to mislead humans, but not computers.
796 * Determining the Element::
797
798 A Graph with Labeled Axes
799
800 * Labeled Example::
801 * print-graph Varlist:: @code{let} expression in @code{print-graph}.
802 * print-Y-axis:: Print a label for the vertical axis.
803 * print-X-axis:: Print a horizontal label.
804 * Print Whole Graph:: The function to print a complete graph.
805
806 The @code{print-Y-axis} Function
807
808 * print-Y-axis in Detail::
809 * Height of label:: What height for the Y axis?
810 * Compute a Remainder:: How to compute the remainder of a division.
811 * Y Axis Element:: Construct a line for the Y axis.
812 * Y-axis-column:: Generate a list of Y axis labels.
813 * print-Y-axis Penultimate:: A not quite final version.
814
815 The @code{print-X-axis} Function
816
817 * Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
818 * X Axis Tic Marks:: Create tic marks for the horizontal axis.
819
820 Printing the Whole Graph
821
822 * The final version:: A few changes.
823 * Test print-graph:: Run a short test.
824 * Graphing words in defuns:: Executing the final code.
825 * lambda:: How to write an anonymous function.
826 * mapcar:: Apply a function to elements of a list.
827 * Another Bug:: Yet another bug @dots{} most insidious.
828 * Final printed graph:: The graph itself!
829
830 @end detailmenu
831 @end menu
832
833 @node Preface
834 @unnumbered Preface
835
836 Most of the GNU Emacs integrated environment is written in the programming
837 language called Emacs Lisp. The code written in this programming
838 language is the software---the sets of instructions---that tell the
839 computer what to do when you give it commands. Emacs is designed so
840 that you can write new code in Emacs Lisp and easily install it as an
841 extension to the editor.
842
843 (GNU Emacs is sometimes called an ``extensible editor'', but it does
844 much more than provide editing capabilities. It is better to refer to
845 Emacs as an ``extensible computing environment''. However, that
846 phrase is quite a mouthful. It is easier to refer to Emacs simply as
847 an editor. Moreover, everything you do in Emacs---find the Mayan date
848 and phases of the moon, simplify polynomials, debug code, manage
849 files, read letters, write books---all these activities are kinds of
850 editing in the most general sense of the word.)
851
852 @menu
853 * Why:: Why learn Emacs Lisp?
854 * On Reading this Text:: Read, gain familiarity, pick up habits....
855 * Who You Are:: For whom this is written.
856 * Lisp History::
857 * Note for Novices:: You can read this as a novice.
858 * Thank You::
859 @end menu
860
861 @ifnottex
862 @node Why
863 @unnumberedsec Why Study Emacs Lisp?
864 @end ifnottex
865
866 Although Emacs Lisp is usually thought of in association only with Emacs,
867 it is a full computer programming language. You can use Emacs Lisp as
868 you would any other programming language.
869
870 Perhaps you want to understand programming; perhaps you want to extend
871 Emacs; or perhaps you want to become a programmer. This introduction to
872 Emacs Lisp is designed to get you started: to guide you in learning the
873 fundamentals of programming, and more importantly, to show you how you
874 can teach yourself to go further.
875
876 @node On Reading this Text
877 @unnumberedsec On Reading this Text
878
879 All through this document, you will see little sample programs you can
880 run inside of Emacs. If you read this document in Info inside of GNU
881 Emacs, you can run the programs as they appear. (This is easy to do and
882 is explained when the examples are presented.) Alternatively, you can
883 read this introduction as a printed book while sitting beside a computer
884 running Emacs. (This is what I like to do; I like printed books.) If
885 you don't have a running Emacs beside you, you can still read this book,
886 but in this case, it is best to treat it as a novel or as a travel guide
887 to a country not yet visited: interesting, but not the same as being
888 there.
889
890 Much of this introduction is dedicated to walkthroughs or guided tours
891 of code used in GNU Emacs. These tours are designed for two purposes:
892 first, to give you familiarity with real, working code (code you use
893 every day); and, second, to give you familiarity with the way Emacs
894 works. It is interesting to see how a working environment is
895 implemented.
896 Also, I
897 hope that you will pick up the habit of browsing through source code.
898 You can learn from it and mine it for ideas. Having GNU Emacs is like
899 having a dragon's cave of treasures.
900
901 In addition to learning about Emacs as an editor and Emacs Lisp as a
902 programming language, the examples and guided tours will give you an
903 opportunity to get acquainted with Emacs as a Lisp programming
904 environment. GNU Emacs supports programming and provides tools that
905 you will want to become comfortable using, such as @kbd{M-.} (the key
906 which invokes the @code{find-tag} command). You will also learn about
907 buffers and other objects that are part of the environment.
908 Learning about these features of Emacs is like learning new routes
909 around your home town.
910
911 @ignore
912 In addition, I have written several programs as extended examples.
913 Although these are examples, the programs are real. I use them.
914 Other people use them. You may use them. Beyond the fragments of
915 programs used for illustrations, there is very little in here that is
916 `just for teaching purposes'; what you see is used. This is a great
917 advantage of Emacs Lisp: it is easy to learn to use it for work.
918 @end ignore
919
920 Finally, I hope to convey some of the skills for using Emacs to
921 learn aspects of programming that you don't know. You can often use
922 Emacs to help you understand what puzzles you or to find out how to do
923 something new. This self-reliance is not only a pleasure, but an
924 advantage.
925
926 @node Who You Are
927 @unnumberedsec For Whom This is Written
928
929 This text is written as an elementary introduction for people who are
930 not programmers. If you are a programmer, you may not be satisfied with
931 this primer. The reason is that you may have become expert at reading
932 reference manuals and be put off by the way this text is organized.
933
934 An expert programmer who reviewed this text said to me:
935
936 @quotation
937 @i{I prefer to learn from reference manuals. I ``dive into'' each
938 paragraph, and ``come up for air'' between paragraphs.}
939
940 @i{When I get to the end of a paragraph, I assume that that subject is
941 done, finished, that I know everything I need (with the
942 possible exception of the case when the next paragraph starts talking
943 about it in more detail). I expect that a well written reference manual
944 will not have a lot of redundancy, and that it will have excellent
945 pointers to the (one) place where the information I want is.}
946 @end quotation
947
948 This introduction is not written for this person!
949
950 Firstly, I try to say everything at least three times: first, to
951 introduce it; second, to show it in context; and third, to show it in a
952 different context, or to review it.
953
954 Secondly, I hardly ever put all the information about a subject in one
955 place, much less in one paragraph. To my way of thinking, that imposes
956 too heavy a burden on the reader. Instead I try to explain only what
957 you need to know at the time. (Sometimes I include a little extra
958 information so you won't be surprised later when the additional
959 information is formally introduced.)
960
961 When you read this text, you are not expected to learn everything the
962 first time. Frequently, you need only make, as it were, a `nodding
963 acquaintance' with some of the items mentioned. My hope is that I have
964 structured the text and given you enough hints that you will be alert to
965 what is important, and concentrate on it.
966
967 You will need to ``dive into'' some paragraphs; there is no other way
968 to read them. But I have tried to keep down the number of such
969 paragraphs. This book is intended as an approachable hill, rather than
970 as a daunting mountain.
971
972 This introduction to @cite{Programming in Emacs Lisp} has a companion
973 document,
974 @iftex
975 @cite{The GNU Emacs Lisp Reference Manual}.
976 @end iftex
977 @ifnottex
978 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
979 Emacs Lisp Reference Manual}.
980 @end ifnottex
981 The reference manual has more detail than this introduction. In the
982 reference manual, all the information about one topic is concentrated
983 in one place. You should turn to it if you are like the programmer
984 quoted above. And, of course, after you have read this
985 @cite{Introduction}, you will find the @cite{Reference Manual} useful
986 when you are writing your own programs.
987
988 @node Lisp History
989 @unnumberedsec Lisp History
990 @cindex Lisp history
991
992 Lisp was first developed in the late 1950s at the Massachusetts
993 Institute of Technology for research in artificial intelligence. The
994 great power of the Lisp language makes it superior for other purposes as
995 well, such as writing editor commands and integrated environments.
996
997 @cindex Maclisp
998 @cindex Common Lisp
999 GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
1000 in the 1960s. It is somewhat inspired by Common Lisp, which became a
1001 standard in the 1980s. However, Emacs Lisp is much simpler than Common
1002 Lisp. (The standard Emacs distribution contains an optional extensions
1003 file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1004
1005 @node Note for Novices
1006 @unnumberedsec A Note for Novices
1007
1008 If you don't know GNU Emacs, you can still read this document
1009 profitably. However, I recommend you learn Emacs, if only to learn to
1010 move around your computer screen. You can teach yourself how to use
1011 Emacs with the on-line tutorial. To use it, type @kbd{C-h t}. (This
1012 means you press and release the @key{CTRL} key and the @kbd{h} at the
1013 same time, and then press and release @kbd{t}.)
1014
1015 Also, I often refer to one of Emacs's standard commands by listing the
1016 keys which you press to invoke the command and then giving the name of
1017 the command in parentheses, like this: @kbd{M-C-\}
1018 (@code{indent-region}). What this means is that the
1019 @code{indent-region} command is customarily invoked by typing
1020 @kbd{M-C-\}. (You can, if you wish, change the keys that are typed to
1021 invoke the command; this is called @dfn{rebinding}. @xref{Keymaps, ,
1022 Keymaps}.) The abbreviation @kbd{M-C-\} means that you type your
1023 @key{META} key, @key{CTRL} key and @key{\} key all at the same time.
1024 (On many modern keyboards the @key{META} key is labeled
1025 @key{ALT}.)
1026 Sometimes a combination like this is called a keychord, since it is
1027 similar to the way you play a chord on a piano. If your keyboard does
1028 not have a @key{META} key, the @key{ESC} key prefix is used in place
1029 of it. In this case, @kbd{M-C-\} means that you press and release your
1030 @key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1031 the same time. But usually @kbd{M-C-\} means press the @key{CTRL} key
1032 along with the key that is labeled @key{ALT} and, at the same time,
1033 press the @key{\} key.
1034
1035 In addition to typing a lone keychord, you can prefix what you type
1036 with @kbd{C-u}, which is called the `universal argument'. The
1037 @kbd{C-u} keychord passes an argument to the subsequent command.
1038 Thus, to indent a region of plain text by 6 spaces, mark the region,
1039 and then type @w{@kbd{C-u 6 M-C-\}}. (If you do not specify a number,
1040 Emacs either passes the number 4 to the command or otherwise runs the
1041 command differently than it would otherwise.) @xref{Arguments, ,
1042 Numeric Arguments, emacs, The GNU Emacs Manual}.
1043
1044 If you are reading this in Info using GNU Emacs, you can read through
1045 this whole document just by pressing the space bar, @key{SPC}.
1046 (To learn about Info, type @kbd{C-h i} and then select Info.)
1047
1048 A note on terminology: when I use the word Lisp alone, I often am
1049 referring to the various dialects of Lisp in general, but when I speak
1050 of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1051
1052 @node Thank You
1053 @unnumberedsec Thank You
1054
1055 My thanks to all who helped me with this book. My especial thanks to
1056 @r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1057 McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.
1058 Stallman}, and @w{Melissa Weisshaus}. My thanks also go to both
1059 @w{Philip Johnson} and @w{David Stampe} for their patient
1060 encouragement. My mistakes are my own.
1061
1062 @flushright
1063 Robert J. Chassell
1064 @email{bob@@gnu.org}
1065 @end flushright
1066
1067 @c ================ Beginning of main text ================
1068
1069 @c Start main text on right-hand (verso) page
1070
1071 @tex
1072 \par\vfill\supereject
1073 \headings off
1074 \ifodd\pageno
1075 \par\vfill\supereject
1076 \else
1077 \par\vfill\supereject
1078 \page\hbox{}\page
1079 \par\vfill\supereject
1080 \fi
1081 @end tex
1082
1083 @c Note: this resetting of the page number back to 1 causes TeX to gripe
1084 @c about already having seen page numbers 1-4 before (in the preface):
1085 @c pdfTeX warning (ext4): destination with the same identifier (name{1})
1086 @c has been already used, duplicate ignored
1087 @c I guess that is harmless (what happens if a later part of the text
1088 @c makes a link to something in the first 4 pages though?).
1089 @c E.g., note that the Emacs manual has a preface, but does not bother
1090 @c resetting the page numbers back to 1 after that.
1091 @iftex
1092 @headings off
1093 @evenheading @thispage @| @| @thischapter
1094 @oddheading @thissection @| @| @thispage
1095 @global@pageno = 1
1096 @end iftex
1097
1098 @node List Processing
1099 @chapter List Processing
1100
1101 To the untutored eye, Lisp is a strange programming language. In Lisp
1102 code there are parentheses everywhere. Some people even claim that
1103 the name stands for `Lots of Isolated Silly Parentheses'. But the
1104 claim is unwarranted. Lisp stands for LISt Processing, and the
1105 programming language handles @emph{lists} (and lists of lists) by
1106 putting them between parentheses. The parentheses mark the boundaries
1107 of the list. Sometimes a list is preceded by a single apostrophe or
1108 quotation mark, @samp{'}@footnote{The single apostrophe or quotation
1109 mark is an abbreviation for the function @code{quote}; you need not
1110 think about functions now; functions are defined in @ref{Making
1111 Errors, , Generate an Error Message}.} Lists are the basis of Lisp.
1112
1113 @menu
1114 * Lisp Lists:: What are lists?
1115 * Run a Program:: Any list in Lisp is a program ready to run.
1116 * Making Errors:: Generating an error message.
1117 * Names & Definitions:: Names of symbols and function definitions.
1118 * Lisp Interpreter:: What the Lisp interpreter does.
1119 * Evaluation:: Running a program.
1120 * Variables:: Returning a value from a variable.
1121 * Arguments:: Passing information to a function.
1122 * set & setq:: Setting the value of a variable.
1123 * Summary:: The major points.
1124 * Error Message Exercises::
1125 @end menu
1126
1127 @node Lisp Lists
1128 @section Lisp Lists
1129 @cindex Lisp Lists
1130
1131 In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1132 This list is preceded by a single apostrophe. It could just as well be
1133 written as follows, which looks more like the kind of list you are likely
1134 to be familiar with:
1135
1136 @smallexample
1137 @group
1138 '(rose
1139 violet
1140 daisy
1141 buttercup)
1142 @end group
1143 @end smallexample
1144
1145 @noindent
1146 The elements of this list are the names of the four different flowers,
1147 separated from each other by whitespace and surrounded by parentheses,
1148 like flowers in a field with a stone wall around them.
1149 @cindex Flowers in a field
1150
1151 @menu
1152 * Numbers Lists:: List have numbers, other lists, in them.
1153 * Lisp Atoms:: Elemental entities.
1154 * Whitespace in Lists:: Formatting lists to be readable.
1155 * Typing Lists:: How GNU Emacs helps you type lists.
1156 @end menu
1157
1158 @ifnottex
1159 @node Numbers Lists
1160 @unnumberedsubsec Numbers, Lists inside of Lists
1161 @end ifnottex
1162
1163 Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1164 This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1165 separated by whitespace.
1166
1167 In Lisp, both data and programs are represented the same way; that is,
1168 they are both lists of words, numbers, or other lists, separated by
1169 whitespace and surrounded by parentheses. (Since a program looks like
1170 data, one program may easily serve as data for another; this is a very
1171 powerful feature of Lisp.) (Incidentally, these two parenthetical
1172 remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1173 @samp{.} as punctuation marks.)
1174
1175 @need 1200
1176 Here is another list, this time with a list inside of it:
1177
1178 @smallexample
1179 '(this list has (a list inside of it))
1180 @end smallexample
1181
1182 The components of this list are the words @samp{this}, @samp{list},
1183 @samp{has}, and the list @samp{(a list inside of it)}. The interior
1184 list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1185 @samp{of}, @samp{it}.
1186
1187 @node Lisp Atoms
1188 @subsection Lisp Atoms
1189 @cindex Lisp Atoms
1190
1191 In Lisp, what we have been calling words are called @dfn{atoms}. This
1192 term comes from the historical meaning of the word atom, which means
1193 `indivisible'. As far as Lisp is concerned, the words we have been
1194 using in the lists cannot be divided into any smaller parts and still
1195 mean the same thing as part of a program; likewise with numbers and
1196 single character symbols like @samp{+}. On the other hand, unlike an
1197 ancient atom, a list can be split into parts. (@xref{car cdr & cons,
1198 , @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1199
1200 In a list, atoms are separated from each other by whitespace. They can be
1201 right next to a parenthesis.
1202
1203 @cindex @samp{empty list} defined
1204 Technically speaking, a list in Lisp consists of parentheses surrounding
1205 atoms separated by whitespace or surrounding other lists or surrounding
1206 both atoms and other lists. A list can have just one atom in it or
1207 have nothing in it at all. A list with nothing in it looks like this:
1208 @code{()}, and is called the @dfn{empty list}. Unlike anything else, an
1209 empty list is considered both an atom and a list at the same time.
1210
1211 @cindex Symbolic expressions, introduced
1212 @cindex @samp{expression} defined
1213 @cindex @samp{form} defined
1214 The printed representation of both atoms and lists are called
1215 @dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1216 The word @dfn{expression} by itself can refer to either the printed
1217 representation, or to the atom or list as it is held internally in the
1218 computer. Often, people use the term @dfn{expression}
1219 indiscriminately. (Also, in many texts, the word @dfn{form} is used
1220 as a synonym for expression.)
1221
1222 Incidentally, the atoms that make up our universe were named such when
1223 they were thought to be indivisible; but it has been found that physical
1224 atoms are not indivisible. Parts can split off an atom or it can
1225 fission into two parts of roughly equal size. Physical atoms were named
1226 prematurely, before their truer nature was found. In Lisp, certain
1227 kinds of atom, such as an array, can be separated into parts; but the
1228 mechanism for doing this is different from the mechanism for splitting a
1229 list. As far as list operations are concerned, the atoms of a list are
1230 unsplittable.
1231
1232 As in English, the meanings of the component letters of a Lisp atom
1233 are different from the meaning the letters make as a word. For
1234 example, the word for the South American sloth, the @samp{ai}, is
1235 completely different from the two words, @samp{a}, and @samp{i}.
1236
1237 There are many kinds of atom in nature but only a few in Lisp: for
1238 example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1239 as @samp{+}, @samp{foo}, or @samp{forward-line}. The words we have
1240 listed in the examples above are all symbols. In everyday Lisp
1241 conversation, the word ``atom'' is not often used, because programmers
1242 usually try to be more specific about what kind of atom they are dealing
1243 with. Lisp programming is mostly about symbols (and sometimes numbers)
1244 within lists. (Incidentally, the preceding three word parenthetical
1245 remark is a proper list in Lisp, since it consists of atoms, which in
1246 this case are symbols, separated by whitespace and enclosed by
1247 parentheses, without any non-Lisp punctuation.)
1248
1249 @need 1250
1250 Text between double quotation marks---even sentences or
1251 paragraphs---is also an atom. Here is an example:
1252 @cindex Text between double quotation marks
1253
1254 @smallexample
1255 '(this list includes "text between quotation marks.")
1256 @end smallexample
1257
1258 @cindex @samp{string} defined
1259 @noindent
1260 In Lisp, all of the quoted text including the punctuation mark and the
1261 blank spaces is a single atom. This kind of atom is called a
1262 @dfn{string} (for `string of characters') and is the sort of thing that
1263 is used for messages that a computer can print for a human to read.
1264 Strings are a different kind of atom than numbers or symbols and are
1265 used differently.
1266
1267 @node Whitespace in Lists
1268 @subsection Whitespace in Lists
1269 @cindex Whitespace in lists
1270
1271 @need 1200
1272 The amount of whitespace in a list does not matter. From the point of view
1273 of the Lisp language,
1274
1275 @smallexample
1276 @group
1277 '(this list
1278 looks like this)
1279 @end group
1280 @end smallexample
1281
1282 @need 800
1283 @noindent
1284 is exactly the same as this:
1285
1286 @smallexample
1287 '(this list looks like this)
1288 @end smallexample
1289
1290 Both examples show what to Lisp is the same list, the list made up of
1291 the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1292 @samp{this} in that order.
1293
1294 Extra whitespace and newlines are designed to make a list more readable
1295 by humans. When Lisp reads the expression, it gets rid of all the extra
1296 whitespace (but it needs to have at least one space between atoms in
1297 order to tell them apart.)
1298
1299 Odd as it seems, the examples we have seen cover almost all of what Lisp
1300 lists look like! Every other list in Lisp looks more or less like one
1301 of these examples, except that the list may be longer and more complex.
1302 In brief, a list is between parentheses, a string is between quotation
1303 marks, a symbol looks like a word, and a number looks like a number.
1304 (For certain situations, square brackets, dots and a few other special
1305 characters may be used; however, we will go quite far without them.)
1306
1307 @node Typing Lists
1308 @subsection GNU Emacs Helps You Type Lists
1309 @cindex Help typing lists
1310 @cindex Formatting help
1311
1312 When you type a Lisp expression in GNU Emacs using either Lisp
1313 Interaction mode or Emacs Lisp mode, you have available to you several
1314 commands to format the Lisp expression so it is easy to read. For
1315 example, pressing the @key{TAB} key automatically indents the line the
1316 cursor is on by the right amount. A command to properly indent the
1317 code in a region is customarily bound to @kbd{M-C-\}. Indentation is
1318 designed so that you can see which elements of a list belong to which
1319 list---elements of a sub-list are indented more than the elements of
1320 the enclosing list.
1321
1322 In addition, when you type a closing parenthesis, Emacs momentarily
1323 jumps the cursor back to the matching opening parenthesis, so you can
1324 see which one it is. This is very useful, since every list you type
1325 in Lisp must have its closing parenthesis match its opening
1326 parenthesis. (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1327 Manual}, for more information about Emacs's modes.)
1328
1329 @node Run a Program
1330 @section Run a Program
1331 @cindex Run a program
1332 @cindex Program, running one
1333
1334 @cindex @samp{evaluate} defined
1335 A list in Lisp---any list---is a program ready to run. If you run it
1336 (for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1337 of three things: do nothing except return to you the list itself; send
1338 you an error message; or, treat the first symbol in the list as a
1339 command to do something. (Usually, of course, it is the last of these
1340 three things that you really want!)
1341
1342 @c use code for the single apostrophe, not samp.
1343 The single apostrophe, @code{'}, that I put in front of some of the
1344 example lists in preceding sections is called a @dfn{quote}; when it
1345 precedes a list, it tells Lisp to do nothing with the list, other than
1346 take it as it is written. But if there is no quote preceding a list,
1347 the first item of the list is special: it is a command for the computer
1348 to obey. (In Lisp, these commands are called @emph{functions}.) The list
1349 @code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1350 understands that the @code{+} is an instruction to do something with the
1351 rest of the list: add the numbers that follow.
1352
1353 @need 1250
1354 If you are reading this inside of GNU Emacs in Info, here is how you can
1355 evaluate such a list: place your cursor immediately after the right
1356 hand parenthesis of the following list and then type @kbd{C-x C-e}:
1357
1358 @smallexample
1359 (+ 2 2)
1360 @end smallexample
1361
1362 @c use code for the number four, not samp.
1363 @noindent
1364 You will see the number @code{4} appear in the echo area. (In the
1365 jargon, what you have just done is ``evaluate the list.'' The echo area
1366 is the line at the bottom of the screen that displays or ``echoes''
1367 text.) Now try the same thing with a quoted list: place the cursor
1368 right after the following list and type @kbd{C-x C-e}:
1369
1370 @smallexample
1371 '(this is a quoted list)
1372 @end smallexample
1373
1374 @noindent
1375 You will see @code{(this is a quoted list)} appear in the echo area.
1376
1377 @cindex Lisp interpreter, explained
1378 @cindex Interpreter, Lisp, explained
1379 In both cases, what you are doing is giving a command to the program
1380 inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1381 interpreter a command to evaluate the expression. The name of the Lisp
1382 interpreter comes from the word for the task done by a human who comes
1383 up with the meaning of an expression---who ``interprets'' it.
1384
1385 You can also evaluate an atom that is not part of a list---one that is
1386 not surrounded by parentheses; again, the Lisp interpreter translates
1387 from the humanly readable expression to the language of the computer.
1388 But before discussing this (@pxref{Variables}), we will discuss what the
1389 Lisp interpreter does when you make an error.
1390
1391 @node Making Errors
1392 @section Generate an Error Message
1393 @cindex Generate an error message
1394 @cindex Error message generation
1395
1396 Partly so you won't worry if you do it accidentally, we will now give
1397 a command to the Lisp interpreter that generates an error message.
1398 This is a harmless activity; and indeed, we will often try to generate
1399 error messages intentionally. Once you understand the jargon, error
1400 messages can be informative. Instead of being called ``error''
1401 messages, they should be called ``help'' messages. They are like
1402 signposts to a traveler in a strange country; deciphering them can be
1403 hard, but once understood, they can point the way.
1404
1405 The error message is generated by a built-in GNU Emacs debugger. We
1406 will `enter the debugger'. You get out of the debugger by typing @code{q}.
1407
1408 What we will do is evaluate a list that is not quoted and does not
1409 have a meaningful command as its first element. Here is a list almost
1410 exactly the same as the one we just used, but without the single-quote
1411 in front of it. Position the cursor right after it and type @kbd{C-x
1412 C-e}:
1413
1414 @smallexample
1415 (this is an unquoted list)
1416 @end smallexample
1417
1418 @ignore
1419 @noindent
1420 What you see depends on which version of Emacs you are running. GNU
1421 Emacs version 22 provides more information than version 20 and before.
1422 First, the more recent result of generating an error; then the
1423 earlier, version 20 result.
1424
1425 @need 1250
1426 @noindent
1427 In GNU Emacs version 22, a @file{*Backtrace*} window will open up and
1428 you will see the following in it:
1429 @end ignore
1430
1431 A @file{*Backtrace*} window will open up and you should see the
1432 following in it:
1433
1434 @smallexample
1435 @group
1436 ---------- Buffer: *Backtrace* ----------
1437 Debugger entered--Lisp error: (void-function this)
1438 (this is an unquoted list)
1439 eval((this is an unquoted list))
1440 eval-last-sexp-1(nil)
1441 eval-last-sexp(nil)
1442 call-interactively(eval-last-sexp)
1443 ---------- Buffer: *Backtrace* ----------
1444 @end group
1445 @end smallexample
1446
1447 @need 1200
1448 @noindent
1449 Your cursor will be in this window (you may have to wait a few seconds
1450 before it becomes visible). To quit the debugger and make the
1451 debugger window go away, type:
1452
1453 @smallexample
1454 q
1455 @end smallexample
1456
1457 @noindent
1458 Please type @kbd{q} right now, so you become confident that you can
1459 get out of the debugger. Then, type @kbd{C-x C-e} again to re-enter
1460 it.
1461
1462 @cindex @samp{function} defined
1463 Based on what we already know, we can almost read this error message.
1464
1465 You read the @file{*Backtrace*} buffer from the bottom up; it tells
1466 you what Emacs did. When you typed @kbd{C-x C-e}, you made an
1467 interactive call to the command @code{eval-last-sexp}. @code{eval} is
1468 an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1469 `symbolic expression'. The command means `evaluate last symbolic
1470 expression', which is the expression just before your cursor.
1471
1472 Each line above tells you what the Lisp interpreter evaluated next.
1473 The most recent action is at the top. The buffer is called the
1474 @file{*Backtrace*} buffer because it enables you to track Emacs
1475 backwards.
1476
1477 @need 800
1478 At the top of the @file{*Backtrace*} buffer, you see the line:
1479
1480 @smallexample
1481 Debugger entered--Lisp error: (void-function this)
1482 @end smallexample
1483
1484 @noindent
1485 The Lisp interpreter tried to evaluate the first atom of the list, the
1486 word @samp{this}. It is this action that generated the error message
1487 @samp{void-function this}.
1488
1489 The message contains the words @samp{void-function} and @samp{this}.
1490
1491 @cindex @samp{function} defined
1492 The word @samp{function} was mentioned once before. It is a very
1493 important word. For our purposes, we can define it by saying that a
1494 @dfn{function} is a set of instructions to the computer that tell the
1495 computer to do something.
1496
1497 Now we can begin to understand the error message: @samp{void-function
1498 this}. The function (that is, the word @samp{this}) does not have a
1499 definition of any set of instructions for the computer to carry out.
1500
1501 The slightly odd word, @samp{void-function}, is designed to cover the
1502 way Emacs Lisp is implemented, which is that when a symbol does not
1503 have a function definition attached to it, the place that should
1504 contain the instructions is `void'.
1505
1506 On the other hand, since we were able to add 2 plus 2 successfully, by
1507 evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1508 have a set of instructions for the computer to obey and those
1509 instructions must be to add the numbers that follow the @code{+}.
1510
1511 It is possible to prevent Emacs entering the debugger in cases like
1512 this. We do not explain how to do that here, but we will mention what
1513 the result looks like, because you may encounter a similar situation
1514 if there is a bug in some Emacs code that you are using. In such
1515 cases, you will see only one line of error message; it will appear in
1516 the echo area and look like this:
1517
1518 @smallexample
1519 Symbol's function definition is void:@: this
1520 @end smallexample
1521
1522 @noindent
1523 @ignore
1524 (Also, your terminal may beep at you---some do, some don't; and others
1525 blink. This is just a device to get your attention.)
1526 @end ignore
1527 The message goes away as soon as you type a key, even just to
1528 move the cursor.
1529
1530 We know the meaning of the word @samp{Symbol}. It refers to the first
1531 atom of the list, the word @samp{this}. The word @samp{function}
1532 refers to the instructions that tell the computer what to do.
1533 (Technically, the symbol tells the computer where to find the
1534 instructions, but this is a complication we can ignore for the
1535 moment.)
1536
1537 The error message can be understood: @samp{Symbol's function
1538 definition is void:@: this}. The symbol (that is, the word
1539 @samp{this}) lacks instructions for the computer to carry out.
1540
1541 @node Names & Definitions
1542 @section Symbol Names and Function Definitions
1543 @cindex Symbol names
1544
1545 We can articulate another characteristic of Lisp based on what we have
1546 discussed so far---an important characteristic: a symbol, like
1547 @code{+}, is not itself the set of instructions for the computer to
1548 carry out. Instead, the symbol is used, perhaps temporarily, as a way
1549 of locating the definition or set of instructions. What we see is the
1550 name through which the instructions can be found. Names of people
1551 work the same way. I can be referred to as @samp{Bob}; however, I am
1552 not the letters @samp{B}, @samp{o}, @samp{b} but am, or was, the
1553 consciousness consistently associated with a particular life-form.
1554 The name is not me, but it can be used to refer to me.
1555
1556 In Lisp, one set of instructions can be attached to several names.
1557 For example, the computer instructions for adding numbers can be
1558 linked to the symbol @code{plus} as well as to the symbol @code{+}
1559 (and are in some dialects of Lisp). Among humans, I can be referred
1560 to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1561
1562 On the other hand, a symbol can have only one function definition
1563 attached to it at a time. Otherwise, the computer would be confused as
1564 to which definition to use. If this were the case among people, only
1565 one person in the world could be named @samp{Bob}. However, the function
1566 definition to which the name refers can be changed readily.
1567 (@xref{Install, , Install a Function Definition}.)
1568
1569 Since Emacs Lisp is large, it is customary to name symbols in a way
1570 that identifies the part of Emacs to which the function belongs.
1571 Thus, all the names for functions that deal with Texinfo start with
1572 @samp{texinfo-} and those for functions that deal with reading mail
1573 start with @samp{rmail-}.
1574
1575 @node Lisp Interpreter
1576 @section The Lisp Interpreter
1577 @cindex Lisp interpreter, what it does
1578 @cindex Interpreter, what it does
1579
1580 Based on what we have seen, we can now start to figure out what the
1581 Lisp interpreter does when we command it to evaluate a list.
1582 First, it looks to see whether there is a quote before the list; if
1583 there is, the interpreter just gives us the list. On the other
1584 hand, if there is no quote, the interpreter looks at the first element
1585 in the list and sees whether it has a function definition. If it does,
1586 the interpreter carries out the instructions in the function definition.
1587 Otherwise, the interpreter prints an error message.
1588
1589 This is how Lisp works. Simple. There are added complications which we
1590 will get to in a minute, but these are the fundamentals. Of course, to
1591 write Lisp programs, you need to know how to write function definitions
1592 and attach them to names, and how to do this without confusing either
1593 yourself or the computer.
1594
1595 @menu
1596 * Complications:: Variables, Special forms, Lists within.
1597 * Byte Compiling:: Specially processing code for speed.
1598 @end menu
1599
1600 @ifnottex
1601 @node Complications
1602 @unnumberedsubsec Complications
1603 @end ifnottex
1604
1605 Now, for the first complication. In addition to lists, the Lisp
1606 interpreter can evaluate a symbol that is not quoted and does not have
1607 parentheses around it. The Lisp interpreter will attempt to determine
1608 the symbol's value as a @dfn{variable}. This situation is described
1609 in the section on variables. (@xref{Variables}.)
1610
1611 @cindex Special form
1612 The second complication occurs because some functions are unusual and do
1613 not work in the usual manner. Those that don't are called @dfn{special
1614 forms}. They are used for special jobs, like defining a function, and
1615 there are not many of them. In the next few chapters, you will be
1616 introduced to several of the more important special forms.
1617
1618 The third and final complication is this: if the function that the
1619 Lisp interpreter is looking at is not a special form, and if it is part
1620 of a list, the Lisp interpreter looks to see whether the list has a list
1621 inside of it. If there is an inner list, the Lisp interpreter first
1622 figures out what it should do with the inside list, and then it works on
1623 the outside list. If there is yet another list embedded inside the
1624 inner list, it works on that one first, and so on. It always works on
1625 the innermost list first. The interpreter works on the innermost list
1626 first, to evaluate the result of that list. The result may be
1627 used by the enclosing expression.
1628
1629 Otherwise, the interpreter works left to right, from one expression to
1630 the next.
1631
1632 @node Byte Compiling
1633 @subsection Byte Compiling
1634 @cindex Byte compiling
1635
1636 One other aspect of interpreting: the Lisp interpreter is able to
1637 interpret two kinds of entity: humanly readable code, on which we will
1638 focus exclusively, and specially processed code, called @dfn{byte
1639 compiled} code, which is not humanly readable. Byte compiled code
1640 runs faster than humanly readable code.
1641
1642 You can transform humanly readable code into byte compiled code by
1643 running one of the compile commands such as @code{byte-compile-file}.
1644 Byte compiled code is usually stored in a file that ends with a
1645 @file{.elc} extension rather than a @file{.el} extension. You will
1646 see both kinds of file in the @file{emacs/lisp} directory; the files
1647 to read are those with @file{.el} extensions.
1648
1649 As a practical matter, for most things you might do to customize or
1650 extend Emacs, you do not need to byte compile; and I will not discuss
1651 the topic here. @xref{Byte Compilation, , Byte Compilation, elisp,
1652 The GNU Emacs Lisp Reference Manual}, for a full description of byte
1653 compilation.
1654
1655 @node Evaluation
1656 @section Evaluation
1657 @cindex Evaluation
1658
1659 When the Lisp interpreter works on an expression, the term for the
1660 activity is called @dfn{evaluation}. We say that the interpreter
1661 `evaluates the expression'. I've used this term several times before.
1662 The word comes from its use in everyday language, `to ascertain the
1663 value or amount of; to appraise', according to @cite{Webster's New
1664 Collegiate Dictionary}.
1665
1666 @menu
1667 * How the Interpreter Acts:: Returns and Side Effects...
1668 * Evaluating Inner Lists:: Lists within lists...
1669 @end menu
1670
1671 @ifnottex
1672 @node How the Interpreter Acts
1673 @unnumberedsubsec How the Lisp Interpreter Acts
1674 @end ifnottex
1675
1676 @cindex @samp{returned value} explained
1677 After evaluating an expression, the Lisp interpreter will most likely
1678 @dfn{return} the value that the computer produces by carrying out the
1679 instructions it found in the function definition, or perhaps it will
1680 give up on that function and produce an error message. (The interpreter
1681 may also find itself tossed, so to speak, to a different function or it
1682 may attempt to repeat continually what it is doing for ever and ever in
1683 what is called an `infinite loop'. These actions are less common; and
1684 we can ignore them.) Most frequently, the interpreter returns a value.
1685
1686 @cindex @samp{side effect} defined
1687 At the same time the interpreter returns a value, it may do something
1688 else as well, such as move a cursor or copy a file; this other kind of
1689 action is called a @dfn{side effect}. Actions that we humans think are
1690 important, such as printing results, are often ``side effects'' to the
1691 Lisp interpreter. The jargon can sound peculiar, but it turns out that
1692 it is fairly easy to learn to use side effects.
1693
1694 In summary, evaluating a symbolic expression most commonly causes the
1695 Lisp interpreter to return a value and perhaps carry out a side effect;
1696 or else produce an error.
1697
1698 @node Evaluating Inner Lists
1699 @subsection Evaluating Inner Lists
1700 @cindex Inner list evaluation
1701 @cindex Evaluating inner lists
1702
1703 If evaluation applies to a list that is inside another list, the outer
1704 list may use the value returned by the first evaluation as information
1705 when the outer list is evaluated. This explains why inner expressions
1706 are evaluated first: the values they return are used by the outer
1707 expressions.
1708
1709 @need 1250
1710 We can investigate this process by evaluating another addition example.
1711 Place your cursor after the following expression and type @kbd{C-x C-e}:
1712
1713 @smallexample
1714 (+ 2 (+ 3 3))
1715 @end smallexample
1716
1717 @noindent
1718 The number 8 will appear in the echo area.
1719
1720 What happens is that the Lisp interpreter first evaluates the inner
1721 expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1722 evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1723 returns the value 8. Since there are no more enclosing expressions to
1724 evaluate, the interpreter prints that value in the echo area.
1725
1726 Now it is easy to understand the name of the command invoked by the
1727 keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}. The
1728 letters @code{sexp} are an abbreviation for `symbolic expression', and
1729 @code{eval} is an abbreviation for `evaluate'. The command means
1730 `evaluate last symbolic expression'.
1731
1732 As an experiment, you can try evaluating the expression by putting the
1733 cursor at the beginning of the next line immediately following the
1734 expression, or inside the expression.
1735
1736 @need 800
1737 Here is another copy of the expression:
1738
1739 @smallexample
1740 (+ 2 (+ 3 3))
1741 @end smallexample
1742
1743 @noindent
1744 If you place the cursor at the beginning of the blank line that
1745 immediately follows the expression and type @kbd{C-x C-e}, you will
1746 still get the value 8 printed in the echo area. Now try putting the
1747 cursor inside the expression. If you put it right after the next to
1748 last parenthesis (so it appears to sit on top of the last parenthesis),
1749 you will get a 6 printed in the echo area! This is because the command
1750 evaluates the expression @code{(+ 3 3)}.
1751
1752 Now put the cursor immediately after a number. Type @kbd{C-x C-e} and
1753 you will get the number itself. In Lisp, if you evaluate a number, you
1754 get the number itself---this is how numbers differ from symbols. If you
1755 evaluate a list starting with a symbol like @code{+}, you will get a
1756 value returned that is the result of the computer carrying out the
1757 instructions in the function definition attached to that name. If a
1758 symbol by itself is evaluated, something different happens, as we will
1759 see in the next section.
1760
1761 @node Variables
1762 @section Variables
1763 @cindex Variables
1764
1765 In Emacs Lisp, a symbol can have a value attached to it just as it can
1766 have a function definition attached to it. The two are different.
1767 The function definition is a set of instructions that a computer will
1768 obey. A value, on the other hand, is something, such as number or a
1769 name, that can vary (which is why such a symbol is called a variable).
1770 The value of a symbol can be any expression in Lisp, such as a symbol,
1771 number, list, or string. A symbol that has a value is often called a
1772 @dfn{variable}.
1773
1774 A symbol can have both a function definition and a value attached to
1775 it at the same time. Or it can have just one or the other.
1776 The two are separate. This is somewhat similar
1777 to the way the name Cambridge can refer to the city in Massachusetts
1778 and have some information attached to the name as well, such as
1779 ``great programming center''.
1780
1781 @ignore
1782 (Incidentally, in Emacs Lisp, a symbol can have two
1783 other things attached to it, too: a property list and a documentation
1784 string; these are discussed later.)
1785 @end ignore
1786
1787 Another way to think about this is to imagine a symbol as being a chest
1788 of drawers. The function definition is put in one drawer, the value in
1789 another, and so on. What is put in the drawer holding the value can be
1790 changed without affecting the contents of the drawer holding the
1791 function definition, and vice-verse.
1792
1793 @menu
1794 * fill-column Example::
1795 * Void Function:: The error message for a symbol
1796 without a function.
1797 * Void Variable:: The error message for a symbol without a value.
1798 @end menu
1799
1800 @ifnottex
1801 @node fill-column Example
1802 @unnumberedsubsec @code{fill-column}, an Example Variable
1803 @end ifnottex
1804
1805 @findex fill-column, @r{an example variable}
1806 @cindex Example variable, @code{fill-column}
1807 @cindex Variable, example of, @code{fill-column}
1808 The variable @code{fill-column} illustrates a symbol with a value
1809 attached to it: in every GNU Emacs buffer, this symbol is set to some
1810 value, usually 72 or 70, but sometimes to some other value. To find the
1811 value of this symbol, evaluate it by itself. If you are reading this in
1812 Info inside of GNU Emacs, you can do this by putting the cursor after
1813 the symbol and typing @kbd{C-x C-e}:
1814
1815 @smallexample
1816 fill-column
1817 @end smallexample
1818
1819 @noindent
1820 After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1821 area. This is the value for which @code{fill-column} is set for me as I
1822 write this. It may be different for you in your Info buffer. Notice
1823 that the value returned as a variable is printed in exactly the same way
1824 as the value returned by a function carrying out its instructions. From
1825 the point of view of the Lisp interpreter, a value returned is a value
1826 returned. What kind of expression it came from ceases to matter once
1827 the value is known.
1828
1829 A symbol can have any value attached to it or, to use the jargon, we can
1830 @dfn{bind} the variable to a value: to a number, such as 72; to a
1831 string, @code{"such as this"}; to a list, such as @code{(spruce pine
1832 oak)}; we can even bind a variable to a function definition.
1833
1834 A symbol can be bound to a value in several ways. @xref{set & setq, ,
1835 Setting the Value of a Variable}, for information about one way to do
1836 this.
1837
1838 @node Void Function
1839 @subsection Error Message for a Symbol Without a Function
1840 @cindex Symbol without function error
1841 @cindex Error for symbol without function
1842
1843 When we evaluated @code{fill-column} to find its value as a variable,
1844 we did not place parentheses around the word. This is because we did
1845 not intend to use it as a function name.
1846
1847 If @code{fill-column} were the first or only element of a list, the
1848 Lisp interpreter would attempt to find the function definition
1849 attached to it. But @code{fill-column} has no function definition.
1850 Try evaluating this:
1851
1852 @smallexample
1853 (fill-column)
1854 @end smallexample
1855
1856 @need 1250
1857 @noindent
1858 You will create a @file{*Backtrace*} buffer that says:
1859
1860 @smallexample
1861 @group
1862 ---------- Buffer: *Backtrace* ----------
1863 Debugger entered--Lisp error: (void-function fill-column)
1864 (fill-column)
1865 eval((fill-column))
1866 eval-last-sexp-1(nil)
1867 eval-last-sexp(nil)
1868 call-interactively(eval-last-sexp)
1869 ---------- Buffer: *Backtrace* ----------
1870 @end group
1871 @end smallexample
1872
1873 @noindent
1874 (Remember, to quit the debugger and make the debugger window go away,
1875 type @kbd{q} in the @file{*Backtrace*} buffer.)
1876
1877 @ignore
1878 @need 800
1879 In GNU Emacs 20 and before, you will produce an error message that says:
1880
1881 @smallexample
1882 Symbol's function definition is void:@: fill-column
1883 @end smallexample
1884
1885 @noindent
1886 (The message will go away as soon as you move the cursor or type
1887 another key.)
1888 @end ignore
1889
1890 @node Void Variable
1891 @subsection Error Message for a Symbol Without a Value
1892 @cindex Symbol without value error
1893 @cindex Error for symbol without value
1894
1895 If you attempt to evaluate a symbol that does not have a value bound to
1896 it, you will receive an error message. You can see this by
1897 experimenting with our 2 plus 2 addition. In the following expression,
1898 put your cursor right after the @code{+}, before the first number 2,
1899 type @kbd{C-x C-e}:
1900
1901 @smallexample
1902 (+ 2 2)
1903 @end smallexample
1904
1905 @need 1500
1906 @noindent
1907 In GNU Emacs 22, you will create a @file{*Backtrace*} buffer that
1908 says:
1909
1910 @smallexample
1911 @group
1912 ---------- Buffer: *Backtrace* ----------
1913 Debugger entered--Lisp error: (void-variable +)
1914 eval(+)
1915 eval-last-sexp-1(nil)
1916 eval-last-sexp(nil)
1917 call-interactively(eval-last-sexp)
1918 ---------- Buffer: *Backtrace* ----------
1919 @end group
1920 @end smallexample
1921
1922 @noindent
1923 (Again, you can quit the debugger by
1924 typing @kbd{q} in the @file{*Backtrace*} buffer.)
1925
1926 This backtrace is different from the very first error message we saw,
1927 which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1928 In this case, the function does not have a value as a variable; while
1929 in the other error message, the function (the word `this') did not
1930 have a definition.
1931
1932 In this experiment with the @code{+}, what we did was cause the Lisp
1933 interpreter to evaluate the @code{+} and look for the value of the
1934 variable instead of the function definition. We did this by placing the
1935 cursor right after the symbol rather than after the parenthesis of the
1936 enclosing list as we did before. As a consequence, the Lisp interpreter
1937 evaluated the preceding s-expression, which in this case was
1938 @code{+} by itself.
1939
1940 Since @code{+} does not have a value bound to it, just the function
1941 definition, the error message reported that the symbol's value as a
1942 variable was void.
1943
1944 @ignore
1945 @need 800
1946 In GNU Emacs version 20 and before, your error message will say:
1947
1948 @example
1949 Symbol's value as variable is void:@: +
1950 @end example
1951
1952 @noindent
1953 The meaning is the same as in GNU Emacs 22.
1954 @end ignore
1955
1956 @node Arguments
1957 @section Arguments
1958 @cindex Arguments
1959 @cindex Passing information to functions
1960
1961 To see how information is passed to functions, let's look again at
1962 our old standby, the addition of two plus two. In Lisp, this is written
1963 as follows:
1964
1965 @smallexample
1966 (+ 2 2)
1967 @end smallexample
1968
1969 If you evaluate this expression, the number 4 will appear in your echo
1970 area. What the Lisp interpreter does is add the numbers that follow
1971 the @code{+}.
1972
1973 @cindex @samp{argument} defined
1974 The numbers added by @code{+} are called the @dfn{arguments} of the
1975 function @code{+}. These numbers are the information that is given to
1976 or @dfn{passed} to the function.
1977
1978 The word `argument' comes from the way it is used in mathematics and
1979 does not refer to a disputation between two people; instead it refers to
1980 the information presented to the function, in this case, to the
1981 @code{+}. In Lisp, the arguments to a function are the atoms or lists
1982 that follow the function. The values returned by the evaluation of
1983 these atoms or lists are passed to the function. Different functions
1984 require different numbers of arguments; some functions require none at
1985 all.@footnote{It is curious to track the path by which the word `argument'
1986 came to have two different meanings, one in mathematics and the other in
1987 everyday English. According to the @cite{Oxford English Dictionary},
1988 the word derives from the Latin for @samp{to make clear, prove}; thus it
1989 came to mean, by one thread of derivation, `the evidence offered as
1990 proof', which is to say, `the information offered', which led to its
1991 meaning in Lisp. But in the other thread of derivation, it came to mean
1992 `to assert in a manner against which others may make counter
1993 assertions', which led to the meaning of the word as a disputation.
1994 (Note here that the English word has two different definitions attached
1995 to it at the same time. By contrast, in Emacs Lisp, a symbol cannot
1996 have two different function definitions at the same time.)}
1997
1998 @menu
1999 * Data types:: Types of data passed to a function.
2000 * Args as Variable or List:: An argument can be the value
2001 of a variable or list.
2002 * Variable Number of Arguments:: Some functions may take a
2003 variable number of arguments.
2004 * Wrong Type of Argument:: Passing an argument of the wrong type
2005 to a function.
2006 * message:: A useful function for sending messages.
2007 @end menu
2008
2009 @node Data types
2010 @subsection Arguments' Data Types
2011 @cindex Data types
2012 @cindex Types of data
2013 @cindex Arguments' data types
2014
2015 The type of data that should be passed to a function depends on what
2016 kind of information it uses. The arguments to a function such as
2017 @code{+} must have values that are numbers, since @code{+} adds numbers.
2018 Other functions use different kinds of data for their arguments.
2019
2020 @need 1250
2021 @findex concat
2022 For example, the @code{concat} function links together or unites two or
2023 more strings of text to produce a string. The arguments are strings.
2024 Concatenating the two character strings @code{abc}, @code{def} produces
2025 the single string @code{abcdef}. This can be seen by evaluating the
2026 following:
2027
2028 @smallexample
2029 (concat "abc" "def")
2030 @end smallexample
2031
2032 @noindent
2033 The value produced by evaluating this expression is @code{"abcdef"}.
2034
2035 A function such as @code{substring} uses both a string and numbers as
2036 arguments. The function returns a part of the string, a substring of
2037 the first argument. This function takes three arguments. Its first
2038 argument is the string of characters, the second and third arguments are
2039 numbers that indicate the beginning and end of the substring. The
2040 numbers are a count of the number of characters (including spaces and
2041 punctuation) from the beginning of the string.
2042
2043 @need 800
2044 For example, if you evaluate the following:
2045
2046 @smallexample
2047 (substring "The quick brown fox jumped." 16 19)
2048 @end smallexample
2049
2050 @noindent
2051 you will see @code{"fox"} appear in the echo area. The arguments are the
2052 string and the two numbers.
2053
2054 Note that the string passed to @code{substring} is a single atom even
2055 though it is made up of several words separated by spaces. Lisp counts
2056 everything between the two quotation marks as part of the string,
2057 including the spaces. You can think of the @code{substring} function as
2058 a kind of `atom smasher' since it takes an otherwise indivisible atom
2059 and extracts a part. However, @code{substring} is only able to extract
2060 a substring from an argument that is a string, not from another type of
2061 atom such as a number or symbol.
2062
2063 @node Args as Variable or List
2064 @subsection An Argument as the Value of a Variable or List
2065
2066 An argument can be a symbol that returns a value when it is evaluated.
2067 For example, when the symbol @code{fill-column} by itself is evaluated,
2068 it returns a number. This number can be used in an addition.
2069
2070 @need 1250
2071 Position the cursor after the following expression and type @kbd{C-x
2072 C-e}:
2073
2074 @smallexample
2075 (+ 2 fill-column)
2076 @end smallexample
2077
2078 @noindent
2079 The value will be a number two more than what you get by evaluating
2080 @code{fill-column} alone. For me, this is 74, because my value of
2081 @code{fill-column} is 72.
2082
2083 As we have just seen, an argument can be a symbol that returns a value
2084 when evaluated. In addition, an argument can be a list that returns a
2085 value when it is evaluated. For example, in the following expression,
2086 the arguments to the function @code{concat} are the strings
2087 @w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2088 @code{(number-to-string (+ 2 fill-column))}.
2089
2090 @c For GNU Emacs 22, need number-to-string
2091 @smallexample
2092 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2093 @end smallexample
2094
2095 @noindent
2096 If you evaluate this expression---and if, as with my Emacs,
2097 @code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2098 appear in the echo area. (Note that you must put spaces after the
2099 word @samp{The} and before the word @samp{red} so they will appear in
2100 the final string. The function @code{number-to-string} converts the
2101 integer that the addition function returns to a string.
2102 @code{number-to-string} is also known as @code{int-to-string}.)
2103
2104 @node Variable Number of Arguments
2105 @subsection Variable Number of Arguments
2106 @cindex Variable number of arguments
2107 @cindex Arguments, variable number of
2108
2109 Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2110 number of arguments. (The @code{*} is the symbol for multiplication.)
2111 This can be seen by evaluating each of the following expressions in
2112 the usual way. What you will see in the echo area is printed in this
2113 text after @samp{@result{}}, which you may read as `evaluates to'.
2114
2115 @need 1250
2116 In the first set, the functions have no arguments:
2117
2118 @smallexample
2119 @group
2120 (+) @result{} 0
2121
2122 (*) @result{} 1
2123 @end group
2124 @end smallexample
2125
2126 @need 1250
2127 In this set, the functions have one argument each:
2128
2129 @smallexample
2130 @group
2131 (+ 3) @result{} 3
2132
2133 (* 3) @result{} 3
2134 @end group
2135 @end smallexample
2136
2137 @need 1250
2138 In this set, the functions have three arguments each:
2139
2140 @smallexample
2141 @group
2142 (+ 3 4 5) @result{} 12
2143
2144 (* 3 4 5) @result{} 60
2145 @end group
2146 @end smallexample
2147
2148 @node Wrong Type of Argument
2149 @subsection Using the Wrong Type Object as an Argument
2150 @cindex Wrong type of argument
2151 @cindex Argument, wrong type of
2152
2153 When a function is passed an argument of the wrong type, the Lisp
2154 interpreter produces an error message. For example, the @code{+}
2155 function expects the values of its arguments to be numbers. As an
2156 experiment we can pass it the quoted symbol @code{hello} instead of a
2157 number. Position the cursor after the following expression and type
2158 @kbd{C-x C-e}:
2159
2160 @smallexample
2161 (+ 2 'hello)
2162 @end smallexample
2163
2164 @noindent
2165 When you do this you will generate an error message. What has happened
2166 is that @code{+} has tried to add the 2 to the value returned by
2167 @code{'hello}, but the value returned by @code{'hello} is the symbol
2168 @code{hello}, not a number. Only numbers can be added. So @code{+}
2169 could not carry out its addition.
2170
2171 @need 1250
2172 You will create and enter a @file{*Backtrace*} buffer that says:
2173
2174 @noindent
2175 @smallexample
2176 @group
2177 ---------- Buffer: *Backtrace* ----------
2178 Debugger entered--Lisp error:
2179 (wrong-type-argument number-or-marker-p hello)
2180 +(2 hello)
2181 eval((+ 2 (quote hello)))
2182 eval-last-sexp-1(nil)
2183 eval-last-sexp(nil)
2184 call-interactively(eval-last-sexp)
2185 ---------- Buffer: *Backtrace* ----------
2186 @end group
2187 @end smallexample
2188
2189 @need 1250
2190 As usual, the error message tries to be helpful and makes sense after you
2191 learn how to read it.@footnote{@code{(quote hello)} is an expansion of
2192 the abbreviation @code{'hello}.}
2193
2194 The first part of the error message is straightforward; it says
2195 @samp{wrong type argument}. Next comes the mysterious jargon word
2196 @w{@samp{number-or-marker-p}}. This word is trying to tell you what
2197 kind of argument the @code{+} expected.
2198
2199 The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2200 trying to determine whether the information presented it (the value of
2201 the argument) is a number or a marker (a special object representing a
2202 buffer position). What it does is test to see whether the @code{+} is
2203 being given numbers to add. It also tests to see whether the
2204 argument is something called a marker, which is a specific feature of
2205 Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
2206 When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2207 its position is kept as a marker. The mark can be considered a
2208 number---the number of characters the location is from the beginning
2209 of the buffer.) In Emacs Lisp, @code{+} can be used to add the
2210 numeric value of marker positions as numbers.
2211
2212 The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2213 practice started in the early days of Lisp programming. The @samp{p}
2214 stands for `predicate'. In the jargon used by the early Lisp
2215 researchers, a predicate refers to a function to determine whether some
2216 property is true or false. So the @samp{p} tells us that
2217 @code{number-or-marker-p} is the name of a function that determines
2218 whether it is true or false that the argument supplied is a number or
2219 a marker. Other Lisp symbols that end in @samp{p} include @code{zerop},
2220 a function that tests whether its argument has the value of zero, and
2221 @code{listp}, a function that tests whether its argument is a list.
2222
2223 Finally, the last part of the error message is the symbol @code{hello}.
2224 This is the value of the argument that was passed to @code{+}. If the
2225 addition had been passed the correct type of object, the value passed
2226 would have been a number, such as 37, rather than a symbol like
2227 @code{hello}. But then you would not have got the error message.
2228
2229 @ignore
2230 @need 1250
2231 In GNU Emacs version 20 and before, the echo area displays an error
2232 message that says:
2233
2234 @smallexample
2235 Wrong type argument:@: number-or-marker-p, hello
2236 @end smallexample
2237
2238 This says, in different words, the same as the top line of the
2239 @file{*Backtrace*} buffer.
2240 @end ignore
2241
2242 @node message
2243 @subsection The @code{message} Function
2244 @findex message
2245
2246 Like @code{+}, the @code{message} function takes a variable number of
2247 arguments. It is used to send messages to the user and is so useful
2248 that we will describe it here.
2249
2250 @need 1250
2251 A message is printed in the echo area. For example, you can print a
2252 message in your echo area by evaluating the following list:
2253
2254 @smallexample
2255 (message "This message appears in the echo area!")
2256 @end smallexample
2257
2258 The whole string between double quotation marks is a single argument
2259 and is printed @i{in toto}. (Note that in this example, the message
2260 itself will appear in the echo area within double quotes; that is
2261 because you see the value returned by the @code{message} function. In
2262 most uses of @code{message} in programs that you write, the text will
2263 be printed in the echo area as a side-effect, without the quotes.
2264 @xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2265 detail}, for an example of this.)
2266
2267 However, if there is a @samp{%s} in the quoted string of characters, the
2268 @code{message} function does not print the @samp{%s} as such, but looks
2269 to the argument that follows the string. It evaluates the second
2270 argument and prints the value at the location in the string where the
2271 @samp{%s} is.
2272
2273 @need 1250
2274 You can see this by positioning the cursor after the following
2275 expression and typing @kbd{C-x C-e}:
2276
2277 @smallexample
2278 (message "The name of this buffer is: %s." (buffer-name))
2279 @end smallexample
2280
2281 @noindent
2282 In Info, @code{"The name of this buffer is: *info*."} will appear in the
2283 echo area. The function @code{buffer-name} returns the name of the
2284 buffer as a string, which the @code{message} function inserts in place
2285 of @code{%s}.
2286
2287 To print a value as an integer, use @samp{%d} in the same way as
2288 @samp{%s}. For example, to print a message in the echo area that
2289 states the value of the @code{fill-column}, evaluate the following:
2290
2291 @smallexample
2292 (message "The value of fill-column is %d." fill-column)
2293 @end smallexample
2294
2295 @noindent
2296 On my system, when I evaluate this list, @code{"The value of
2297 fill-column is 72."} appears in my echo area@footnote{Actually, you
2298 can use @code{%s} to print a number. It is non-specific. @code{%d}
2299 prints only the part of a number left of a decimal point, and not
2300 anything that is not a number.}.
2301
2302 If there is more than one @samp{%s} in the quoted string, the value of
2303 the first argument following the quoted string is printed at the
2304 location of the first @samp{%s} and the value of the second argument is
2305 printed at the location of the second @samp{%s}, and so on.
2306
2307 @need 1250
2308 For example, if you evaluate the following,
2309
2310 @smallexample
2311 @group
2312 (message "There are %d %s in the office!"
2313 (- fill-column 14) "pink elephants")
2314 @end group
2315 @end smallexample
2316
2317 @noindent
2318 a rather whimsical message will appear in your echo area. On my system
2319 it says, @code{"There are 58 pink elephants in the office!"}.
2320
2321 The expression @code{(- fill-column 14)} is evaluated and the resulting
2322 number is inserted in place of the @samp{%d}; and the string in double
2323 quotes, @code{"pink elephants"}, is treated as a single argument and
2324 inserted in place of the @samp{%s}. (That is to say, a string between
2325 double quotes evaluates to itself, like a number.)
2326
2327 Finally, here is a somewhat complex example that not only illustrates
2328 the computation of a number, but also shows how you can use an
2329 expression within an expression to generate the text that is substituted
2330 for @samp{%s}:
2331
2332 @smallexample
2333 @group
2334 (message "He saw %d %s"
2335 (- fill-column 32)
2336 (concat "red "
2337 (substring
2338 "The quick brown foxes jumped." 16 21)
2339 " leaping."))
2340 @end group
2341 @end smallexample
2342
2343 In this example, @code{message} has three arguments: the string,
2344 @code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2345 the expression beginning with the function @code{concat}. The value
2346 resulting from the evaluation of @code{(- fill-column 32)} is inserted
2347 in place of the @samp{%d}; and the value returned by the expression
2348 beginning with @code{concat} is inserted in place of the @samp{%s}.
2349
2350 When your fill column is 70 and you evaluate the expression, the
2351 message @code{"He saw 38 red foxes leaping."} appears in your echo
2352 area.
2353
2354 @node set & setq
2355 @section Setting the Value of a Variable
2356 @cindex Variable, setting value
2357 @cindex Setting value of variable
2358
2359 @cindex @samp{bind} defined
2360 There are several ways by which a variable can be given a value. One of
2361 the ways is to use either the function @code{set} or the function
2362 @code{setq}. Another way is to use @code{let} (@pxref{let}). (The
2363 jargon for this process is to @dfn{bind} a variable to a value.)
2364
2365 The following sections not only describe how @code{set} and @code{setq}
2366 work but also illustrate how arguments are passed.
2367
2368 @menu
2369 * Using set:: Setting values.
2370 * Using setq:: Setting a quoted value.
2371 * Counting:: Using @code{setq} to count.
2372 @end menu
2373
2374 @node Using set
2375 @subsection Using @code{set}
2376 @findex set
2377
2378 To set the value of the symbol @code{flowers} to the list @code{'(rose
2379 violet daisy buttercup)}, evaluate the following expression by
2380 positioning the cursor after the expression and typing @kbd{C-x C-e}.
2381
2382 @smallexample
2383 (set 'flowers '(rose violet daisy buttercup))
2384 @end smallexample
2385
2386 @noindent
2387 The list @code{(rose violet daisy buttercup)} will appear in the echo
2388 area. This is what is @emph{returned} by the @code{set} function. As a
2389 side effect, the symbol @code{flowers} is bound to the list; that is,
2390 the symbol @code{flowers}, which can be viewed as a variable, is given
2391 the list as its value. (This process, by the way, illustrates how a
2392 side effect to the Lisp interpreter, setting the value, can be the
2393 primary effect that we humans are interested in. This is because every
2394 Lisp function must return a value if it does not get an error, but it
2395 will only have a side effect if it is designed to have one.)
2396
2397 After evaluating the @code{set} expression, you can evaluate the symbol
2398 @code{flowers} and it will return the value you just set. Here is the
2399 symbol. Place your cursor after it and type @kbd{C-x C-e}.
2400
2401 @smallexample
2402 flowers
2403 @end smallexample
2404
2405 @noindent
2406 When you evaluate @code{flowers}, the list
2407 @code{(rose violet daisy buttercup)} appears in the echo area.
2408
2409 Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2410 in front of it, what you will see in the echo area is the symbol itself,
2411 @code{flowers}. Here is the quoted symbol, so you can try this:
2412
2413 @smallexample
2414 'flowers
2415 @end smallexample
2416
2417 Note also, that when you use @code{set}, you need to quote both
2418 arguments to @code{set}, unless you want them evaluated. Since we do
2419 not want either argument evaluated, neither the variable
2420 @code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2421 are quoted. (When you use @code{set} without quoting its first
2422 argument, the first argument is evaluated before anything else is
2423 done. If you did this and @code{flowers} did not have a value
2424 already, you would get an error message that the @samp{Symbol's value
2425 as variable is void}; on the other hand, if @code{flowers} did return
2426 a value after it was evaluated, the @code{set} would attempt to set
2427 the value that was returned. There are situations where this is the
2428 right thing for the function to do; but such situations are rare.)
2429
2430 @node Using setq
2431 @subsection Using @code{setq}
2432 @findex setq
2433
2434 As a practical matter, you almost always quote the first argument to
2435 @code{set}. The combination of @code{set} and a quoted first argument
2436 is so common that it has its own name: the special form @code{setq}.
2437 This special form is just like @code{set} except that the first argument
2438 is quoted automatically, so you don't need to type the quote mark
2439 yourself. Also, as an added convenience, @code{setq} permits you to set
2440 several different variables to different values, all in one expression.
2441
2442 To set the value of the variable @code{carnivores} to the list
2443 @code{'(lion tiger leopard)} using @code{setq}, the following expression
2444 is used:
2445
2446 @smallexample
2447 (setq carnivores '(lion tiger leopard))
2448 @end smallexample
2449
2450 @noindent
2451 This is exactly the same as using @code{set} except the first argument
2452 is automatically quoted by @code{setq}. (The @samp{q} in @code{setq}
2453 means @code{quote}.)
2454
2455 @need 1250
2456 With @code{set}, the expression would look like this:
2457
2458 @smallexample
2459 (set 'carnivores '(lion tiger leopard))
2460 @end smallexample
2461
2462 Also, @code{setq} can be used to assign different values to
2463 different variables. The first argument is bound to the value
2464 of the second argument, the third argument is bound to the value of the
2465 fourth argument, and so on. For example, you could use the following to
2466 assign a list of trees to the symbol @code{trees} and a list of herbivores
2467 to the symbol @code{herbivores}:
2468
2469 @smallexample
2470 @group
2471 (setq trees '(pine fir oak maple)
2472 herbivores '(gazelle antelope zebra))
2473 @end group
2474 @end smallexample
2475
2476 @noindent
2477 (The expression could just as well have been on one line, but it might
2478 not have fit on a page; and humans find it easier to read nicely
2479 formatted lists.)
2480
2481 Although I have been using the term `assign', there is another way of
2482 thinking about the workings of @code{set} and @code{setq}; and that is to
2483 say that @code{set} and @code{setq} make the symbol @emph{point} to the
2484 list. This latter way of thinking is very common and in forthcoming
2485 chapters we shall come upon at least one symbol that has `pointer' as
2486 part of its name. The name is chosen because the symbol has a value,
2487 specifically a list, attached to it; or, expressed another way,
2488 the symbol is set to ``point'' to the list.
2489
2490 @node Counting
2491 @subsection Counting
2492 @cindex Counting
2493
2494 Here is an example that shows how to use @code{setq} in a counter. You
2495 might use this to count how many times a part of your program repeats
2496 itself. First set a variable to zero; then add one to the number each
2497 time the program repeats itself. To do this, you need a variable that
2498 serves as a counter, and two expressions: an initial @code{setq}
2499 expression that sets the counter variable to zero; and a second
2500 @code{setq} expression that increments the counter each time it is
2501 evaluated.
2502
2503 @smallexample
2504 @group
2505 (setq counter 0) ; @r{Let's call this the initializer.}
2506
2507 (setq counter (+ counter 1)) ; @r{This is the incrementer.}
2508
2509 counter ; @r{This is the counter.}
2510 @end group
2511 @end smallexample
2512
2513 @noindent
2514 (The text following the @samp{;} are comments. @xref{Change a
2515 defun, , Change a Function Definition}.)
2516
2517 If you evaluate the first of these expressions, the initializer,
2518 @code{(setq counter 0)}, and then evaluate the third expression,
2519 @code{counter}, the number @code{0} will appear in the echo area. If
2520 you then evaluate the second expression, the incrementer, @code{(setq
2521 counter (+ counter 1))}, the counter will get the value 1. So if you
2522 again evaluate @code{counter}, the number @code{1} will appear in the
2523 echo area. Each time you evaluate the second expression, the value of
2524 the counter will be incremented.
2525
2526 When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2527 the Lisp interpreter first evaluates the innermost list; this is the
2528 addition. In order to evaluate this list, it must evaluate the variable
2529 @code{counter} and the number @code{1}. When it evaluates the variable
2530 @code{counter}, it receives its current value. It passes this value and
2531 the number @code{1} to the @code{+} which adds them together. The sum
2532 is then returned as the value of the inner list and passed to the
2533 @code{setq} which sets the variable @code{counter} to this new value.
2534 Thus, the value of the variable, @code{counter}, is changed.
2535
2536 @node Summary
2537 @section Summary
2538
2539 Learning Lisp is like climbing a hill in which the first part is the
2540 steepest. You have now climbed the most difficult part; what remains
2541 becomes easier as you progress onwards.
2542
2543 @need 1000
2544 In summary,
2545
2546 @itemize @bullet
2547
2548 @item
2549 Lisp programs are made up of expressions, which are lists or single atoms.
2550
2551 @item
2552 Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2553 surrounded by parentheses. A list can be empty.
2554
2555 @item
2556 Atoms are multi-character symbols, like @code{forward-paragraph}, single
2557 character symbols like @code{+}, strings of characters between double
2558 quotation marks, or numbers.
2559
2560 @item
2561 A number evaluates to itself.
2562
2563 @item
2564 A string between double quotes also evaluates to itself.
2565
2566 @item
2567 When you evaluate a symbol by itself, its value is returned.
2568
2569 @item
2570 When you evaluate a list, the Lisp interpreter looks at the first symbol
2571 in the list and then at the function definition bound to that symbol.
2572 Then the instructions in the function definition are carried out.
2573
2574 @item
2575 A single quotation mark,
2576 @ifinfo
2577 '
2578 @end ifinfo
2579 @ifnotinfo
2580 @code{'}
2581 @end ifnotinfo
2582 , tells the Lisp interpreter that it should
2583 return the following expression as written, and not evaluate it as it
2584 would if the quote were not there.
2585
2586 @item
2587 Arguments are the information passed to a function. The arguments to a
2588 function are computed by evaluating the rest of the elements of the list
2589 of which the function is the first element.
2590
2591 @item
2592 A function always returns a value when it is evaluated (unless it gets
2593 an error); in addition, it may also carry out some action called a
2594 ``side effect''. In many cases, a function's primary purpose is to
2595 create a side effect.
2596 @end itemize
2597
2598 @node Error Message Exercises
2599 @section Exercises
2600
2601 A few simple exercises:
2602
2603 @itemize @bullet
2604 @item
2605 Generate an error message by evaluating an appropriate symbol that is
2606 not within parentheses.
2607
2608 @item
2609 Generate an error message by evaluating an appropriate symbol that is
2610 between parentheses.
2611
2612 @item
2613 Create a counter that increments by two rather than one.
2614
2615 @item
2616 Write an expression that prints a message in the echo area when
2617 evaluated.
2618 @end itemize
2619
2620 @node Practicing Evaluation
2621 @chapter Practicing Evaluation
2622 @cindex Practicing evaluation
2623 @cindex Evaluation practice
2624
2625 Before learning how to write a function definition in Emacs Lisp, it is
2626 useful to spend a little time evaluating various expressions that have
2627 already been written. These expressions will be lists with the
2628 functions as their first (and often only) element. Since some of the
2629 functions associated with buffers are both simple and interesting, we
2630 will start with those. In this section, we will evaluate a few of
2631 these. In another section, we will study the code of several other
2632 buffer-related functions, to see how they were written.
2633
2634 @menu
2635 * How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
2636 causes evaluation.
2637 * Buffer Names:: Buffers and files are different.
2638 * Getting Buffers:: Getting a buffer itself, not merely its name.
2639 * Switching Buffers:: How to change to another buffer.
2640 * Buffer Size & Locations:: Where point is located and the size of
2641 the buffer.
2642 * Evaluation Exercise::
2643 @end menu
2644
2645 @ifnottex
2646 @node How to Evaluate
2647 @unnumberedsec How to Evaluate
2648 @end ifnottex
2649
2650 @i{Whenever you give an editing command} to Emacs Lisp, such as the
2651 command to move the cursor or to scroll the screen, @i{you are evaluating
2652 an expression,} the first element of which is a function. @i{This is
2653 how Emacs works.}
2654
2655 @cindex @samp{interactive function} defined
2656 @cindex @samp{command} defined
2657 When you type keys, you cause the Lisp interpreter to evaluate an
2658 expression and that is how you get your results. Even typing plain text
2659 involves evaluating an Emacs Lisp function, in this case, one that uses
2660 @code{self-insert-command}, which simply inserts the character you
2661 typed. The functions you evaluate by typing keystrokes are called
2662 @dfn{interactive} functions, or @dfn{commands}; how you make a function
2663 interactive will be illustrated in the chapter on how to write function
2664 definitions. @xref{Interactive, , Making a Function Interactive}.
2665
2666 In addition to typing keyboard commands, we have seen a second way to
2667 evaluate an expression: by positioning the cursor after a list and
2668 typing @kbd{C-x C-e}. This is what we will do in the rest of this
2669 section. There are other ways to evaluate an expression as well; these
2670 will be described as we come to them.
2671
2672 Besides being used for practicing evaluation, the functions shown in the
2673 next few sections are important in their own right. A study of these
2674 functions makes clear the distinction between buffers and files, how to
2675 switch to a buffer, and how to determine a location within it.
2676
2677 @node Buffer Names
2678 @section Buffer Names
2679 @findex buffer-name
2680 @findex buffer-file-name
2681
2682 The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2683 the difference between a file and a buffer. When you evaluate the
2684 following expression, @code{(buffer-name)}, the name of the buffer
2685 appears in the echo area. When you evaluate @code{(buffer-file-name)},
2686 the name of the file to which the buffer refers appears in the echo
2687 area. Usually, the name returned by @code{(buffer-name)} is the same as
2688 the name of the file to which it refers, and the name returned by
2689 @code{(buffer-file-name)} is the full path-name of the file.
2690
2691 A file and a buffer are two different entities. A file is information
2692 recorded permanently in the computer (unless you delete it). A buffer,
2693 on the other hand, is information inside of Emacs that will vanish at
2694 the end of the editing session (or when you kill the buffer). Usually,
2695 a buffer contains information that you have copied from a file; we say
2696 the buffer is @dfn{visiting} that file. This copy is what you work on
2697 and modify. Changes to the buffer do not change the file, until you
2698 save the buffer. When you save the buffer, the buffer is copied to the file
2699 and is thus saved permanently.
2700
2701 @need 1250
2702 If you are reading this in Info inside of GNU Emacs, you can evaluate
2703 each of the following expressions by positioning the cursor after it and
2704 typing @kbd{C-x C-e}.
2705
2706 @example
2707 @group
2708 (buffer-name)
2709
2710 (buffer-file-name)
2711 @end group
2712 @end example
2713
2714 @noindent
2715 When I do this in Info, the value returned by evaluating
2716 @code{(buffer-name)} is @file{"*info*"}, and the value returned by
2717 evaluating @code{(buffer-file-name)} is @file{nil}.
2718
2719 On the other hand, while I am writing this document, the value
2720 returned by evaluating @code{(buffer-name)} is
2721 @file{"introduction.texinfo"}, and the value returned by evaluating
2722 @code{(buffer-file-name)} is
2723 @file{"/gnu/work/intro/introduction.texinfo"}.
2724
2725 @cindex @code{nil}, history of word
2726 The former is the name of the buffer and the latter is the name of the
2727 file. In Info, the buffer name is @file{"*info*"}. Info does not
2728 point to any file, so the result of evaluating
2729 @code{(buffer-file-name)} is @file{nil}. The symbol @code{nil} is
2730 from the Latin word for `nothing'; in this case, it means that the
2731 buffer is not associated with any file. (In Lisp, @code{nil} is also
2732 used to mean `false' and is a synonym for the empty list, @code{()}.)
2733
2734 When I am writing, the name of my buffer is
2735 @file{"introduction.texinfo"}. The name of the file to which it
2736 points is @file{"/gnu/work/intro/introduction.texinfo"}.
2737
2738 (In the expressions, the parentheses tell the Lisp interpreter to
2739 treat @w{@code{buffer-name}} and @w{@code{buffer-file-name}} as
2740 functions; without the parentheses, the interpreter would attempt to
2741 evaluate the symbols as variables. @xref{Variables}.)
2742
2743 In spite of the distinction between files and buffers, you will often
2744 find that people refer to a file when they mean a buffer and vice-verse.
2745 Indeed, most people say, ``I am editing a file,'' rather than saying,
2746 ``I am editing a buffer which I will soon save to a file.'' It is
2747 almost always clear from context what people mean. When dealing with
2748 computer programs, however, it is important to keep the distinction in mind,
2749 since the computer is not as smart as a person.
2750
2751 @cindex Buffer, history of word
2752 The word `buffer', by the way, comes from the meaning of the word as a
2753 cushion that deadens the force of a collision. In early computers, a
2754 buffer cushioned the interaction between files and the computer's
2755 central processing unit. The drums or tapes that held a file and the
2756 central processing unit were pieces of equipment that were very
2757 different from each other, working at their own speeds, in spurts. The
2758 buffer made it possible for them to work together effectively.
2759 Eventually, the buffer grew from being an intermediary, a temporary
2760 holding place, to being the place where work is done. This
2761 transformation is rather like that of a small seaport that grew into a
2762 great city: once it was merely the place where cargo was warehoused
2763 temporarily before being loaded onto ships; then it became a business
2764 and cultural center in its own right.
2765
2766 Not all buffers are associated with files. For example, a
2767 @file{*scratch*} buffer does not visit any file. Similarly, a
2768 @file{*Help*} buffer is not associated with any file.
2769
2770 In the old days, when you lacked a @file{~/.emacs} file and started an
2771 Emacs session by typing the command @code{emacs} alone, without naming
2772 any files, Emacs started with the @file{*scratch*} buffer visible.
2773 Nowadays, you will see a splash screen. You can follow one of the
2774 commands suggested on the splash screen, visit a file, or press the
2775 spacebar to reach the @file{*scratch*} buffer.
2776
2777 If you switch to the @file{*scratch*} buffer, type
2778 @code{(buffer-name)}, position the cursor after it, and then type
2779 @kbd{C-x C-e} to evaluate the expression. The name @code{"*scratch*"}
2780 will be returned and will appear in the echo area. @code{"*scratch*"}
2781 is the name of the buffer. When you type @code{(buffer-file-name)} in
2782 the @file{*scratch*} buffer and evaluate that, @code{nil} will appear
2783 in the echo area, just as it does when you evaluate
2784 @code{(buffer-file-name)} in Info.
2785
2786 Incidentally, if you are in the @file{*scratch*} buffer and want the
2787 value returned by an expression to appear in the @file{*scratch*}
2788 buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2789 instead of @kbd{C-x C-e}. This causes the value returned to appear
2790 after the expression. The buffer will look like this:
2791
2792 @smallexample
2793 (buffer-name)"*scratch*"
2794 @end smallexample
2795
2796 @noindent
2797 You cannot do this in Info since Info is read-only and it will not allow
2798 you to change the contents of the buffer. But you can do this in any
2799 buffer you can edit; and when you write code or documentation (such as
2800 this book), this feature is very useful.
2801
2802 @node Getting Buffers
2803 @section Getting Buffers
2804 @findex current-buffer
2805 @findex other-buffer
2806 @cindex Getting a buffer
2807
2808 The @code{buffer-name} function returns the @emph{name} of the buffer;
2809 to get the buffer @emph{itself}, a different function is needed: the
2810 @code{current-buffer} function. If you use this function in code, what
2811 you get is the buffer itself.
2812
2813 A name and the object or entity to which the name refers are different
2814 from each other. You are not your name. You are a person to whom
2815 others refer by name. If you ask to speak to George and someone hands you
2816 a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2817 @samp{g}, and @samp{e} written on it, you might be amused, but you would
2818 not be satisfied. You do not want to speak to the name, but to the
2819 person to whom the name refers. A buffer is similar: the name of the
2820 scratch buffer is @file{*scratch*}, but the name is not the buffer. To
2821 get a buffer itself, you need to use a function such as
2822 @code{current-buffer}.
2823
2824 However, there is a slight complication: if you evaluate
2825 @code{current-buffer} in an expression on its own, as we will do here,
2826 what you see is a printed representation of the name of the buffer
2827 without the contents of the buffer. Emacs works this way for two
2828 reasons: the buffer may be thousands of lines long---too long to be
2829 conveniently displayed; and, another buffer may have the same contents
2830 but a different name, and it is important to distinguish between them.
2831
2832 @need 800
2833 Here is an expression containing the function:
2834
2835 @smallexample
2836 (current-buffer)
2837 @end smallexample
2838
2839 @noindent
2840 If you evaluate this expression in Info in Emacs in the usual way,
2841 @file{#<buffer *info*>} will appear in the echo area. The special
2842 format indicates that the buffer itself is being returned, rather than
2843 just its name.
2844
2845 Incidentally, while you can type a number or symbol into a program, you
2846 cannot do that with the printed representation of a buffer: the only way
2847 to get a buffer itself is with a function such as @code{current-buffer}.
2848
2849 A related function is @code{other-buffer}. This returns the most
2850 recently selected buffer other than the one you are in currently, not
2851 a printed representation of its name. If you have recently switched
2852 back and forth from the @file{*scratch*} buffer, @code{other-buffer}
2853 will return that buffer.
2854
2855 @need 800
2856 You can see this by evaluating the expression:
2857
2858 @smallexample
2859 (other-buffer)
2860 @end smallexample
2861
2862 @noindent
2863 You should see @file{#<buffer *scratch*>} appear in the echo area, or
2864 the name of whatever other buffer you switched back from most
2865 recently@footnote{Actually, by default, if the buffer from which you
2866 just switched is visible to you in another window, @code{other-buffer}
2867 will choose the most recent buffer that you cannot see; this is a
2868 subtlety that I often forget.}.
2869
2870 @node Switching Buffers
2871 @section Switching Buffers
2872 @findex switch-to-buffer
2873 @findex set-buffer
2874 @cindex Switching to a buffer
2875
2876 The @code{other-buffer} function actually provides a buffer when it is
2877 used as an argument to a function that requires one. We can see this
2878 by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2879 different buffer.
2880
2881 But first, a brief introduction to the @code{switch-to-buffer}
2882 function. When you switched back and forth from Info to the
2883 @file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2884 likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2885 rather, to save typing, you probably only typed @kbd{RET} if the
2886 default buffer was @file{*scratch*}, or if it was different, then you
2887 typed just part of the name, such as @code{*sc}, pressed your
2888 @kbd{TAB} key to cause it to expand to the full name, and then typed
2889 @kbd{RET}.} when prompted in the minibuffer for the name of
2890 the buffer to which you wanted to switch. The keystrokes, @kbd{C-x
2891 b}, cause the Lisp interpreter to evaluate the interactive function
2892 @code{switch-to-buffer}. As we said before, this is how Emacs works:
2893 different keystrokes call or run different functions. For example,
2894 @kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2895 @code{forward-sentence}, and so on.
2896
2897 By writing @code{switch-to-buffer} in an expression, and giving it a
2898 buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2899 does:
2900
2901 @smallexample
2902 (switch-to-buffer (other-buffer))
2903 @end smallexample
2904
2905 @noindent
2906 The symbol @code{switch-to-buffer} is the first element of the list,
2907 so the Lisp interpreter will treat it as a function and carry out the
2908 instructions that are attached to it. But before doing that, the
2909 interpreter will note that @code{other-buffer} is inside parentheses
2910 and work on that symbol first. @code{other-buffer} is the first (and
2911 in this case, the only) element of this list, so the Lisp interpreter
2912 calls or runs the function. It returns another buffer. Next, the
2913 interpreter runs @code{switch-to-buffer}, passing to it, as an
2914 argument, the other buffer, which is what Emacs will switch to. If
2915 you are reading this in Info, try this now. Evaluate the expression.
2916 (To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2917 expression will move you to your most recent other buffer that you
2918 cannot see. If you really want to go to your most recently selected
2919 buffer, even if you can still see it, you need to evaluate the
2920 following more complex expression:
2921
2922 @smallexample
2923 (switch-to-buffer (other-buffer (current-buffer) t))
2924 @end smallexample
2925
2926 @c noindent
2927 In this case, the first argument to @code{other-buffer} tells it which
2928 buffer to skip---the current one---and the second argument tells
2929 @code{other-buffer} it is OK to switch to a visible buffer.
2930 In regular use, @code{switch-to-buffer} takes you to an invisible
2931 window since you would most likely use @kbd{C-x o} (@code{other-window})
2932 to go to another visible buffer.}
2933
2934 In the programming examples in later sections of this document, you will
2935 see the function @code{set-buffer} more often than
2936 @code{switch-to-buffer}. This is because of a difference between
2937 computer programs and humans: humans have eyes and expect to see the
2938 buffer on which they are working on their computer terminals. This is
2939 so obvious, it almost goes without saying. However, programs do not
2940 have eyes. When a computer program works on a buffer, that buffer does
2941 not need to be visible on the screen.
2942
2943 @code{switch-to-buffer} is designed for humans and does two different
2944 things: it switches the buffer to which Emacs's attention is directed; and
2945 it switches the buffer displayed in the window to the new buffer.
2946 @code{set-buffer}, on the other hand, does only one thing: it switches
2947 the attention of the computer program to a different buffer. The buffer
2948 on the screen remains unchanged (of course, normally nothing happens
2949 there until the command finishes running).
2950
2951 @cindex @samp{call} defined
2952 Also, we have just introduced another jargon term, the word @dfn{call}.
2953 When you evaluate a list in which the first symbol is a function, you
2954 are calling that function. The use of the term comes from the notion of
2955 the function as an entity that can do something for you if you `call'
2956 it---just as a plumber is an entity who can fix a leak if you call him
2957 or her.
2958
2959 @node Buffer Size & Locations
2960 @section Buffer Size and the Location of Point
2961 @cindex Size of buffer
2962 @cindex Buffer size
2963 @cindex Point location
2964 @cindex Location of point
2965
2966 Finally, let's look at several rather simple functions,
2967 @code{buffer-size}, @code{point}, @code{point-min}, and
2968 @code{point-max}. These give information about the size of a buffer and
2969 the location of point within it.
2970
2971 The function @code{buffer-size} tells you the size of the current
2972 buffer; that is, the function returns a count of the number of
2973 characters in the buffer.
2974
2975 @smallexample
2976 (buffer-size)
2977 @end smallexample
2978
2979 @noindent
2980 You can evaluate this in the usual way, by positioning the
2981 cursor after the expression and typing @kbd{C-x C-e}.
2982
2983 @cindex @samp{point} defined
2984 In Emacs, the current position of the cursor is called @dfn{point}.
2985 The expression @code{(point)} returns a number that tells you where the
2986 cursor is located as a count of the number of characters from the
2987 beginning of the buffer up to point.
2988
2989 @need 1250
2990 You can see the character count for point in this buffer by evaluating
2991 the following expression in the usual way:
2992
2993 @smallexample
2994 (point)
2995 @end smallexample
2996
2997 @noindent
2998 As I write this, the value of @code{point} is 65724. The @code{point}
2999 function is frequently used in some of the examples later in this
3000 book.
3001
3002 @need 1250
3003 The value of point depends, of course, on its location within the
3004 buffer. If you evaluate point in this spot, the number will be larger:
3005
3006 @smallexample
3007 (point)
3008 @end smallexample
3009
3010 @noindent
3011 For me, the value of point in this location is 66043, which means that
3012 there are 319 characters (including spaces) between the two
3013 expressions. (Doubtless, you will see different numbers, since I will
3014 have edited this since I first evaluated point.)
3015
3016 @cindex @samp{narrowing} defined
3017 The function @code{point-min} is somewhat similar to @code{point}, but
3018 it returns the value of the minimum permissible value of point in the
3019 current buffer. This is the number 1 unless @dfn{narrowing} is in
3020 effect. (Narrowing is a mechanism whereby you can restrict yourself,
3021 or a program, to operations on just a part of a buffer.
3022 @xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the
3023 function @code{point-max} returns the value of the maximum permissible
3024 value of point in the current buffer.
3025
3026 @node Evaluation Exercise
3027 @section Exercise
3028
3029 Find a file with which you are working and move towards its middle.
3030 Find its buffer name, file name, length, and your position in the file.
3031
3032 @node Writing Defuns
3033 @chapter How To Write Function Definitions
3034 @cindex Definition writing
3035 @cindex Function definition writing
3036 @cindex Writing a function definition
3037
3038 When the Lisp interpreter evaluates a list, it looks to see whether the
3039 first symbol on the list has a function definition attached to it; or,
3040 put another way, whether the symbol points to a function definition. If
3041 it does, the computer carries out the instructions in the definition. A
3042 symbol that has a function definition is called, simply, a function
3043 (although, properly speaking, the definition is the function and the
3044 symbol refers to it.)
3045
3046 @menu
3047 * Primitive Functions::
3048 * defun:: The @code{defun} special form.
3049 * Install:: Install a function definition.
3050 * Interactive:: Making a function interactive.
3051 * Interactive Options:: Different options for @code{interactive}.
3052 * Permanent Installation:: Installing code permanently.
3053 * let:: Creating and initializing local variables.
3054 * if:: What if?
3055 * else:: If--then--else expressions.
3056 * Truth & Falsehood:: What Lisp considers false and true.
3057 * save-excursion:: Keeping track of point, mark, and buffer.
3058 * Review::
3059 * defun Exercises::
3060 @end menu
3061
3062 @ifnottex
3063 @node Primitive Functions
3064 @unnumberedsec An Aside about Primitive Functions
3065 @end ifnottex
3066 @cindex Primitive functions
3067 @cindex Functions, primitive
3068
3069 @cindex C language primitives
3070 @cindex Primitives written in C
3071 All functions are defined in terms of other functions, except for a few
3072 @dfn{primitive} functions that are written in the C programming
3073 language. When you write functions' definitions, you will write them in
3074 Emacs Lisp and use other functions as your building blocks. Some of the
3075 functions you will use will themselves be written in Emacs Lisp (perhaps
3076 by you) and some will be primitives written in C@. The primitive
3077 functions are used exactly like those written in Emacs Lisp and behave
3078 like them. They are written in C so we can easily run GNU Emacs on any
3079 computer that has sufficient power and can run C.
3080
3081 Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3082 distinguish between the use of functions written in C and the use of
3083 functions written in Emacs Lisp. The difference is irrelevant. I
3084 mention the distinction only because it is interesting to know. Indeed,
3085 unless you investigate, you won't know whether an already-written
3086 function is written in Emacs Lisp or C.
3087
3088 @node defun
3089 @section The @code{defun} Special Form
3090 @findex defun
3091 @cindex Special form of @code{defun}
3092
3093 @cindex @samp{function definition} defined
3094 In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3095 it that tells the computer what to do when the function is called.
3096 This code is called the @dfn{function definition} and is created by
3097 evaluating a Lisp expression that starts with the symbol @code{defun}
3098 (which is an abbreviation for @emph{define function}). Because
3099 @code{defun} does not evaluate its arguments in the usual way, it is
3100 called a @dfn{special form}.
3101
3102 In subsequent sections, we will look at function definitions from the
3103 Emacs source code, such as @code{mark-whole-buffer}. In this section,
3104 we will describe a simple function definition so you can see how it
3105 looks. This function definition uses arithmetic because it makes for a
3106 simple example. Some people dislike examples using arithmetic; however,
3107 if you are such a person, do not despair. Hardly any of the code we
3108 will study in the remainder of this introduction involves arithmetic or
3109 mathematics. The examples mostly involve text in one way or another.
3110
3111 A function definition has up to five parts following the word
3112 @code{defun}:
3113
3114 @enumerate
3115 @item
3116 The name of the symbol to which the function definition should be
3117 attached.
3118
3119 @item
3120 A list of the arguments that will be passed to the function. If no
3121 arguments will be passed to the function, this is an empty list,
3122 @code{()}.
3123
3124 @item
3125 Documentation describing the function. (Technically optional, but
3126 strongly recommended.)
3127
3128 @item
3129 Optionally, an expression to make the function interactive so you can
3130 use it by typing @kbd{M-x} and then the name of the function; or by
3131 typing an appropriate key or keychord.
3132
3133 @cindex @samp{body} defined
3134 @item
3135 The code that instructs the computer what to do: the @dfn{body} of the
3136 function definition.
3137 @end enumerate
3138
3139 It is helpful to think of the five parts of a function definition as
3140 being organized in a template, with slots for each part:
3141
3142 @smallexample
3143 @group
3144 (defun @var{function-name} (@var{arguments}@dots{})
3145 "@var{optional-documentation}@dots{}"
3146 (interactive @var{argument-passing-info}) ; @r{optional}
3147 @var{body}@dots{})
3148 @end group
3149 @end smallexample
3150
3151 As an example, here is the code for a function that multiplies its
3152 argument by 7. (This example is not interactive. @xref{Interactive,
3153 , Making a Function Interactive}, for that information.)
3154
3155 @smallexample
3156 @group
3157 (defun multiply-by-seven (number)
3158 "Multiply NUMBER by seven."
3159 (* 7 number))
3160 @end group
3161 @end smallexample
3162
3163 This definition begins with a parenthesis and the symbol @code{defun},
3164 followed by the name of the function.
3165
3166 @cindex @samp{argument list} defined
3167 The name of the function is followed by a list that contains the
3168 arguments that will be passed to the function. This list is called
3169 the @dfn{argument list}. In this example, the list has only one
3170 element, the symbol, @code{number}. When the function is used, the
3171 symbol will be bound to the value that is used as the argument to the
3172 function.
3173
3174 Instead of choosing the word @code{number} for the name of the argument,
3175 I could have picked any other name. For example, I could have chosen
3176 the word @code{multiplicand}. I picked the word `number' because it
3177 tells what kind of value is intended for this slot; but I could just as
3178 well have chosen the word `multiplicand' to indicate the role that the
3179 value placed in this slot will play in the workings of the function. I
3180 could have called it @code{foogle}, but that would have been a bad
3181 choice because it would not tell humans what it means. The choice of
3182 name is up to the programmer and should be chosen to make the meaning of
3183 the function clear.
3184
3185 Indeed, you can choose any name you wish for a symbol in an argument
3186 list, even the name of a symbol used in some other function: the name
3187 you use in an argument list is private to that particular definition.
3188 In that definition, the name refers to a different entity than any use
3189 of the same name outside the function definition. Suppose you have a
3190 nick-name `Shorty' in your family; when your family members refer to
3191 `Shorty', they mean you. But outside your family, in a movie, for
3192 example, the name `Shorty' refers to someone else. Because a name in an
3193 argument list is private to the function definition, you can change the
3194 value of such a symbol inside the body of a function without changing
3195 its value outside the function. The effect is similar to that produced
3196 by a @code{let} expression. (@xref{let, , @code{let}}.)
3197
3198 @ignore
3199 Note also that we discuss the word `number' in two different ways: as a
3200 symbol that appears in the code, and as the name of something that will
3201 be replaced by a something else during the evaluation of the function.
3202 In the first case, @code{number} is a symbol, not a number; it happens
3203 that within the function, it is a variable who value is the number in
3204 question, but our primary interest in it is as a symbol. On the other
3205 hand, when we are talking about the function, our interest is that we
3206 will substitute a number for the word @var{number}. To keep this
3207 distinction clear, we use different typography for the two
3208 circumstances. When we talk about this function, or about how it works,
3209 we refer to this number by writing @var{number}. In the function
3210 itself, we refer to it by writing @code{number}.
3211 @end ignore
3212
3213 The argument list is followed by the documentation string that
3214 describes the function. This is what you see when you type
3215 @w{@kbd{C-h f}} and the name of a function. Incidentally, when you
3216 write a documentation string like this, you should make the first line
3217 a complete sentence since some commands, such as @code{apropos}, print
3218 only the first line of a multi-line documentation string. Also, you
3219 should not indent the second line of a documentation string, if you
3220 have one, because that looks odd when you use @kbd{C-h f}
3221 (@code{describe-function}). The documentation string is optional, but
3222 it is so useful, it should be included in almost every function you
3223 write.
3224
3225 @findex * @r{(multiplication)}
3226 The third line of the example consists of the body of the function
3227 definition. (Most functions' definitions, of course, are longer than
3228 this.) In this function, the body is the list, @code{(* 7 number)}, which
3229 says to multiply the value of @var{number} by 7. (In Emacs Lisp,
3230 @code{*} is the function for multiplication, just as @code{+} is the
3231 function for addition.)
3232
3233 When you use the @code{multiply-by-seven} function, the argument
3234 @code{number} evaluates to the actual number you want used. Here is an
3235 example that shows how @code{multiply-by-seven} is used; but don't try
3236 to evaluate this yet!
3237
3238 @smallexample
3239 (multiply-by-seven 3)
3240 @end smallexample
3241
3242 @noindent
3243 The symbol @code{number}, specified in the function definition in the
3244 next section, is given or ``bound to'' the value 3 in the actual use of
3245 the function. Note that although @code{number} was inside parentheses
3246 in the function definition, the argument passed to the
3247 @code{multiply-by-seven} function is not in parentheses. The
3248 parentheses are written in the function definition so the computer can
3249 figure out where the argument list ends and the rest of the function
3250 definition begins.
3251
3252 If you evaluate this example, you are likely to get an error message.
3253 (Go ahead, try it!) This is because we have written the function
3254 definition, but not yet told the computer about the definition---we have
3255 not yet installed (or `loaded') the function definition in Emacs.
3256 Installing a function is the process that tells the Lisp interpreter the
3257 definition of the function. Installation is described in the next
3258 section.
3259
3260 @node Install
3261 @section Install a Function Definition
3262 @cindex Install a Function Definition
3263 @cindex Definition installation
3264 @cindex Function definition installation
3265
3266 If you are reading this inside of Info in Emacs, you can try out the
3267 @code{multiply-by-seven} function by first evaluating the function
3268 definition and then evaluating @code{(multiply-by-seven 3)}. A copy of
3269 the function definition follows. Place the cursor after the last
3270 parenthesis of the function definition and type @kbd{C-x C-e}. When you
3271 do this, @code{multiply-by-seven} will appear in the echo area. (What
3272 this means is that when a function definition is evaluated, the value it
3273 returns is the name of the defined function.) At the same time, this
3274 action installs the function definition.
3275
3276 @smallexample
3277 @group
3278 (defun multiply-by-seven (number)
3279 "Multiply NUMBER by seven."
3280 (* 7 number))
3281 @end group
3282 @end smallexample
3283
3284 @noindent
3285 By evaluating this @code{defun}, you have just installed
3286 @code{multiply-by-seven} in Emacs. The function is now just as much a
3287 part of Emacs as @code{forward-word} or any other editing function you
3288 use. (@code{multiply-by-seven} will stay installed until you quit
3289 Emacs. To reload code automatically whenever you start Emacs, see
3290 @ref{Permanent Installation, , Installing Code Permanently}.)
3291
3292 @menu
3293 * Effect of installation::
3294 * Change a defun:: How to change a function definition.
3295 @end menu
3296
3297 @ifnottex
3298 @node Effect of installation
3299 @unnumberedsubsec The effect of installation
3300 @end ifnottex
3301
3302 You can see the effect of installing @code{multiply-by-seven} by
3303 evaluating the following sample. Place the cursor after the following
3304 expression and type @kbd{C-x C-e}. The number 21 will appear in the
3305 echo area.
3306
3307 @smallexample
3308 (multiply-by-seven 3)
3309 @end smallexample
3310
3311 If you wish, you can read the documentation for the function by typing
3312 @kbd{C-h f} (@code{describe-function}) and then the name of the
3313 function, @code{multiply-by-seven}. When you do this, a
3314 @file{*Help*} window will appear on your screen that says:
3315
3316 @smallexample
3317 @group
3318 multiply-by-seven is a Lisp function.
3319 (multiply-by-seven NUMBER)
3320
3321 Multiply NUMBER by seven.
3322 @end group
3323 @end smallexample
3324
3325 @noindent
3326 (To return to a single window on your screen, type @kbd{C-x 1}.)
3327
3328 @node Change a defun
3329 @subsection Change a Function Definition
3330 @cindex Changing a function definition
3331 @cindex Function definition, how to change
3332 @cindex Definition, how to change
3333
3334 If you want to change the code in @code{multiply-by-seven}, just rewrite
3335 it. To install the new version in place of the old one, evaluate the
3336 function definition again. This is how you modify code in Emacs. It is
3337 very simple.
3338
3339 As an example, you can change the @code{multiply-by-seven} function to
3340 add the number to itself seven times instead of multiplying the number
3341 by seven. It produces the same answer, but by a different path. At
3342 the same time, we will add a comment to the code; a comment is text
3343 that the Lisp interpreter ignores, but that a human reader may find
3344 useful or enlightening. The comment is that this is the ``second
3345 version''.
3346
3347 @smallexample
3348 @group
3349 (defun multiply-by-seven (number) ; @r{Second version.}
3350 "Multiply NUMBER by seven."
3351 (+ number number number number number number number))
3352 @end group
3353 @end smallexample
3354
3355 @cindex Comments in Lisp code
3356 The comment follows a semicolon, @samp{;}. In Lisp, everything on a
3357 line that follows a semicolon is a comment. The end of the line is the
3358 end of the comment. To stretch a comment over two or more lines, begin
3359 each line with a semicolon.
3360
3361 @xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3362 File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3363 Reference Manual}, for more about comments.
3364
3365 You can install this version of the @code{multiply-by-seven} function by
3366 evaluating it in the same way you evaluated the first function: place
3367 the cursor after the last parenthesis and type @kbd{C-x C-e}.
3368
3369 In summary, this is how you write code in Emacs Lisp: you write a
3370 function; install it; test it; and then make fixes or enhancements and
3371 install it again.
3372
3373 @node Interactive
3374 @section Make a Function Interactive
3375 @cindex Interactive functions
3376 @findex interactive
3377
3378 You make a function interactive by placing a list that begins with
3379 the special form @code{interactive} immediately after the
3380 documentation. A user can invoke an interactive function by typing
3381 @kbd{M-x} and then the name of the function; or by typing the keys to
3382 which it is bound, for example, by typing @kbd{C-n} for
3383 @code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3384
3385 Interestingly, when you call an interactive function interactively,
3386 the value returned is not automatically displayed in the echo area.
3387 This is because you often call an interactive function for its side
3388 effects, such as moving forward by a word or line, and not for the
3389 value returned. If the returned value were displayed in the echo area
3390 each time you typed a key, it would be very distracting.
3391
3392 @menu
3393 * Interactive multiply-by-seven:: An overview.
3394 * multiply-by-seven in detail:: The interactive version.
3395 @end menu
3396
3397 @ifnottex
3398 @node Interactive multiply-by-seven
3399 @unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3400 @end ifnottex
3401
3402 Both the use of the special form @code{interactive} and one way to
3403 display a value in the echo area can be illustrated by creating an
3404 interactive version of @code{multiply-by-seven}.
3405
3406 @need 1250
3407 Here is the code:
3408
3409 @smallexample
3410 @group
3411 (defun multiply-by-seven (number) ; @r{Interactive version.}
3412 "Multiply NUMBER by seven."
3413 (interactive "p")
3414 (message "The result is %d" (* 7 number)))
3415 @end group
3416 @end smallexample
3417
3418 @noindent
3419 You can install this code by placing your cursor after it and typing
3420 @kbd{C-x C-e}. The name of the function will appear in your echo area.
3421 Then, you can use this code by typing @kbd{C-u} and a number and then
3422 typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase
3423 @samp{The result is @dots{}} followed by the product will appear in the
3424 echo area.
3425
3426 Speaking more generally, you invoke a function like this in either of two
3427 ways:
3428
3429 @enumerate
3430 @item
3431 By typing a prefix argument that contains the number to be passed, and
3432 then typing @kbd{M-x} and the name of the function, as with
3433 @kbd{C-u 3 M-x forward-sentence}; or,
3434
3435 @item
3436 By typing whatever key or keychord the function is bound to, as with
3437 @kbd{C-u 3 M-e}.
3438 @end enumerate
3439
3440 @noindent
3441 Both the examples just mentioned work identically to move point forward
3442 three sentences. (Since @code{multiply-by-seven} is not bound to a key,
3443 it could not be used as an example of key binding.)
3444
3445 (@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3446 to a key.)
3447
3448 A prefix argument is passed to an interactive function by typing the
3449 @key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3450 typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3451 type @kbd{C-u} without a number, it defaults to 4).
3452
3453 @node multiply-by-seven in detail
3454 @subsection An Interactive @code{multiply-by-seven}
3455
3456 Let's look at the use of the special form @code{interactive} and then at
3457 the function @code{message} in the interactive version of
3458 @code{multiply-by-seven}. You will recall that the function definition
3459 looks like this:
3460
3461 @smallexample
3462 @group
3463 (defun multiply-by-seven (number) ; @r{Interactive version.}
3464 "Multiply NUMBER by seven."
3465 (interactive "p")
3466 (message "The result is %d" (* 7 number)))
3467 @end group
3468 @end smallexample
3469
3470 In this function, the expression, @code{(interactive "p")}, is a list of
3471 two elements. The @code{"p"} tells Emacs to pass the prefix argument to
3472 the function and use its value for the argument of the function.
3473
3474 @need 1000
3475 The argument will be a number. This means that the symbol
3476 @code{number} will be bound to a number in the line:
3477
3478 @smallexample
3479 (message "The result is %d" (* 7 number))
3480 @end smallexample
3481
3482 @need 1250
3483 @noindent
3484 For example, if your prefix argument is 5, the Lisp interpreter will
3485 evaluate the line as if it were:
3486
3487 @smallexample
3488 (message "The result is %d" (* 7 5))
3489 @end smallexample
3490
3491 @noindent
3492 (If you are reading this in GNU Emacs, you can evaluate this expression
3493 yourself.) First, the interpreter will evaluate the inner list, which
3494 is @code{(* 7 5)}. This returns a value of 35. Next, it
3495 will evaluate the outer list, passing the values of the second and
3496 subsequent elements of the list to the function @code{message}.
3497
3498 As we have seen, @code{message} is an Emacs Lisp function especially
3499 designed for sending a one line message to a user. (@xref{message, ,
3500 The @code{message} function}.) In summary, the @code{message}
3501 function prints its first argument in the echo area as is, except for
3502 occurrences of @samp{%d} or @samp{%s} (and various other %-sequences
3503 which we have not mentioned). When it sees a control sequence, the
3504 function looks to the second or subsequent arguments and prints the
3505 value of the argument in the location in the string where the control
3506 sequence is located.
3507
3508 In the interactive @code{multiply-by-seven} function, the control string
3509 is @samp{%d}, which requires a number, and the value returned by
3510 evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35
3511 is printed in place of the @samp{%d} and the message is @samp{The result
3512 is 35}.
3513
3514 (Note that when you call the function @code{multiply-by-seven}, the
3515 message is printed without quotes, but when you call @code{message}, the
3516 text is printed in double quotes. This is because the value returned by
3517 @code{message} is what appears in the echo area when you evaluate an
3518 expression whose first element is @code{message}; but when embedded in a
3519 function, @code{message} prints the text as a side effect without
3520 quotes.)
3521
3522 @node Interactive Options
3523 @section Different Options for @code{interactive}
3524 @cindex Options for @code{interactive}
3525 @cindex Interactive options
3526
3527 In the example, @code{multiply-by-seven} used @code{"p"} as the
3528 argument to @code{interactive}. This argument told Emacs to interpret
3529 your typing either @kbd{C-u} followed by a number or @key{META}
3530 followed by a number as a command to pass that number to the function
3531 as its argument. Emacs has more than twenty characters predefined for
3532 use with @code{interactive}. In almost every case, one of these
3533 options will enable you to pass the right information interactively to
3534 a function. (@xref{Interactive Codes, , Code Characters for
3535 @code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3536
3537 @need 1250
3538 Consider the function @code{zap-to-char}. Its interactive expression
3539 is
3540
3541 @smallexample
3542 (interactive "p\ncZap to char: ")
3543 @end smallexample
3544
3545 The first part of the argument to @code{interactive} is @samp{p}, with
3546 which you are already familiar. This argument tells Emacs to
3547 interpret a `prefix', as a number to be passed to the function. You
3548 can specify a prefix either by typing @kbd{C-u} followed by a number
3549 or by typing @key{META} followed by a number. The prefix is the
3550 number of specified characters. Thus, if your prefix is three and the
3551 specified character is @samp{x}, then you will delete all the text up
3552 to and including the third next @samp{x}. If you do not set a prefix,
3553 then you delete all the text up to and including the specified
3554 character, but no more.
3555
3556 The @samp{c} tells the function the name of the character to which to delete.
3557
3558 More formally, a function with two or more arguments can have
3559 information passed to each argument by adding parts to the string that
3560 follows @code{interactive}. When you do this, the information is
3561 passed to each argument in the same order it is specified in the
3562 @code{interactive} list. In the string, each part is separated from
3563 the next part by a @samp{\n}, which is a newline. For example, you
3564 can follow @samp{p} with a @samp{\n} and an @samp{cZap to char:@: }.
3565 This causes Emacs to pass the value of the prefix argument (if there
3566 is one) and the character.
3567
3568 In this case, the function definition looks like the following, where
3569 @code{arg} and @code{char} are the symbols to which @code{interactive}
3570 binds the prefix argument and the specified character:
3571
3572 @smallexample
3573 @group
3574 (defun @var{name-of-function} (arg char)
3575 "@var{documentation}@dots{}"
3576 (interactive "p\ncZap to char: ")
3577 @var{body-of-function}@dots{})
3578 @end group
3579 @end smallexample
3580
3581 @noindent
3582 (The space after the colon in the prompt makes it look better when you
3583 are prompted. @xref{copy-to-buffer, , The Definition of
3584 @code{copy-to-buffer}}, for an example.)
3585
3586 When a function does not take arguments, @code{interactive} does not
3587 require any. Such a function contains the simple expression
3588 @code{(interactive)}. The @code{mark-whole-buffer} function is like
3589 this.
3590
3591 Alternatively, if the special letter-codes are not right for your
3592 application, you can pass your own arguments to @code{interactive} as
3593 a list.
3594
3595 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}},
3596 for an example. @xref{Using Interactive, , Using @code{Interactive},
3597 elisp, The GNU Emacs Lisp Reference Manual}, for a more complete
3598 explanation about this technique.
3599
3600 @node Permanent Installation
3601 @section Install Code Permanently
3602 @cindex Install code permanently
3603 @cindex Permanent code installation
3604 @cindex Code installation
3605
3606 When you install a function definition by evaluating it, it will stay
3607 installed until you quit Emacs. The next time you start a new session
3608 of Emacs, the function will not be installed unless you evaluate the
3609 function definition again.
3610
3611 At some point, you may want to have code installed automatically
3612 whenever you start a new session of Emacs. There are several ways of
3613 doing this:
3614
3615 @itemize @bullet
3616 @item
3617 If you have code that is just for yourself, you can put the code for the
3618 function definition in your @file{.emacs} initialization file. When you
3619 start Emacs, your @file{.emacs} file is automatically evaluated and all
3620 the function definitions within it are installed.
3621 @xref{Emacs Initialization, , Your @file{.emacs} File}.
3622
3623 @item
3624 Alternatively, you can put the function definitions that you want
3625 installed in one or more files of their own and use the @code{load}
3626 function to cause Emacs to evaluate and thereby install each of the
3627 functions in the files.
3628 @xref{Loading Files, , Loading Files}.
3629
3630 @item
3631 Thirdly, if you have code that your whole site will use, it is usual
3632 to put it in a file called @file{site-init.el} that is loaded when
3633 Emacs is built. This makes the code available to everyone who uses
3634 your machine. (See the @file{INSTALL} file that is part of the Emacs
3635 distribution.)
3636 @end itemize
3637
3638 Finally, if you have code that everyone who uses Emacs may want, you
3639 can post it on a computer network or send a copy to the Free Software
3640 Foundation. (When you do this, please license the code and its
3641 documentation under a license that permits other people to run, copy,
3642 study, modify, and redistribute the code and which protects you from
3643 having your work taken from you.) If you send a copy of your code to
3644 the Free Software Foundation, and properly protect yourself and
3645 others, it may be included in the next release of Emacs. In large
3646 part, this is how Emacs has grown over the past years, by donations.
3647
3648 @node let
3649 @section @code{let}
3650 @findex let
3651
3652 The @code{let} expression is a special form in Lisp that you will need
3653 to use in most function definitions.
3654
3655 @code{let} is used to attach or bind a symbol to a value in such a way
3656 that the Lisp interpreter will not confuse the variable with a
3657 variable of the same name that is not part of the function.
3658
3659 To understand why the @code{let} special form is necessary, consider
3660 the situation in which you own a home that you generally refer to as
3661 `the house', as in the sentence, ``The house needs painting.'' If you
3662 are visiting a friend and your host refers to `the house', he is
3663 likely to be referring to @emph{his} house, not yours, that is, to a
3664 different house.
3665
3666 If your friend is referring to his house and you think he is referring
3667 to your house, you may be in for some confusion. The same thing could
3668 happen in Lisp if a variable that is used inside of one function has
3669 the same name as a variable that is used inside of another function,
3670 and the two are not intended to refer to the same value. The
3671 @code{let} special form prevents this kind of confusion.
3672
3673 @menu
3674 * Prevent confusion::
3675 * Parts of let Expression::
3676 * Sample let Expression::
3677 * Uninitialized let Variables::
3678 @end menu
3679
3680 @ifnottex
3681 @node Prevent confusion
3682 @unnumberedsubsec @code{let} Prevents Confusion
3683 @end ifnottex
3684
3685 @cindex @samp{local variable} defined
3686 @cindex @samp{variable, local}, defined
3687 The @code{let} special form prevents confusion. @code{let} creates a
3688 name for a @dfn{local variable} that overshadows any use of the same
3689 name outside the @code{let} expression. This is like understanding
3690 that whenever your host refers to `the house', he means his house, not
3691 yours. (Symbols used in argument lists work the same way.
3692 @xref{defun, , The @code{defun} Special Form}.)
3693
3694 Local variables created by a @code{let} expression retain their value
3695 @emph{only} within the @code{let} expression itself (and within
3696 expressions called within the @code{let} expression); the local
3697 variables have no effect outside the @code{let} expression.
3698
3699 Another way to think about @code{let} is that it is like a @code{setq}
3700 that is temporary and local. The values set by @code{let} are
3701 automatically undone when the @code{let} is finished. The setting
3702 only affects expressions that are inside the bounds of the @code{let}
3703 expression. In computer science jargon, we would say ``the binding of
3704 a symbol is visible only in functions called in the @code{let} form;
3705 in Emacs Lisp, scoping is dynamic, not lexical.''
3706
3707 @code{let} can create more than one variable at once. Also,
3708 @code{let} gives each variable it creates an initial value, either a
3709 value specified by you, or @code{nil}. (In the jargon, this is called
3710 `binding the variable to the value'.) After @code{let} has created
3711 and bound the variables, it executes the code in the body of the
3712 @code{let}, and returns the value of the last expression in the body,
3713 as the value of the whole @code{let} expression. (`Execute' is a jargon
3714 term that means to evaluate a list; it comes from the use of the word
3715 meaning `to give practical effect to' (@cite{Oxford English
3716 Dictionary}). Since you evaluate an expression to perform an action,
3717 `execute' has evolved as a synonym to `evaluate'.)
3718
3719 @node Parts of let Expression
3720 @subsection The Parts of a @code{let} Expression
3721 @cindex @code{let} expression, parts of
3722 @cindex Parts of @code{let} expression
3723
3724 @cindex @samp{varlist} defined
3725 A @code{let} expression is a list of three parts. The first part is
3726 the symbol @code{let}. The second part is a list, called a
3727 @dfn{varlist}, each element of which is either a symbol by itself or a
3728 two-element list, the first element of which is a symbol. The third
3729 part of the @code{let} expression is the body of the @code{let}. The
3730 body usually consists of one or more lists.
3731
3732 @need 800
3733 A template for a @code{let} expression looks like this:
3734
3735 @smallexample
3736 (let @var{varlist} @var{body}@dots{})
3737 @end smallexample
3738
3739 @noindent
3740 The symbols in the varlist are the variables that are given initial
3741 values by the @code{let} special form. Symbols by themselves are given
3742 the initial value of @code{nil}; and each symbol that is the first
3743 element of a two-element list is bound to the value that is returned
3744 when the Lisp interpreter evaluates the second element.
3745
3746 Thus, a varlist might look like this: @code{(thread (needles 3))}. In
3747 this case, in a @code{let} expression, Emacs binds the symbol
3748 @code{thread} to an initial value of @code{nil}, and binds the symbol
3749 @code{needles} to an initial value of 3.
3750
3751 When you write a @code{let} expression, what you do is put the
3752 appropriate expressions in the slots of the @code{let} expression
3753 template.
3754
3755 If the varlist is composed of two-element lists, as is often the case,
3756 the template for the @code{let} expression looks like this:
3757
3758 @smallexample
3759 @group
3760 (let ((@var{variable} @var{value})
3761 (@var{variable} @var{value})
3762 @dots{})
3763 @var{body}@dots{})
3764 @end group
3765 @end smallexample
3766
3767 @node Sample let Expression
3768 @subsection Sample @code{let} Expression
3769 @cindex Sample @code{let} expression
3770 @cindex @code{let} expression sample
3771
3772 The following expression creates and gives initial values
3773 to the two variables @code{zebra} and @code{tiger}. The body of the
3774 @code{let} expression is a list which calls the @code{message} function.
3775
3776 @smallexample
3777 @group
3778 (let ((zebra 'stripes)
3779 (tiger 'fierce))
3780 (message "One kind of animal has %s and another is %s."
3781 zebra tiger))
3782 @end group
3783 @end smallexample
3784
3785 Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3786
3787 The two variables are @code{zebra} and @code{tiger}. Each variable is
3788 the first element of a two-element list and each value is the second
3789 element of its two-element list. In the varlist, Emacs binds the
3790 variable @code{zebra} to the value @code{stripes}@footnote{According
3791 to Jared Diamond in @cite{Guns, Germs, and Steel}, ``@dots{} zebras
3792 become impossibly dangerous as they grow older'' but the claim here is
3793 that they do not become fierce like a tiger. (1997, W. W. Norton and
3794 Co., ISBN 0-393-03894-2, page 171)}, and binds the
3795 variable @code{tiger} to the value @code{fierce}. In this example,
3796 both values are symbols preceded by a quote. The values could just as
3797 well have been another list or a string. The body of the @code{let}
3798 follows after the list holding the variables. In this example, the
3799 body is a list that uses the @code{message} function to print a string
3800 in the echo area.
3801
3802 @need 1500
3803 You may evaluate the example in the usual fashion, by placing the
3804 cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do
3805 this, the following will appear in the echo area:
3806
3807 @smallexample
3808 "One kind of animal has stripes and another is fierce."
3809 @end smallexample
3810
3811 As we have seen before, the @code{message} function prints its first
3812 argument, except for @samp{%s}. In this example, the value of the variable
3813 @code{zebra} is printed at the location of the first @samp{%s} and the
3814 value of the variable @code{tiger} is printed at the location of the
3815 second @samp{%s}.
3816
3817 @node Uninitialized let Variables
3818 @subsection Uninitialized Variables in a @code{let} Statement
3819 @cindex Uninitialized @code{let} variables
3820 @cindex @code{let} variables uninitialized
3821
3822 If you do not bind the variables in a @code{let} statement to specific
3823 initial values, they will automatically be bound to an initial value of
3824 @code{nil}, as in the following expression:
3825
3826 @smallexample
3827 @group
3828 (let ((birch 3)
3829 pine
3830 fir
3831 (oak 'some))
3832 (message
3833 "Here are %d variables with %s, %s, and %s value."
3834 birch pine fir oak))
3835 @end group
3836 @end smallexample
3837
3838 @noindent
3839 Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3840
3841 @need 1250
3842 If you evaluate this expression in the usual way, the following will
3843 appear in your echo area:
3844
3845 @smallexample
3846 "Here are 3 variables with nil, nil, and some value."
3847 @end smallexample
3848
3849 @noindent
3850 In this example, Emacs binds the symbol @code{birch} to the number 3,
3851 binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3852 the symbol @code{oak} to the value @code{some}.
3853
3854 Note that in the first part of the @code{let}, the variables @code{pine}
3855 and @code{fir} stand alone as atoms that are not surrounded by
3856 parentheses; this is because they are being bound to @code{nil}, the
3857 empty list. But @code{oak} is bound to @code{some} and so is a part of
3858 the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the
3859 number 3 and so is in a list with that number. (Since a number
3860 evaluates to itself, the number does not need to be quoted. Also, the
3861 number is printed in the message using a @samp{%d} rather than a
3862 @samp{%s}.) The four variables as a group are put into a list to
3863 delimit them from the body of the @code{let}.
3864
3865 @node if
3866 @section The @code{if} Special Form
3867 @findex if
3868 @cindex Conditional with @code{if}
3869
3870 A third special form, in addition to @code{defun} and @code{let}, is the
3871 conditional @code{if}. This form is used to instruct the computer to
3872 make decisions. You can write function definitions without using
3873 @code{if}, but it is used often enough, and is important enough, to be
3874 included here. It is used, for example, in the code for the
3875 function @code{beginning-of-buffer}.
3876
3877 The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3878 @emph{then} an expression is evaluated.'' If the test is not true, the
3879 expression is not evaluated. For example, you might make a decision
3880 such as, ``if it is warm and sunny, then go to the beach!''
3881
3882 @menu
3883 * if in more detail::
3884 * type-of-animal in detail:: An example of an @code{if} expression.
3885 @end menu
3886
3887 @ifnottex
3888 @node if in more detail
3889 @unnumberedsubsec @code{if} in more detail
3890 @end ifnottex
3891
3892 @cindex @samp{if-part} defined
3893 @cindex @samp{then-part} defined
3894 An @code{if} expression written in Lisp does not use the word `then';
3895 the test and the action are the second and third elements of the list
3896 whose first element is @code{if}. Nonetheless, the test part of an
3897 @code{if} expression is often called the @dfn{if-part} and the second
3898 argument is often called the @dfn{then-part}.
3899
3900 Also, when an @code{if} expression is written, the true-or-false-test
3901 is usually written on the same line as the symbol @code{if}, but the
3902 action to carry out if the test is true, the ``then-part'', is written
3903 on the second and subsequent lines. This makes the @code{if}
3904 expression easier to read.
3905
3906 @smallexample
3907 @group
3908 (if @var{true-or-false-test}
3909 @var{action-to-carry-out-if-test-is-true})
3910 @end group
3911 @end smallexample
3912
3913 @noindent
3914 The true-or-false-test will be an expression that
3915 is evaluated by the Lisp interpreter.
3916
3917 Here is an example that you can evaluate in the usual manner. The test
3918 is whether the number 5 is greater than the number 4. Since it is, the
3919 message @samp{5 is greater than 4!} will be printed.
3920
3921 @smallexample
3922 @group
3923 (if (> 5 4) ; @r{if-part}
3924 (message "5 is greater than 4!")) ; @r{then-part}
3925 @end group
3926 @end smallexample
3927
3928 @noindent
3929 (The function @code{>} tests whether its first argument is greater than
3930 its second argument and returns true if it is.)
3931 @findex > (greater than)
3932
3933 Of course, in actual use, the test in an @code{if} expression will not
3934 be fixed for all time as it is by the expression @code{(> 5 4)}.
3935 Instead, at least one of the variables used in the test will be bound to
3936 a value that is not known ahead of time. (If the value were known ahead
3937 of time, we would not need to run the test!)
3938
3939 For example, the value may be bound to an argument of a function
3940 definition. In the following function definition, the character of the
3941 animal is a value that is passed to the function. If the value bound to
3942 @code{characteristic} is @code{fierce}, then the message, @samp{It's a
3943 tiger!} will be printed; otherwise, @code{nil} will be returned.
3944
3945 @smallexample
3946 @group
3947 (defun type-of-animal (characteristic)
3948 "Print message in echo area depending on CHARACTERISTIC.
3949 If the CHARACTERISTIC is the symbol `fierce',
3950 then warn of a tiger."
3951 (if (equal characteristic 'fierce)
3952 (message "It's a tiger!")))
3953 @end group
3954 @end smallexample
3955
3956 @need 1500
3957 @noindent
3958 If you are reading this inside of GNU Emacs, you can evaluate the
3959 function definition in the usual way to install it in Emacs, and then you
3960 can evaluate the following two expressions to see the results:
3961
3962 @smallexample
3963 @group
3964 (type-of-animal 'fierce)
3965
3966 (type-of-animal 'zebra)
3967
3968 @end group
3969 @end smallexample
3970
3971 @c Following sentences rewritten to prevent overfull hbox.
3972 @noindent
3973 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3974 following message printed in the echo area: @code{"It's a tiger!"}; and
3975 when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3976 printed in the echo area.
3977
3978 @node type-of-animal in detail
3979 @subsection The @code{type-of-animal} Function in Detail
3980
3981 Let's look at the @code{type-of-animal} function in detail.
3982
3983 The function definition for @code{type-of-animal} was written by filling
3984 the slots of two templates, one for a function definition as a whole, and
3985 a second for an @code{if} expression.
3986
3987 @need 1250
3988 The template for every function that is not interactive is:
3989
3990 @smallexample
3991 @group
3992 (defun @var{name-of-function} (@var{argument-list})
3993 "@var{documentation}@dots{}"
3994 @var{body}@dots{})
3995 @end group
3996 @end smallexample
3997
3998 @need 800
3999 The parts of the function that match this template look like this:
4000
4001 @smallexample
4002 @group
4003 (defun type-of-animal (characteristic)
4004 "Print message in echo area depending on CHARACTERISTIC.
4005 If the CHARACTERISTIC is the symbol `fierce',
4006 then warn of a tiger."
4007 @var{body: the} @code{if} @var{expression})
4008 @end group
4009 @end smallexample
4010
4011 The name of function is @code{type-of-animal}; it is passed the value
4012 of one argument. The argument list is followed by a multi-line
4013 documentation string. The documentation string is included in the
4014 example because it is a good habit to write documentation string for
4015 every function definition. The body of the function definition
4016 consists of the @code{if} expression.
4017
4018 @need 800
4019 The template for an @code{if} expression looks like this:
4020
4021 @smallexample
4022 @group
4023 (if @var{true-or-false-test}
4024 @var{action-to-carry-out-if-the-test-returns-true})
4025 @end group
4026 @end smallexample
4027
4028 @need 1250
4029 In the @code{type-of-animal} function, the code for the @code{if}
4030 looks like this:
4031
4032 @smallexample
4033 @group
4034 (if (equal characteristic 'fierce)
4035 (message "It's a tiger!")))
4036 @end group
4037 @end smallexample
4038
4039 @need 800
4040 Here, the true-or-false-test is the expression:
4041
4042 @smallexample
4043 (equal characteristic 'fierce)
4044 @end smallexample
4045
4046 @noindent
4047 In Lisp, @code{equal} is a function that determines whether its first
4048 argument is equal to its second argument. The second argument is the
4049 quoted symbol @code{'fierce} and the first argument is the value of the
4050 symbol @code{characteristic}---in other words, the argument passed to
4051 this function.
4052
4053 In the first exercise of @code{type-of-animal}, the argument
4054 @code{fierce} is passed to @code{type-of-animal}. Since @code{fierce}
4055 is equal to @code{fierce}, the expression, @code{(equal characteristic
4056 'fierce)}, returns a value of true. When this happens, the @code{if}
4057 evaluates the second argument or then-part of the @code{if}:
4058 @code{(message "It's tiger!")}.
4059
4060 On the other hand, in the second exercise of @code{type-of-animal}, the
4061 argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra}
4062 is not equal to @code{fierce}, so the then-part is not evaluated and
4063 @code{nil} is returned by the @code{if} expression.
4064
4065 @node else
4066 @section If--then--else Expressions
4067 @cindex Else
4068
4069 An @code{if} expression may have an optional third argument, called
4070 the @dfn{else-part}, for the case when the true-or-false-test returns
4071 false. When this happens, the second argument or then-part of the
4072 overall @code{if} expression is @emph{not} evaluated, but the third or
4073 else-part @emph{is} evaluated. You might think of this as the cloudy
4074 day alternative for the decision ``if it is warm and sunny, then go to
4075 the beach, else read a book!''.
4076
4077 The word ``else'' is not written in the Lisp code; the else-part of an
4078 @code{if} expression comes after the then-part. In the written Lisp, the
4079 else-part is usually written to start on a line of its own and is
4080 indented less than the then-part:
4081
4082 @smallexample
4083 @group
4084 (if @var{true-or-false-test}
4085 @var{action-to-carry-out-if-the-test-returns-true}
4086 @var{action-to-carry-out-if-the-test-returns-false})
4087 @end group
4088 @end smallexample
4089
4090 For example, the following @code{if} expression prints the message @samp{4
4091 is not greater than 5!} when you evaluate it in the usual way:
4092
4093 @smallexample
4094 @group
4095 (if (> 4 5) ; @r{if-part}
4096 (message "4 falsely greater than 5!") ; @r{then-part}
4097 (message "4 is not greater than 5!")) ; @r{else-part}
4098 @end group
4099 @end smallexample
4100
4101 @noindent
4102 Note that the different levels of indentation make it easy to
4103 distinguish the then-part from the else-part. (GNU Emacs has several
4104 commands that automatically indent @code{if} expressions correctly.
4105 @xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4106
4107 We can extend the @code{type-of-animal} function to include an
4108 else-part by simply incorporating an additional part to the @code{if}
4109 expression.
4110
4111 @need 1500
4112 You can see the consequences of doing this if you evaluate the following
4113 version of the @code{type-of-animal} function definition to install it
4114 and then evaluate the two subsequent expressions to pass different
4115 arguments to the function.
4116
4117 @smallexample
4118 @group
4119 (defun type-of-animal (characteristic) ; @r{Second version.}
4120 "Print message in echo area depending on CHARACTERISTIC.
4121 If the CHARACTERISTIC is the symbol `fierce',
4122 then warn of a tiger;
4123 else say it's not fierce."
4124 (if (equal characteristic 'fierce)
4125 (message "It's a tiger!")
4126 (message "It's not fierce!")))
4127 @end group
4128 @end smallexample
4129 @sp 1
4130
4131 @smallexample
4132 @group
4133 (type-of-animal 'fierce)
4134
4135 (type-of-animal 'zebra)
4136
4137 @end group
4138 @end smallexample
4139
4140 @c Following sentence rewritten to prevent overfull hbox.
4141 @noindent
4142 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4143 following message printed in the echo area: @code{"It's a tiger!"}; but
4144 when you evaluate @code{(type-of-animal 'zebra)}, you will see
4145 @code{"It's not fierce!"}.
4146
4147 (Of course, if the @var{characteristic} were @code{ferocious}, the
4148 message @code{"It's not fierce!"} would be printed; and it would be
4149 misleading! When you write code, you need to take into account the
4150 possibility that some such argument will be tested by the @code{if}
4151 and write your program accordingly.)
4152
4153 @node Truth & Falsehood
4154 @section Truth and Falsehood in Emacs Lisp
4155 @cindex Truth and falsehood in Emacs Lisp
4156 @cindex Falsehood and truth in Emacs Lisp
4157 @findex nil
4158
4159 There is an important aspect to the truth test in an @code{if}
4160 expression. So far, we have spoken of `true' and `false' as values of
4161 predicates as if they were new kinds of Emacs Lisp objects. In fact,
4162 `false' is just our old friend @code{nil}. Anything else---anything
4163 at all---is `true'.
4164
4165 The expression that tests for truth is interpreted as @dfn{true}
4166 if the result of evaluating it is a value that is not @code{nil}. In
4167 other words, the result of the test is considered true if the value
4168 returned is a number such as 47, a string such as @code{"hello"}, or a
4169 symbol (other than @code{nil}) such as @code{flowers}, or a list (so
4170 long as it is not empty), or even a buffer!
4171
4172 @menu
4173 * nil explained:: @code{nil} has two meanings.
4174 @end menu
4175
4176 @ifnottex
4177 @node nil explained
4178 @unnumberedsubsec An explanation of @code{nil}
4179 @end ifnottex
4180
4181 Before illustrating a test for truth, we need an explanation of @code{nil}.
4182
4183 In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the
4184 empty list. Second, it means false and is the value returned when a
4185 true-or-false-test tests false. @code{nil} can be written as an empty
4186 list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is
4187 concerned, @code{()} and @code{nil} are the same. Humans, however, tend
4188 to use @code{nil} for false and @code{()} for the empty list.
4189
4190 In Emacs Lisp, any value that is not @code{nil}---is not the empty
4191 list---is considered true. This means that if an evaluation returns
4192 something that is not an empty list, an @code{if} expression will test
4193 true. For example, if a number is put in the slot for the test, it
4194 will be evaluated and will return itself, since that is what numbers
4195 do when evaluated. In this conditional, the @code{if} expression will
4196 test true. The expression tests false only when @code{nil}, an empty
4197 list, is returned by evaluating the expression.
4198
4199 You can see this by evaluating the two expressions in the following examples.
4200
4201 In the first example, the number 4 is evaluated as the test in the
4202 @code{if} expression and returns itself; consequently, the then-part
4203 of the expression is evaluated and returned: @samp{true} appears in
4204 the echo area. In the second example, the @code{nil} indicates false;
4205 consequently, the else-part of the expression is evaluated and
4206 returned: @samp{false} appears in the echo area.
4207
4208 @smallexample
4209 @group
4210 (if 4
4211 'true
4212 'false)
4213 @end group
4214
4215 @group
4216 (if nil
4217 'true
4218 'false)
4219 @end group
4220 @end smallexample
4221
4222 @need 1250
4223 Incidentally, if some other useful value is not available for a test that
4224 returns true, then the Lisp interpreter will return the symbol @code{t}
4225 for true. For example, the expression @code{(> 5 4)} returns @code{t}
4226 when evaluated, as you can see by evaluating it in the usual way:
4227
4228 @smallexample
4229 (> 5 4)
4230 @end smallexample
4231
4232 @need 1250
4233 @noindent
4234 On the other hand, this function returns @code{nil} if the test is false.
4235
4236 @smallexample
4237 (> 4 5)
4238 @end smallexample
4239
4240 @node save-excursion
4241 @section @code{save-excursion}
4242 @findex save-excursion
4243 @cindex Region, what it is
4244 @cindex Preserving point, mark, and buffer
4245 @cindex Point, mark, buffer preservation
4246 @findex point
4247 @findex mark
4248
4249 The @code{save-excursion} function is the fourth and final special form
4250 that we will discuss in this chapter.
4251
4252 In Emacs Lisp programs used for editing, the @code{save-excursion}
4253 function is very common. It saves the location of point and mark,
4254 executes the body of the function, and then restores point and mark to
4255 their previous positions if their locations were changed. Its primary
4256 purpose is to keep the user from being surprised and disturbed by
4257 unexpected movement of point or mark.
4258
4259 @menu
4260 * Point and mark:: A review of various locations.
4261 * Template for save-excursion::
4262 @end menu
4263
4264 @ifnottex
4265 @node Point and mark
4266 @unnumberedsubsec Point and Mark
4267 @end ifnottex
4268
4269 Before discussing @code{save-excursion}, however, it may be useful
4270 first to review what point and mark are in GNU Emacs. @dfn{Point} is
4271 the current location of the cursor. Wherever the cursor
4272 is, that is point. More precisely, on terminals where the cursor
4273 appears to be on top of a character, point is immediately before the
4274 character. In Emacs Lisp, point is an integer. The first character in
4275 a buffer is number one, the second is number two, and so on. The
4276 function @code{point} returns the current position of the cursor as a
4277 number. Each buffer has its own value for point.
4278
4279 The @dfn{mark} is another position in the buffer; its value can be set
4280 with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If
4281 a mark has been set, you can use the command @kbd{C-x C-x}
4282 (@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4283 and set the mark to be the previous position of point. In addition, if
4284 you set another mark, the position of the previous mark is saved in the
4285 mark ring. Many mark positions can be saved this way. You can jump the
4286 cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4287 times.
4288
4289 The part of the buffer between point and mark is called @dfn{the
4290 region}. Numerous commands work on the region, including
4291 @code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4292 @code{print-region}.
4293
4294 The @code{save-excursion} special form saves the locations of point and
4295 mark and restores those positions after the code within the body of the
4296 special form is evaluated by the Lisp interpreter. Thus, if point were
4297 in the beginning of a piece of text and some code moved point to the end
4298 of the buffer, the @code{save-excursion} would put point back to where
4299 it was before, after the expressions in the body of the function were
4300 evaluated.
4301
4302 In Emacs, a function frequently moves point as part of its internal
4303 workings even though a user would not expect this. For example,
4304 @code{count-lines-region} moves point. To prevent the user from being
4305 bothered by jumps that are both unexpected and (from the user's point of
4306 view) unnecessary, @code{save-excursion} is often used to keep point and
4307 mark in the location expected by the user. The use of
4308 @code{save-excursion} is good housekeeping.
4309
4310 To make sure the house stays clean, @code{save-excursion} restores the
4311 values of point and mark even if something goes wrong in the code inside
4312 of it (or, to be more precise and to use the proper jargon, ``in case of
4313 abnormal exit''). This feature is very helpful.
4314
4315 In addition to recording the values of point and mark,
4316 @code{save-excursion} keeps track of the current buffer, and restores
4317 it, too. This means you can write code that will change the buffer and
4318 have @code{save-excursion} switch you back to the original buffer.
4319 This is how @code{save-excursion} is used in @code{append-to-buffer}.
4320 (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4321
4322 @node Template for save-excursion
4323 @subsection Template for a @code{save-excursion} Expression
4324
4325 @need 800
4326 The template for code using @code{save-excursion} is simple:
4327
4328 @smallexample
4329 @group
4330 (save-excursion
4331 @var{body}@dots{})
4332 @end group
4333 @end smallexample
4334
4335 @noindent
4336 The body of the function is one or more expressions that will be
4337 evaluated in sequence by the Lisp interpreter. If there is more than
4338 one expression in the body, the value of the last one will be returned
4339 as the value of the @code{save-excursion} function. The other
4340 expressions in the body are evaluated only for their side effects; and
4341 @code{save-excursion} itself is used only for its side effect (which
4342 is restoring the positions of point and mark).
4343
4344 @need 1250
4345 In more detail, the template for a @code{save-excursion} expression
4346 looks like this:
4347
4348 @smallexample
4349 @group
4350 (save-excursion
4351 @var{first-expression-in-body}
4352 @var{second-expression-in-body}
4353 @var{third-expression-in-body}
4354 @dots{}
4355 @var{last-expression-in-body})
4356 @end group
4357 @end smallexample
4358
4359 @noindent
4360 An expression, of course, may be a symbol on its own or a list.
4361
4362 In Emacs Lisp code, a @code{save-excursion} expression often occurs
4363 within the body of a @code{let} expression. It looks like this:
4364
4365 @smallexample
4366 @group
4367 (let @var{varlist}
4368 (save-excursion
4369 @var{body}@dots{}))
4370 @end group
4371 @end smallexample
4372
4373 @node Review
4374 @section Review
4375
4376 In the last few chapters we have introduced a fair number of functions
4377 and special forms. Here they are described in brief, along with a few
4378 similar functions that have not been mentioned yet.
4379
4380 @table @code
4381 @item eval-last-sexp
4382 Evaluate the last symbolic expression before the current location of
4383 point. The value is printed in the echo area unless the function is
4384 invoked with an argument; in that case, the output is printed in the
4385 current buffer. This command is normally bound to @kbd{C-x C-e}.
4386
4387 @item defun
4388 Define function. This special form has up to five parts: the name,
4389 a template for the arguments that will be passed to the function,
4390 documentation, an optional interactive declaration, and the body of the
4391 definition.
4392
4393 @need 1250
4394 For example, in an early version of Emacs, the function definition was
4395 as follows. (It is slightly more complex now that it seeks the first
4396 non-whitespace character rather than the first visible character.)
4397
4398 @smallexample
4399 @group
4400 (defun back-to-indentation ()
4401 "Move point to first visible character on line."
4402 (interactive)
4403 (beginning-of-line 1)
4404 (skip-chars-forward " \t"))
4405 @end group
4406 @end smallexample
4407
4408 @ignore
4409 In GNU Emacs 22,
4410
4411 (defun backward-to-indentation (&optional arg)
4412 "Move backward ARG lines and position at first nonblank character."
4413 (interactive "p")
4414 (forward-line (- (or arg 1)))
4415 (skip-chars-forward " \t"))
4416
4417 (defun back-to-indentation ()
4418 "Move point to the first non-whitespace character on this line."
4419 (interactive)
4420 (beginning-of-line 1)
4421 (skip-syntax-forward " " (line-end-position))
4422 ;; Move back over chars that have whitespace syntax but have the p flag.
4423 (backward-prefix-chars))
4424 @end ignore
4425
4426 @item interactive
4427 Declare to the interpreter that the function can be used
4428 interactively. This special form may be followed by a string with one
4429 or more parts that pass the information to the arguments of the
4430 function, in sequence. These parts may also tell the interpreter to
4431 prompt for information. Parts of the string are separated by
4432 newlines, @samp{\n}.
4433
4434 @need 1000
4435 Common code characters are:
4436
4437 @table @code
4438 @item b
4439 The name of an existing buffer.
4440
4441 @item f
4442 The name of an existing file.
4443
4444 @item p
4445 The numeric prefix argument. (Note that this `p' is lower case.)
4446
4447 @item r
4448 Point and the mark, as two numeric arguments, smallest first. This
4449 is the only code letter that specifies two successive arguments
4450 rather than one.
4451 @end table
4452
4453 @xref{Interactive Codes, , Code Characters for @samp{interactive},
4454 elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4455 code characters.
4456
4457 @item let
4458 Declare that a list of variables is for use within the body of the
4459 @code{let} and give them an initial value, either @code{nil} or a
4460 specified value; then evaluate the rest of the expressions in the body
4461 of the @code{let} and return the value of the last one. Inside the
4462 body of the @code{let}, the Lisp interpreter does not see the values of
4463 the variables of the same names that are bound outside of the
4464 @code{let}.
4465
4466 @need 1250
4467 For example,
4468
4469 @smallexample
4470 @group
4471 (let ((foo (buffer-name))
4472 (bar (buffer-size)))
4473 (message
4474 "This buffer is %s and has %d characters."
4475 foo bar))
4476 @end group
4477 @end smallexample
4478
4479 @item save-excursion
4480 Record the values of point and mark and the current buffer before
4481 evaluating the body of this special form. Restore the values of point
4482 and mark and buffer afterward.
4483
4484 @need 1250
4485 For example,
4486
4487 @smallexample
4488 @group
4489 (message "We are %d characters into this buffer."
4490 (- (point)
4491 (save-excursion
4492 (goto-char (point-min)) (point))))
4493 @end group
4494 @end smallexample
4495
4496 @item if
4497 Evaluate the first argument to the function; if it is true, evaluate
4498 the second argument; else evaluate the third argument, if there is one.
4499
4500 The @code{if} special form is called a @dfn{conditional}. There are
4501 other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4502 commonly used.
4503
4504 @need 1250
4505 For example,
4506
4507 @smallexample
4508 @group
4509 (if (= 22 emacs-major-version)
4510 (message "This is version 22 Emacs")
4511 (message "This is not version 22 Emacs"))
4512 @end group
4513 @end smallexample
4514
4515 @need 1250
4516 @item <
4517 @itemx >
4518 @itemx <=
4519 @itemx >=
4520 The @code{<} function tests whether its first argument is smaller than
4521 its second argument. A corresponding function, @code{>}, tests whether
4522 the first argument is greater than the second. Likewise, @code{<=}
4523 tests whether the first argument is less than or equal to the second and
4524 @code{>=} tests whether the first argument is greater than or equal to
4525 the second. In all cases, both arguments must be numbers or markers
4526 (markers indicate positions in buffers).
4527
4528 @need 800
4529 @item =
4530 The @code{=} function tests whether two arguments, both numbers or
4531 markers, are equal.
4532
4533 @need 1250
4534 @item equal
4535 @itemx eq
4536 Test whether two objects are the same. @code{equal} uses one meaning
4537 of the word `same' and @code{eq} uses another: @code{equal} returns
4538 true if the two objects have a similar structure and contents, such as
4539 two copies of the same book. On the other hand, @code{eq}, returns
4540 true if both arguments are actually the same object.
4541 @findex equal
4542 @findex eq
4543
4544 @need 1250
4545 @item string<
4546 @itemx string-lessp
4547 @itemx string=
4548 @itemx string-equal
4549 The @code{string-lessp} function tests whether its first argument is
4550 smaller than the second argument. A shorter, alternative name for the
4551 same function (a @code{defalias}) is @code{string<}.
4552
4553 The arguments to @code{string-lessp} must be strings or symbols; the
4554 ordering is lexicographic, so case is significant. The print names of
4555 symbols are used instead of the symbols themselves.
4556
4557 @cindex @samp{empty string} defined
4558 An empty string, @samp{""}, a string with no characters in it, is
4559 smaller than any string of characters.
4560
4561 @code{string-equal} provides the corresponding test for equality. Its
4562 shorter, alternative name is @code{string=}. There are no string test
4563 functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4564
4565 @item message
4566 Print a message in the echo area. The first argument is a string that
4567 can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4568 arguments that follow the string. The argument used by @samp{%s} must
4569 be a string or a symbol; the argument used by @samp{%d} must be a
4570 number. The argument used by @samp{%c} must be an @sc{ascii} code
4571 number; it will be printed as the character with that @sc{ascii} code.
4572 (Various other %-sequences have not been mentioned.)
4573
4574 @item setq
4575 @itemx set
4576 The @code{setq} function sets the value of its first argument to the
4577 value of the second argument. The first argument is automatically
4578 quoted by @code{setq}. It does the same for succeeding pairs of
4579 arguments. Another function, @code{set}, takes only two arguments and
4580 evaluates both of them before setting the value returned by its first
4581 argument to the value returned by its second argument.
4582
4583 @item buffer-name
4584 Without an argument, return the name of the buffer, as a string.
4585
4586 @itemx buffer-file-name
4587 Without an argument, return the name of the file the buffer is
4588 visiting.
4589
4590 @item current-buffer
4591 Return the buffer in which Emacs is active; it may not be
4592 the buffer that is visible on the screen.
4593
4594 @item other-buffer
4595 Return the most recently selected buffer (other than the buffer passed
4596 to @code{other-buffer} as an argument and other than the current
4597 buffer).
4598
4599 @item switch-to-buffer
4600 Select a buffer for Emacs to be active in and display it in the current
4601 window so users can look at it. Usually bound to @kbd{C-x b}.
4602
4603 @item set-buffer
4604 Switch Emacs's attention to a buffer on which programs will run. Don't
4605 alter what the window is showing.
4606
4607 @item buffer-size
4608 Return the number of characters in the current buffer.
4609
4610 @item point
4611 Return the value of the current position of the cursor, as an
4612 integer counting the number of characters from the beginning of the
4613 buffer.
4614
4615 @item point-min
4616 Return the minimum permissible value of point in
4617 the current buffer. This is 1, unless narrowing is in effect.
4618
4619 @item point-max
4620 Return the value of the maximum permissible value of point in the
4621 current buffer. This is the end of the buffer, unless narrowing is in
4622 effect.
4623 @end table
4624
4625 @need 1500
4626 @node defun Exercises
4627 @section Exercises
4628
4629 @itemize @bullet
4630 @item
4631 Write a non-interactive function that doubles the value of its
4632 argument, a number. Make that function interactive.
4633
4634 @item
4635 Write a function that tests whether the current value of
4636 @code{fill-column} is greater than the argument passed to the function,
4637 and if so, prints an appropriate message.
4638 @end itemize
4639
4640 @node Buffer Walk Through
4641 @chapter A Few Buffer--Related Functions
4642
4643 In this chapter we study in detail several of the functions used in GNU
4644 Emacs. This is called a ``walk-through''. These functions are used as
4645 examples of Lisp code, but are not imaginary examples; with the
4646 exception of the first, simplified function definition, these functions
4647 show the actual code used in GNU Emacs. You can learn a great deal from
4648 these definitions. The functions described here are all related to
4649 buffers. Later, we will study other functions.
4650
4651 @menu
4652 * Finding More:: How to find more information.
4653 * simplified-beginning-of-buffer:: Shows @code{goto-char},
4654 @code{point-min}, and @code{push-mark}.
4655 * mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
4656 * append-to-buffer:: Uses @code{save-excursion} and
4657 @code{insert-buffer-substring}.
4658 * Buffer Related Review:: Review.
4659 * Buffer Exercises::
4660 @end menu
4661
4662 @node Finding More
4663 @section Finding More Information
4664
4665 @findex describe-function, @r{introduced}
4666 @cindex Find function documentation
4667 In this walk-through, I will describe each new function as we come to
4668 it, sometimes in detail and sometimes briefly. If you are interested,
4669 you can get the full documentation of any Emacs Lisp function at any
4670 time by typing @kbd{C-h f} and then the name of the function (and then
4671 @key{RET}). Similarly, you can get the full documentation for a
4672 variable by typing @kbd{C-h v} and then the name of the variable (and
4673 then @key{RET}).
4674
4675 @cindex Find source of function
4676 @c In version 22, tells location both of C and of Emacs Lisp
4677 Also, @code{describe-function} will tell you the location of the
4678 function definition.
4679
4680 Put point into the name of the file that contains the function and
4681 press the @key{RET} key. In this case, @key{RET} means
4682 @code{push-button} rather than `return' or `enter'. Emacs will take
4683 you directly to the function definition.
4684
4685 @ignore
4686 Not In version 22
4687
4688 If you move point over the file name and press
4689 the @key{RET} key, which in this case means @code{help-follow} rather
4690 than `return' or `enter', Emacs will take you directly to the function
4691 definition.
4692 @end ignore
4693
4694 More generally, if you want to see a function in its original source
4695 file, you can use the @code{find-tag} function to jump to it.
4696 @code{find-tag} works with a wide variety of languages, not just
4697 Lisp, and C, and it works with non-programming text as well. For
4698 example, @code{find-tag} will jump to the various nodes in the
4699 Texinfo source file of this document.
4700 The @code{find-tag} function depends on `tags tables' that record
4701 the locations of the functions, variables, and other items to which
4702 @code{find-tag} jumps.
4703
4704 To use the @code{find-tag} command, type @kbd{M-.} (i.e., press the
4705 period key while holding down the @key{META} key, or else type the
4706 @key{ESC} key and then type the period key), and then, at the prompt,
4707 type in the name of the function whose source code you want to see,
4708 such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will
4709 switch buffers and display the source code for the function on your
4710 screen. To switch back to your current buffer, type @kbd{C-x b
4711 @key{RET}}. (On some keyboards, the @key{META} key is labeled
4712 @key{ALT}.)
4713
4714 @c !!! 22.1.1 tags table location in this paragraph
4715 @cindex TAGS table, specifying
4716 @findex find-tag
4717 Depending on how the initial default values of your copy of Emacs are
4718 set, you may also need to specify the location of your `tags table',
4719 which is a file called @file{TAGS}. For example, if you are
4720 interested in Emacs sources, the tags table you will most likely want,
4721 if it has already been created for you, will be in a subdirectory of
4722 the @file{/usr/local/share/emacs/} directory; thus you would use the
4723 @code{M-x visit-tags-table} command and specify a pathname such as
4724 @file{/usr/local/share/emacs/22.1.1/lisp/TAGS}. If the tags table
4725 has not already been created, you will have to create it yourself. It
4726 will be in a file such as @file{/usr/local/src/emacs/src/TAGS}.
4727
4728 @need 1250
4729 To create a @file{TAGS} file in a specific directory, switch to that
4730 directory in Emacs using @kbd{M-x cd} command, or list the directory
4731 with @kbd{C-x d} (@code{dired}). Then run the compile command, with
4732 @w{@code{etags *.el}} as the command to execute:
4733
4734 @smallexample
4735 M-x compile RET etags *.el RET
4736 @end smallexample
4737
4738 For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4739
4740 After you become more familiar with Emacs Lisp, you will find that you will
4741 frequently use @code{find-tag} to navigate your way around source code;
4742 and you will create your own @file{TAGS} tables.
4743
4744 @cindex Library, as term for `file'
4745 Incidentally, the files that contain Lisp code are conventionally
4746 called @dfn{libraries}. The metaphor is derived from that of a
4747 specialized library, such as a law library or an engineering library,
4748 rather than a general library. Each library, or file, contains
4749 functions that relate to a particular topic or activity, such as
4750 @file{abbrev.el} for handling abbreviations and other typing
4751 shortcuts, and @file{help.el} for on-line help. (Sometimes several
4752 libraries provide code for a single activity, as the various
4753 @file{rmail@dots{}} files provide code for reading electronic mail.)
4754 In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4755 @kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4756 by topic keywords.''
4757
4758 @node simplified-beginning-of-buffer
4759 @section A Simplified @code{beginning-of-buffer} Definition
4760 @findex simplified-beginning-of-buffer
4761
4762 The @code{beginning-of-buffer} command is a good function to start with
4763 since you are likely to be familiar with it and it is easy to
4764 understand. Used as an interactive command, @code{beginning-of-buffer}
4765 moves the cursor to the beginning of the buffer, leaving the mark at the
4766 previous position. It is generally bound to @kbd{M-<}.
4767
4768 In this section, we will discuss a shortened version of the function
4769 that shows how it is most frequently used. This shortened function
4770 works as written, but it does not contain the code for a complex option.
4771 In another section, we will describe the entire function.
4772 (@xref{beginning-of-buffer, , Complete Definition of
4773 @code{beginning-of-buffer}}.)
4774
4775 Before looking at the code, let's consider what the function
4776 definition has to contain: it must include an expression that makes
4777 the function interactive so it can be called by typing @kbd{M-x
4778 beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
4779 must include code to leave a mark at the original position in the
4780 buffer; and it must include code to move the cursor to the beginning
4781 of the buffer.
4782
4783 @need 1250
4784 Here is the complete text of the shortened version of the function:
4785
4786 @smallexample
4787 @group
4788 (defun simplified-beginning-of-buffer ()
4789 "Move point to the beginning of the buffer;
4790 leave mark at previous position."
4791 (interactive)
4792 (push-mark)
4793 (goto-char (point-min)))
4794 @end group
4795 @end smallexample
4796
4797 Like all function definitions, this definition has five parts following
4798 the special form @code{defun}:
4799
4800 @enumerate
4801 @item
4802 The name: in this example, @code{simplified-beginning-of-buffer}.
4803
4804 @item
4805 A list of the arguments: in this example, an empty list, @code{()},
4806
4807 @item
4808 The documentation string.
4809
4810 @item
4811 The interactive expression.
4812
4813 @item
4814 The body.
4815 @end enumerate
4816
4817 @noindent
4818 In this function definition, the argument list is empty; this means that
4819 this function does not require any arguments. (When we look at the
4820 definition for the complete function, we will see that it may be passed
4821 an optional argument.)
4822
4823 The interactive expression tells Emacs that the function is intended to
4824 be used interactively. In this example, @code{interactive} does not have
4825 an argument because @code{simplified-beginning-of-buffer} does not
4826 require one.
4827
4828 @need 800
4829 The body of the function consists of the two lines:
4830
4831 @smallexample
4832 @group
4833 (push-mark)
4834 (goto-char (point-min))
4835 @end group
4836 @end smallexample
4837
4838 The first of these lines is the expression, @code{(push-mark)}. When
4839 this expression is evaluated by the Lisp interpreter, it sets a mark at
4840 the current position of the cursor, wherever that may be. The position
4841 of this mark is saved in the mark ring.
4842
4843 The next line is @code{(goto-char (point-min))}. This expression
4844 jumps the cursor to the minimum point in the buffer, that is, to the
4845 beginning of the buffer (or to the beginning of the accessible portion
4846 of the buffer if it is narrowed. @xref{Narrowing & Widening, ,
4847 Narrowing and Widening}.)
4848
4849 The @code{push-mark} command sets a mark at the place where the cursor
4850 was located before it was moved to the beginning of the buffer by the
4851 @code{(goto-char (point-min))} expression. Consequently, you can, if
4852 you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4853
4854 That is all there is to the function definition!
4855
4856 @findex describe-function
4857 When you are reading code such as this and come upon an unfamiliar
4858 function, such as @code{goto-char}, you can find out what it does by
4859 using the @code{describe-function} command. To use this command, type
4860 @kbd{C-h f} and then type in the name of the function and press
4861 @key{RET}. The @code{describe-function} command will print the
4862 function's documentation string in a @file{*Help*} window. For
4863 example, the documentation for @code{goto-char} is:
4864
4865 @smallexample
4866 @group
4867 Set point to POSITION, a number or marker.
4868 Beginning of buffer is position (point-min), end is (point-max).
4869 @end group
4870 @end smallexample
4871
4872 @noindent
4873 The function's one argument is the desired position.
4874
4875 @noindent
4876 (The prompt for @code{describe-function} will offer you the symbol
4877 under or preceding the cursor, so you can save typing by positioning
4878 the cursor right over or after the function and then typing @kbd{C-h f
4879 @key{RET}}.)
4880
4881 The @code{end-of-buffer} function definition is written in the same way as
4882 the @code{beginning-of-buffer} definition except that the body of the
4883 function contains the expression @code{(goto-char (point-max))} in place
4884 of @code{(goto-char (point-min))}.
4885
4886 @node mark-whole-buffer
4887 @section The Definition of @code{mark-whole-buffer}
4888 @findex mark-whole-buffer
4889
4890 The @code{mark-whole-buffer} function is no harder to understand than the
4891 @code{simplified-beginning-of-buffer} function. In this case, however,
4892 we will look at the complete function, not a shortened version.
4893
4894 The @code{mark-whole-buffer} function is not as commonly used as the
4895 @code{beginning-of-buffer} function, but is useful nonetheless: it
4896 marks a whole buffer as a region by putting point at the beginning and
4897 a mark at the end of the buffer. It is generally bound to @kbd{C-x
4898 h}.
4899
4900 @menu
4901 * mark-whole-buffer overview::
4902 * Body of mark-whole-buffer:: Only three lines of code.
4903 @end menu
4904
4905 @ifnottex
4906 @node mark-whole-buffer overview
4907 @unnumberedsubsec An overview of @code{mark-whole-buffer}
4908 @end ifnottex
4909
4910 @need 1250
4911 In GNU Emacs 22, the code for the complete function looks like this:
4912
4913 @smallexample
4914 @group
4915 (defun mark-whole-buffer ()
4916 "Put point at beginning and mark at end of buffer.
4917 You probably should not use this function in Lisp programs;
4918 it is usually a mistake for a Lisp function to use any subroutine
4919 that uses or sets the mark."
4920 (interactive)
4921 (push-mark (point))
4922 (push-mark (point-max) nil t)
4923 (goto-char (point-min)))
4924 @end group
4925 @end smallexample
4926
4927 @need 1250
4928 Like all other functions, the @code{mark-whole-buffer} function fits
4929 into the template for a function definition. The template looks like
4930 this:
4931
4932 @smallexample
4933 @group
4934 (defun @var{name-of-function} (@var{argument-list})
4935 "@var{documentation}@dots{}"
4936 (@var{interactive-expression}@dots{})
4937 @var{body}@dots{})
4938 @end group
4939 @end smallexample
4940
4941 Here is how the function works: the name of the function is
4942 @code{mark-whole-buffer}; it is followed by an empty argument list,
4943 @samp{()}, which means that the function does not require arguments.
4944 The documentation comes next.
4945
4946 The next line is an @code{(interactive)} expression that tells Emacs
4947 that the function will be used interactively. These details are similar
4948 to the @code{simplified-beginning-of-buffer} function described in the
4949 previous section.
4950
4951 @need 1250
4952 @node Body of mark-whole-buffer
4953 @subsection Body of @code{mark-whole-buffer}
4954
4955 The body of the @code{mark-whole-buffer} function consists of three
4956 lines of code:
4957
4958 @c GNU Emacs 22
4959 @smallexample
4960 @group
4961 (push-mark (point))
4962 (push-mark (point-max) nil t)
4963 (goto-char (point-min))
4964 @end group
4965 @end smallexample
4966
4967 The first of these lines is the expression, @code{(push-mark (point))}.
4968
4969 This line does exactly the same job as the first line of the body of
4970 the @code{simplified-beginning-of-buffer} function, which is written
4971 @code{(push-mark)}. In both cases, the Lisp interpreter sets a mark
4972 at the current position of the cursor.
4973
4974 I don't know why the expression in @code{mark-whole-buffer} is written
4975 @code{(push-mark (point))} and the expression in
4976 @code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps
4977 whoever wrote the code did not know that the arguments for
4978 @code{push-mark} are optional and that if @code{push-mark} is not
4979 passed an argument, the function automatically sets mark at the
4980 location of point by default. Or perhaps the expression was written
4981 so as to parallel the structure of the next line. In any case, the
4982 line causes Emacs to determine the position of point and set a mark
4983 there.
4984
4985 In earlier versions of GNU Emacs, the next line of
4986 @code{mark-whole-buffer} was @code{(push-mark (point-max))}. This
4987 expression sets a mark at the point in the buffer that has the highest
4988 number. This will be the end of the buffer (or, if the buffer is
4989 narrowed, the end of the accessible portion of the buffer.
4990 @xref{Narrowing & Widening, , Narrowing and Widening}, for more about
4991 narrowing.) After this mark has been set, the previous mark, the one
4992 set at point, is no longer set, but Emacs remembers its position, just
4993 as all other recent marks are always remembered. This means that you
4994 can, if you wish, go back to that position by typing @kbd{C-u
4995 C-@key{SPC}} twice.
4996
4997 @need 1250
4998 In GNU Emacs 22, the @code{(point-max)} is slightly more complicated.
4999 The line reads
5000
5001 @smallexample
5002 (push-mark (point-max) nil t)
5003 @end smallexample
5004
5005 @noindent
5006 The expression works nearly the same as before. It sets a mark at the
5007 highest numbered place in the buffer that it can. However, in this
5008 version, @code{push-mark} has two additional arguments. The second
5009 argument to @code{push-mark} is @code{nil}. This tells the function
5010 it @emph{should} display a message that says `Mark set' when it pushes
5011 the mark. The third argument is @code{t}. This tells
5012 @code{push-mark} to activate the mark when Transient Mark mode is
5013 turned on. Transient Mark mode highlights the currently active
5014 region. It is often turned off.
5015
5016 Finally, the last line of the function is @code{(goto-char
5017 (point-min)))}. This is written exactly the same way as it is written
5018 in @code{beginning-of-buffer}. The expression moves the cursor to
5019 the minimum point in the buffer, that is, to the beginning of the buffer
5020 (or to the beginning of the accessible portion of the buffer). As a
5021 result of this, point is placed at the beginning of the buffer and mark
5022 is set at the end of the buffer. The whole buffer is, therefore, the
5023 region.
5024
5025 @node append-to-buffer
5026 @section The Definition of @code{append-to-buffer}
5027 @findex append-to-buffer
5028
5029 The @code{append-to-buffer} command is more complex than the
5030 @code{mark-whole-buffer} command. What it does is copy the region
5031 (that is, the part of the buffer between point and mark) from the
5032 current buffer to a specified buffer.
5033
5034 @menu
5035 * append-to-buffer overview::
5036 * append interactive:: A two part interactive expression.
5037 * append-to-buffer body:: Incorporates a @code{let} expression.
5038 * append save-excursion:: How the @code{save-excursion} works.
5039 @end menu
5040
5041 @ifnottex
5042 @node append-to-buffer overview
5043 @unnumberedsubsec An Overview of @code{append-to-buffer}
5044 @end ifnottex
5045
5046 @findex insert-buffer-substring
5047 The @code{append-to-buffer} command uses the
5048 @code{insert-buffer-substring} function to copy the region.
5049 @code{insert-buffer-substring} is described by its name: it takes a
5050 string of characters from part of a buffer, a ``substring'', and
5051 inserts them into another buffer.
5052
5053 Most of @code{append-to-buffer} is
5054 concerned with setting up the conditions for
5055 @code{insert-buffer-substring} to work: the code must specify both the
5056 buffer to which the text will go, the window it comes from and goes
5057 to, and the region that will be copied.
5058
5059 @need 1250
5060 Here is the complete text of the function:
5061
5062 @smallexample
5063 @group
5064 (defun append-to-buffer (buffer start end)
5065 "Append to specified buffer the text of the region.
5066 It is inserted into that buffer before its point.
5067 @end group
5068
5069 @group
5070 When calling from a program, give three arguments:
5071 BUFFER (or buffer name), START and END.
5072 START and END specify the portion of the current buffer to be copied."
5073 (interactive
5074 (list (read-buffer "Append to buffer: " (other-buffer
5075 (current-buffer) t))
5076 (region-beginning) (region-end)))
5077 @end group
5078 @group
5079 (let ((oldbuf (current-buffer)))
5080 (save-excursion
5081 (let* ((append-to (get-buffer-create buffer))
5082 (windows (get-buffer-window-list append-to t t))
5083 point)
5084 (set-buffer append-to)
5085 (setq point (point))
5086 (barf-if-buffer-read-only)
5087 (insert-buffer-substring oldbuf start end)
5088 (dolist (window windows)
5089 (when (= (window-point window) point)
5090 (set-window-point window (point))))))))
5091 @end group
5092 @end smallexample
5093
5094 The function can be understood by looking at it as a series of
5095 filled-in templates.
5096
5097 The outermost template is for the function definition. In this
5098 function, it looks like this (with several slots filled in):
5099
5100 @smallexample
5101 @group
5102 (defun append-to-buffer (buffer start end)
5103 "@var{documentation}@dots{}"
5104 (interactive @dots{})
5105 @var{body}@dots{})
5106 @end group
5107 @end smallexample
5108
5109 The first line of the function includes its name and three arguments.
5110 The arguments are the @code{buffer} to which the text will be copied, and
5111 the @code{start} and @code{end} of the region in the current buffer that
5112 will be copied.
5113
5114 The next part of the function is the documentation, which is clear and
5115 complete. As is conventional, the three arguments are written in
5116 upper case so you will notice them easily. Even better, they are
5117 described in the same order as in the argument list.
5118
5119 Note that the documentation distinguishes between a buffer and its
5120 name. (The function can handle either.)
5121
5122 @node append interactive
5123 @subsection The @code{append-to-buffer} Interactive Expression
5124
5125 Since the @code{append-to-buffer} function will be used interactively,
5126 the function must have an @code{interactive} expression. (For a
5127 review of @code{interactive}, see @ref{Interactive, , Making a
5128 Function Interactive}.) The expression reads as follows:
5129
5130 @smallexample
5131 @group
5132 (interactive
5133 (list (read-buffer
5134 "Append to buffer: "
5135 (other-buffer (current-buffer) t))
5136 (region-beginning)
5137 (region-end)))
5138 @end group
5139 @end smallexample
5140
5141 @noindent
5142 This expression is not one with letters standing for parts, as
5143 described earlier. Instead, it starts a list with these parts:
5144
5145 The first part of the list is an expression to read the name of a
5146 buffer and return it as a string. That is @code{read-buffer}. The
5147 function requires a prompt as its first argument, @samp{"Append to
5148 buffer: "}. Its second argument tells the command what value to
5149 provide if you don't specify anything.
5150
5151 In this case that second argument is an expression containing the
5152 function @code{other-buffer}, an exception, and a @samp{t}, standing
5153 for true.
5154
5155 The first argument to @code{other-buffer}, the exception, is yet
5156 another function, @code{current-buffer}. That is not going to be
5157 returned. The second argument is the symbol for true, @code{t}. that
5158 tells @code{other-buffer} that it may show visible buffers (except in
5159 this case, it will not show the current buffer, which makes sense).
5160
5161 @need 1250
5162 The expression looks like this:
5163
5164 @smallexample
5165 (other-buffer (current-buffer) t)
5166 @end smallexample
5167
5168 The second and third arguments to the @code{list} expression are
5169 @code{(region-beginning)} and @code{(region-end)}. These two
5170 functions specify the beginning and end of the text to be appended.
5171
5172 @need 1250
5173 Originally, the command used the letters @samp{B} and @samp{r}.
5174 The whole @code{interactive} expression looked like this:
5175
5176 @smallexample
5177 (interactive "BAppend to buffer:@: \nr")
5178 @end smallexample
5179
5180 @noindent
5181 But when that was done, the default value of the buffer switched to
5182 was invisible. That was not wanted.
5183
5184 (The prompt was separated from the second argument with a newline,
5185 @samp{\n}. It was followed by an @samp{r} that told Emacs to bind the
5186 two arguments that follow the symbol @code{buffer} in the function's
5187 argument list (that is, @code{start} and @code{end}) to the values of
5188 point and mark. That argument worked fine.)
5189
5190 @node append-to-buffer body
5191 @subsection The Body of @code{append-to-buffer}
5192
5193 @ignore
5194 in GNU Emacs 22 in /usr/local/src/emacs/lisp/simple.el
5195
5196 (defun append-to-buffer (buffer start end)
5197 "Append to specified buffer the text of the region.
5198 It is inserted into that buffer before its point.
5199
5200 When calling from a program, give three arguments:
5201 BUFFER (or buffer name), START and END.
5202 START and END specify the portion of the current buffer to be copied."
5203 (interactive
5204 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5205 (region-beginning) (region-end)))
5206 (let ((oldbuf (current-buffer)))
5207 (save-excursion
5208 (let* ((append-to (get-buffer-create buffer))
5209 (windows (get-buffer-window-list append-to t t))
5210 point)
5211 (set-buffer append-to)
5212 (setq point (point))
5213 (barf-if-buffer-read-only)
5214 (insert-buffer-substring oldbuf start end)
5215 (dolist (window windows)
5216 (when (= (window-point window) point)
5217 (set-window-point window (point))))))))
5218 @end ignore
5219
5220 The body of the @code{append-to-buffer} function begins with @code{let}.
5221
5222 As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5223 @code{let} expression is to create and give initial values to one or
5224 more variables that will only be used within the body of the
5225 @code{let}. This means that such a variable will not be confused with
5226 any variable of the same name outside the @code{let} expression.
5227
5228 We can see how the @code{let} expression fits into the function as a
5229 whole by showing a template for @code{append-to-buffer} with the
5230 @code{let} expression in outline:
5231
5232 @smallexample
5233 @group
5234 (defun append-to-buffer (buffer start end)
5235 "@var{documentation}@dots{}"
5236 (interactive @dots{})
5237 (let ((@var{variable} @var{value}))
5238 @var{body}@dots{})
5239 @end group
5240 @end smallexample
5241
5242 The @code{let} expression has three elements:
5243
5244 @enumerate
5245 @item
5246 The symbol @code{let};
5247
5248 @item
5249 A varlist containing, in this case, a single two-element list,
5250 @code{(@var{variable} @var{value})};
5251
5252 @item
5253 The body of the @code{let} expression.
5254 @end enumerate
5255
5256 @need 800
5257 In the @code{append-to-buffer} function, the varlist looks like this:
5258
5259 @smallexample
5260 (oldbuf (current-buffer))
5261 @end smallexample
5262
5263 @noindent
5264 In this part of the @code{let} expression, the one variable,
5265 @code{oldbuf}, is bound to the value returned by the
5266 @code{(current-buffer)} expression. The variable, @code{oldbuf}, is
5267 used to keep track of the buffer in which you are working and from
5268 which you will copy.
5269
5270 The element or elements of a varlist are surrounded by a set of
5271 parentheses so the Lisp interpreter can distinguish the varlist from
5272 the body of the @code{let}. As a consequence, the two-element list
5273 within the varlist is surrounded by a circumscribing set of parentheses.
5274 The line looks like this:
5275
5276 @smallexample
5277 @group
5278 (let ((oldbuf (current-buffer)))
5279 @dots{} )
5280 @end group
5281 @end smallexample
5282
5283 @noindent
5284 The two parentheses before @code{oldbuf} might surprise you if you did
5285 not realize that the first parenthesis before @code{oldbuf} marks the
5286 boundary of the varlist and the second parenthesis marks the beginning
5287 of the two-element list, @code{(oldbuf (current-buffer))}.
5288
5289 @node append save-excursion
5290 @subsection @code{save-excursion} in @code{append-to-buffer}
5291
5292 The body of the @code{let} expression in @code{append-to-buffer}
5293 consists of a @code{save-excursion} expression.
5294
5295 The @code{save-excursion} function saves the locations of point and
5296 mark, and restores them to those positions after the expressions in the
5297 body of the @code{save-excursion} complete execution. In addition,
5298 @code{save-excursion} keeps track of the original buffer, and
5299 restores it. This is how @code{save-excursion} is used in
5300 @code{append-to-buffer}.
5301
5302 @need 1500
5303 @cindex Indentation for formatting
5304 @cindex Formatting convention
5305 Incidentally, it is worth noting here that a Lisp function is normally
5306 formatted so that everything that is enclosed in a multi-line spread is
5307 indented more to the right than the first symbol. In this function
5308 definition, the @code{let} is indented more than the @code{defun}, and
5309 the @code{save-excursion} is indented more than the @code{let}, like
5310 this:
5311
5312 @smallexample
5313 @group
5314 (defun @dots{}
5315 @dots{}
5316 @dots{}
5317 (let@dots{}
5318 (save-excursion
5319 @dots{}
5320 @end group
5321 @end smallexample
5322
5323 @need 1500
5324 @noindent
5325 This formatting convention makes it easy to see that the lines in
5326 the body of the @code{save-excursion} are enclosed by the parentheses
5327 associated with @code{save-excursion}, just as the
5328 @code{save-excursion} itself is enclosed by the parentheses associated
5329 with the @code{let}:
5330
5331 @smallexample
5332 @group
5333 (let ((oldbuf (current-buffer)))
5334 (save-excursion
5335 @dots{}
5336 (set-buffer @dots{})
5337 (insert-buffer-substring oldbuf start end)
5338 @dots{}))
5339 @end group
5340 @end smallexample
5341
5342 @need 1200
5343 The use of the @code{save-excursion} function can be viewed as a process
5344 of filling in the slots of a template:
5345
5346 @smallexample
5347 @group
5348 (save-excursion
5349 @var{first-expression-in-body}
5350 @var{second-expression-in-body}
5351 @dots{}
5352 @var{last-expression-in-body})
5353 @end group
5354 @end smallexample
5355
5356 @need 1200
5357 @noindent
5358 In this function, the body of the @code{save-excursion} contains only
5359 one expression, the @code{let*} expression. You know about a
5360 @code{let} function. The @code{let*} function is different. It has a
5361 @samp{*} in its name. It enables Emacs to set each variable in its
5362 varlist in sequence, one after another.
5363
5364 Its critical feature is that variables later in the varlist can make
5365 use of the values to which Emacs set variables earlier in the varlist.
5366 @xref{fwd-para let, , The @code{let*} expression}.
5367
5368 We will skip functions like @code{let*} and focus on two: the
5369 @code{set-buffer} function and the @code{insert-buffer-substring}
5370 function.
5371
5372 @need 1250
5373 In the old days, the @code{set-buffer} expression was simply
5374
5375 @smallexample
5376 (set-buffer (get-buffer-create buffer))
5377 @end smallexample
5378
5379 @need 1250
5380 @noindent
5381 but now it is
5382
5383 @smallexample
5384 (set-buffer append-to)
5385 @end smallexample
5386
5387 @noindent
5388 @code{append-to} is bound to @code{(get-buffer-create buffer)} earlier
5389 on in the @code{let*} expression. That extra binding would not be
5390 necessary except for that @code{append-to} is used later in the
5391 varlist as an argument to @code{get-buffer-window-list}.
5392
5393 @ignore
5394 in GNU Emacs 22
5395
5396 (let ((oldbuf (current-buffer)))
5397 (save-excursion
5398 (let* ((append-to (get-buffer-create buffer))
5399 (windows (get-buffer-window-list append-to t t))
5400 point)
5401 (set-buffer append-to)
5402 (setq point (point))
5403 (barf-if-buffer-read-only)
5404 (insert-buffer-substring oldbuf start end)
5405 (dolist (window windows)
5406 (when (= (window-point window) point)
5407 (set-window-point window (point))))))))
5408 @end ignore
5409
5410 The @code{append-to-buffer} function definition inserts text from the
5411 buffer in which you are currently to a named buffer. It happens that
5412 @code{insert-buffer-substring} copies text from another buffer to the
5413 current buffer, just the reverse---that is why the
5414 @code{append-to-buffer} definition starts out with a @code{let} that
5415 binds the local symbol @code{oldbuf} to the value returned by
5416 @code{current-buffer}.
5417
5418 @need 1250
5419 The @code{insert-buffer-substring} expression looks like this:
5420
5421 @smallexample
5422 (insert-buffer-substring oldbuf start end)
5423 @end smallexample
5424
5425 @noindent
5426 The @code{insert-buffer-substring} function copies a string
5427 @emph{from} the buffer specified as its first argument and inserts the
5428 string into the present buffer. In this case, the argument to
5429 @code{insert-buffer-substring} is the value of the variable created
5430 and bound by the @code{let}, namely the value of @code{oldbuf}, which
5431 was the current buffer when you gave the @code{append-to-buffer}
5432 command.
5433
5434 After @code{insert-buffer-substring} has done its work,
5435 @code{save-excursion} will restore the action to the original buffer
5436 and @code{append-to-buffer} will have done its job.
5437
5438 @need 800
5439 Written in skeletal form, the workings of the body look like this:
5440
5441 @smallexample
5442 @group
5443 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5444 (save-excursion ; @r{Keep track of buffer.}
5445 @var{change-buffer}
5446 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5447
5448 @var{change-back-to-original-buffer-when-finished}
5449 @var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5450 @end group
5451 @end smallexample
5452
5453 In summary, @code{append-to-buffer} works as follows: it saves the
5454 value of the current buffer in the variable called @code{oldbuf}. It
5455 gets the new buffer (creating one if need be) and switches Emacs's
5456 attention to it. Using the value of @code{oldbuf}, it inserts the
5457 region of text from the old buffer into the new buffer; and then using
5458 @code{save-excursion}, it brings you back to your original buffer.
5459
5460 In looking at @code{append-to-buffer}, you have explored a fairly
5461 complex function. It shows how to use @code{let} and
5462 @code{save-excursion}, and how to change to and come back from another
5463 buffer. Many function definitions use @code{let},
5464 @code{save-excursion}, and @code{set-buffer} this way.
5465
5466 @node Buffer Related Review
5467 @section Review
5468
5469 Here is a brief summary of the various functions discussed in this chapter.
5470
5471 @table @code
5472 @item describe-function
5473 @itemx describe-variable
5474 Print the documentation for a function or variable.
5475 Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5476
5477 @item find-tag
5478 Find the file containing the source for a function or variable and
5479 switch buffers to it, positioning point at the beginning of the item.
5480 Conventionally bound to @kbd{M-.} (that's a period following the
5481 @key{META} key).
5482
5483 @item save-excursion
5484 Save the location of point and mark and restore their values after the
5485 arguments to @code{save-excursion} have been evaluated. Also, remember
5486 the current buffer and return to it.
5487
5488 @item push-mark
5489 Set mark at a location and record the value of the previous mark on the
5490 mark ring. The mark is a location in the buffer that will keep its
5491 relative position even if text is added to or removed from the buffer.
5492
5493 @item goto-char
5494 Set point to the location specified by the value of the argument, which
5495 can be a number, a marker, or an expression that returns the number of
5496 a position, such as @code{(point-min)}.
5497
5498 @item insert-buffer-substring
5499 Copy a region of text from a buffer that is passed to the function as
5500 an argument and insert the region into the current buffer.
5501
5502 @item mark-whole-buffer
5503 Mark the whole buffer as a region. Normally bound to @kbd{C-x h}.
5504
5505 @item set-buffer
5506 Switch the attention of Emacs to another buffer, but do not change the
5507 window being displayed. Used when the program rather than a human is
5508 to work on a different buffer.
5509
5510 @item get-buffer-create
5511 @itemx get-buffer
5512 Find a named buffer or create one if a buffer of that name does not
5513 exist. The @code{get-buffer} function returns @code{nil} if the named
5514 buffer does not exist.
5515 @end table
5516
5517 @need 1500
5518 @node Buffer Exercises
5519 @section Exercises
5520
5521 @itemize @bullet
5522 @item
5523 Write your own @code{simplified-end-of-buffer} function definition;
5524 then test it to see whether it works.
5525
5526 @item
5527 Use @code{if} and @code{get-buffer} to write a function that prints a
5528 message telling you whether a buffer exists.
5529
5530 @item
5531 Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5532 function.
5533 @end itemize
5534
5535 @node More Complex
5536 @chapter A Few More Complex Functions
5537
5538 In this chapter, we build on what we have learned in previous chapters
5539 by looking at more complex functions. The @code{copy-to-buffer}
5540 function illustrates use of two @code{save-excursion} expressions in
5541 one definition, while the @code{insert-buffer} function illustrates
5542 use of an asterisk in an @code{interactive} expression, use of
5543 @code{or}, and the important distinction between a name and the object
5544 to which the name refers.
5545
5546 @menu
5547 * copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
5548 * insert-buffer:: Read-only, and with @code{or}.
5549 * beginning-of-buffer:: Shows @code{goto-char},
5550 @code{point-min}, and @code{push-mark}.
5551 * Second Buffer Related Review::
5552 * optional Exercise::
5553 @end menu
5554
5555 @node copy-to-buffer
5556 @section The Definition of @code{copy-to-buffer}
5557 @findex copy-to-buffer
5558
5559 After understanding how @code{append-to-buffer} works, it is easy to
5560 understand @code{copy-to-buffer}. This function copies text into a
5561 buffer, but instead of adding to the second buffer, it replaces all the
5562 previous text in the second buffer.
5563
5564 @need 800
5565 The body of @code{copy-to-buffer} looks like this,
5566
5567 @smallexample
5568 @group
5569 @dots{}
5570 (interactive "BCopy to buffer: \nr")
5571 (let ((oldbuf (current-buffer)))
5572 (with-current-buffer (get-buffer-create buffer)
5573 (barf-if-buffer-read-only)
5574 (erase-buffer)
5575 (save-excursion
5576 (insert-buffer-substring oldbuf start end)))))
5577 @end group
5578 @end smallexample
5579
5580 The @code{copy-to-buffer} function has a simpler @code{interactive}
5581 expression than @code{append-to-buffer}.
5582
5583 @need 800
5584 The definition then says
5585
5586 @smallexample
5587 (with-current-buffer (get-buffer-create buffer) @dots{}
5588 @end smallexample
5589
5590 First, look at the earliest inner expression; that is evaluated first.
5591 That expression starts with @code{get-buffer-create buffer}. The
5592 function tells the computer to use the buffer with the name specified
5593 as the one to which you are copying, or if such a buffer does not
5594 exist, to create it. Then, the @code{with-current-buffer} function
5595 evaluates its body with that buffer temporarily current.
5596
5597 (This demonstrates another way to shift the computer's attention but
5598 not the user's. The @code{append-to-buffer} function showed how to do
5599 the same with @code{save-excursion} and @code{set-buffer}.
5600 @code{with-current-buffer} is a newer, and arguably easier,
5601 mechanism.)
5602
5603 The @code{barf-if-buffer-read-only} function sends you an error
5604 message saying the buffer is read-only if you cannot modify it.
5605
5606 The next line has the @code{erase-buffer} function as its sole
5607 contents. That function erases the buffer.
5608
5609 Finally, the last two lines contain the @code{save-excursion}
5610 expression with @code{insert-buffer-substring} as its body.
5611 The @code{insert-buffer-substring} expression copies the text from
5612 the buffer you are in (and you have not seen the computer shift its
5613 attention, so you don't know that that buffer is now called
5614 @code{oldbuf}).
5615
5616 Incidentally, this is what is meant by `replacement'. To replace text,
5617 Emacs erases the previous text and then inserts new text.
5618
5619 @need 1250
5620 In outline, the body of @code{copy-to-buffer} looks like this:
5621
5622 @smallexample
5623 @group
5624 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5625 (@var{with-the-buffer-you-are-copying-to}
5626 (@var{but-do-not-erase-or-copy-to-a-read-only-buffer})
5627 (erase-buffer)
5628 (save-excursion
5629 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5630 @end group
5631 @end smallexample
5632
5633 @node insert-buffer
5634 @section The Definition of @code{insert-buffer}
5635 @findex insert-buffer
5636
5637 @code{insert-buffer} is yet another buffer-related function. This
5638 command copies another buffer @emph{into} the current buffer. It is the
5639 reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5640 copy a region of text @emph{from} the current buffer to another buffer.
5641
5642 Here is a discussion based on the original code. The code was
5643 simplified in 2003 and is harder to understand.
5644
5645 (@xref{New insert-buffer, , New Body for @code{insert-buffer}}, to see
5646 a discussion of the new body.)
5647
5648 In addition, this code illustrates the use of @code{interactive} with a
5649 buffer that might be @dfn{read-only} and the important distinction
5650 between the name of an object and the object actually referred to.
5651
5652 @menu
5653 * insert-buffer code::
5654 * insert-buffer interactive:: When you can read, but not write.
5655 * insert-buffer body:: The body has an @code{or} and a @code{let}.
5656 * if & or:: Using an @code{if} instead of an @code{or}.
5657 * Insert or:: How the @code{or} expression works.
5658 * Insert let:: Two @code{save-excursion} expressions.
5659 * New insert-buffer::
5660 @end menu
5661
5662 @ifnottex
5663 @node insert-buffer code
5664 @unnumberedsubsec The Code for @code{insert-buffer}
5665 @end ifnottex
5666
5667 @need 800
5668 Here is the earlier code:
5669
5670 @smallexample
5671 @group
5672 (defun insert-buffer (buffer)
5673 "Insert after point the contents of BUFFER.
5674 Puts mark after the inserted text.
5675 BUFFER may be a buffer or a buffer name."
5676 (interactive "*bInsert buffer:@: ")
5677 @end group
5678 @group
5679 (or (bufferp buffer)
5680 (setq buffer (get-buffer buffer)))
5681 (let (start end newmark)
5682 (save-excursion
5683 (save-excursion
5684 (set-buffer buffer)
5685 (setq start (point-min) end (point-max)))
5686 @end group
5687 @group
5688 (insert-buffer-substring buffer start end)
5689 (setq newmark (point)))
5690 (push-mark newmark)))
5691 @end group
5692 @end smallexample
5693
5694 @need 1200
5695 As with other function definitions, you can use a template to see an
5696 outline of the function:
5697
5698 @smallexample
5699 @group
5700 (defun insert-buffer (buffer)
5701 "@var{documentation}@dots{}"
5702 (interactive "*bInsert buffer:@: ")
5703 @var{body}@dots{})
5704 @end group
5705 @end smallexample
5706
5707 @node insert-buffer interactive
5708 @subsection The Interactive Expression in @code{insert-buffer}
5709 @findex interactive, @r{example use of}
5710
5711 In @code{insert-buffer}, the argument to the @code{interactive}
5712 declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5713 buffer:@: }.
5714
5715 @menu
5716 * Read-only buffer:: When a buffer cannot be modified.
5717 * b for interactive:: An existing buffer or else its name.
5718 @end menu
5719
5720 @node Read-only buffer
5721 @unnumberedsubsubsec A Read-only Buffer
5722 @cindex Read-only buffer
5723 @cindex Asterisk for read-only buffer
5724 @findex * @r{for read-only buffer}
5725
5726 The asterisk is for the situation when the current buffer is a
5727 read-only buffer---a buffer that cannot be modified. If
5728 @code{insert-buffer} is called when the current buffer is read-only, a
5729 message to this effect is printed in the echo area and the terminal
5730 may beep or blink at you; you will not be permitted to insert anything
5731 into current buffer. The asterisk does not need to be followed by a
5732 newline to separate it from the next argument.
5733
5734 @node b for interactive
5735 @unnumberedsubsubsec @samp{b} in an Interactive Expression
5736
5737 The next argument in the interactive expression starts with a lower
5738 case @samp{b}. (This is different from the code for
5739 @code{append-to-buffer}, which uses an upper-case @samp{B}.
5740 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5741 The lower-case @samp{b} tells the Lisp interpreter that the argument
5742 for @code{insert-buffer} should be an existing buffer or else its
5743 name. (The upper-case @samp{B} option provides for the possibility
5744 that the buffer does not exist.) Emacs will prompt you for the name
5745 of the buffer, offering you a default buffer, with name completion
5746 enabled. If the buffer does not exist, you receive a message that
5747 says ``No match''; your terminal may beep at you as well.
5748
5749 The new and simplified code generates a list for @code{interactive}.
5750 It uses the @code{barf-if-buffer-read-only} and @code{read-buffer}
5751 functions with which we are already familiar and the @code{progn}
5752 special form with which we are not. (It will be described later.)
5753
5754 @node insert-buffer body
5755 @subsection The Body of the @code{insert-buffer} Function
5756
5757 The body of the @code{insert-buffer} function has two major parts: an
5758 @code{or} expression and a @code{let} expression. The purpose of the
5759 @code{or} expression is to ensure that the argument @code{buffer} is
5760 bound to a buffer and not just the name of a buffer. The body of the
5761 @code{let} expression contains the code which copies the other buffer
5762 into the current buffer.
5763
5764 @need 1250
5765 In outline, the two expressions fit into the @code{insert-buffer}
5766 function like this:
5767
5768 @smallexample
5769 @group
5770 (defun insert-buffer (buffer)
5771 "@var{documentation}@dots{}"
5772 (interactive "*bInsert buffer:@: ")
5773 (or @dots{}
5774 @dots{}
5775 @end group
5776 @group
5777 (let (@var{varlist})
5778 @var{body-of-}@code{let}@dots{} )
5779 @end group
5780 @end smallexample
5781
5782 To understand how the @code{or} expression ensures that the argument
5783 @code{buffer} is bound to a buffer and not to the name of a buffer, it
5784 is first necessary to understand the @code{or} function.
5785
5786 Before doing this, let me rewrite this part of the function using
5787 @code{if} so that you can see what is done in a manner that will be familiar.
5788
5789 @node if & or
5790 @subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5791
5792 The job to be done is to make sure the value of @code{buffer} is a
5793 buffer itself and not the name of a buffer. If the value is the name,
5794 then the buffer itself must be got.
5795
5796 You can imagine yourself at a conference where an usher is wandering
5797 around holding a list with your name on it and looking for you: the
5798 usher is ``bound'' to your name, not to you; but when the usher finds
5799 you and takes your arm, the usher becomes ``bound'' to you.
5800
5801 @need 800
5802 In Lisp, you might describe this situation like this:
5803
5804 @smallexample
5805 @group
5806 (if (not (holding-on-to-guest))
5807 (find-and-take-arm-of-guest))
5808 @end group
5809 @end smallexample
5810
5811 We want to do the same thing with a buffer---if we do not have the
5812 buffer itself, we want to get it.
5813
5814 @need 1200
5815 Using a predicate called @code{bufferp} that tells us whether we have a
5816 buffer (rather than its name), we can write the code like this:
5817
5818 @smallexample
5819 @group
5820 (if (not (bufferp buffer)) ; @r{if-part}
5821 (setq buffer (get-buffer buffer))) ; @r{then-part}
5822 @end group
5823 @end smallexample
5824
5825 @noindent
5826 Here, the true-or-false-test of the @code{if} expression is
5827 @w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5828 @w{@code{(setq buffer (get-buffer buffer))}}.
5829
5830 In the test, the function @code{bufferp} returns true if its argument is
5831 a buffer---but false if its argument is the name of the buffer. (The
5832 last character of the function name @code{bufferp} is the character
5833 @samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5834 indicates that the function is a predicate, which is a term that means
5835 that the function will determine whether some property is true or false.
5836 @xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5837 Argument}.)
5838
5839 @need 1200
5840 The function @code{not} precedes the expression @code{(bufferp buffer)},
5841 so the true-or-false-test looks like this:
5842
5843 @smallexample
5844 (not (bufferp buffer))
5845 @end smallexample
5846
5847 @noindent
5848 @code{not} is a function that returns true if its argument is false
5849 and false if its argument is true. So if @code{(bufferp buffer)}
5850 returns true, the @code{not} expression returns false and vice-verse:
5851 what is ``not true'' is false and what is ``not false'' is true.
5852
5853 Using this test, the @code{if} expression works as follows: when the
5854 value of the variable @code{buffer} is actually a buffer rather than
5855 its name, the true-or-false-test returns false and the @code{if}
5856 expression does not evaluate the then-part. This is fine, since we do
5857 not need to do anything to the variable @code{buffer} if it really is
5858 a buffer.
5859
5860 On the other hand, when the value of @code{buffer} is not a buffer
5861 itself, but the name of a buffer, the true-or-false-test returns true
5862 and the then-part of the expression is evaluated. In this case, the
5863 then-part is @code{(setq buffer (get-buffer buffer))}. This
5864 expression uses the @code{get-buffer} function to return an actual
5865 buffer itself, given its name. The @code{setq} then sets the variable
5866 @code{buffer} to the value of the buffer itself, replacing its previous
5867 value (which was the name of the buffer).
5868
5869 @node Insert or
5870 @subsection The @code{or} in the Body
5871
5872 The purpose of the @code{or} expression in the @code{insert-buffer}
5873 function is to ensure that the argument @code{buffer} is bound to a
5874 buffer and not just to the name of a buffer. The previous section shows
5875 how the job could have been done using an @code{if} expression.
5876 However, the @code{insert-buffer} function actually uses @code{or}.
5877 To understand this, it is necessary to understand how @code{or} works.
5878
5879 @findex or
5880 An @code{or} function can have any number of arguments. It evaluates
5881 each argument in turn and returns the value of the first of its
5882 arguments that is not @code{nil}. Also, and this is a crucial feature
5883 of @code{or}, it does not evaluate any subsequent arguments after
5884 returning the first non-@code{nil} value.
5885
5886 @need 800
5887 The @code{or} expression looks like this:
5888
5889 @smallexample
5890 @group
5891 (or (bufferp buffer)
5892 (setq buffer (get-buffer buffer)))
5893 @end group
5894 @end smallexample
5895
5896 @noindent
5897 The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5898 This expression returns true (a non-@code{nil} value) if the buffer is
5899 actually a buffer, and not just the name of a buffer. In the @code{or}
5900 expression, if this is the case, the @code{or} expression returns this
5901 true value and does not evaluate the next expression---and this is fine
5902 with us, since we do not want to do anything to the value of
5903 @code{buffer} if it really is a buffer.
5904
5905 On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5906 which it will be if the value of @code{buffer} is the name of a buffer,
5907 the Lisp interpreter evaluates the next element of the @code{or}
5908 expression. This is the expression @code{(setq buffer (get-buffer
5909 buffer))}. This expression returns a non-@code{nil} value, which
5910 is the value to which it sets the variable @code{buffer}---and this
5911 value is a buffer itself, not the name of a buffer.
5912
5913 The result of all this is that the symbol @code{buffer} is always
5914 bound to a buffer itself rather than to the name of a buffer. All
5915 this is necessary because the @code{set-buffer} function in a
5916 following line only works with a buffer itself, not with the name to a
5917 buffer.
5918
5919 @need 1250
5920 Incidentally, using @code{or}, the situation with the usher would be
5921 written like this:
5922
5923 @smallexample
5924 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
5925 @end smallexample
5926
5927 @node Insert let
5928 @subsection The @code{let} Expression in @code{insert-buffer}
5929
5930 After ensuring that the variable @code{buffer} refers to a buffer itself
5931 and not just to the name of a buffer, the @code{insert-buffer function}
5932 continues with a @code{let} expression. This specifies three local
5933 variables, @code{start}, @code{end}, and @code{newmark} and binds them
5934 to the initial value @code{nil}. These variables are used inside the
5935 remainder of the @code{let} and temporarily hide any other occurrence of
5936 variables of the same name in Emacs until the end of the @code{let}.
5937
5938 @need 1200
5939 The body of the @code{let} contains two @code{save-excursion}
5940 expressions. First, we will look at the inner @code{save-excursion}
5941 expression in detail. The expression looks like this:
5942
5943 @smallexample
5944 @group
5945 (save-excursion
5946 (set-buffer buffer)
5947 (setq start (point-min) end (point-max)))
5948 @end group
5949 @end smallexample
5950
5951 @noindent
5952 The expression @code{(set-buffer buffer)} changes Emacs's attention
5953 from the current buffer to the one from which the text will copied.
5954 In that buffer, the variables @code{start} and @code{end} are set to
5955 the beginning and end of the buffer, using the commands
5956 @code{point-min} and @code{point-max}. Note that we have here an
5957 illustration of how @code{setq} is able to set two variables in the
5958 same expression. The first argument of @code{setq} is set to the
5959 value of its second, and its third argument is set to the value of its
5960 fourth.
5961
5962 After the body of the inner @code{save-excursion} is evaluated, the
5963 @code{save-excursion} restores the original buffer, but @code{start} and
5964 @code{end} remain set to the values of the beginning and end of the
5965 buffer from which the text will be copied.
5966
5967 @need 1250
5968 The outer @code{save-excursion} expression looks like this:
5969
5970 @smallexample
5971 @group
5972 (save-excursion
5973 (@var{inner-}@code{save-excursion}@var{-expression}
5974 (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5975 (insert-buffer-substring buffer start end)
5976 (setq newmark (point)))
5977 @end group
5978 @end smallexample
5979
5980 @noindent
5981 The @code{insert-buffer-substring} function copies the text
5982 @emph{into} the current buffer @emph{from} the region indicated by
5983 @code{start} and @code{end} in @code{buffer}. Since the whole of the
5984 second buffer lies between @code{start} and @code{end}, the whole of
5985 the second buffer is copied into the buffer you are editing. Next,
5986 the value of point, which will be at the end of the inserted text, is
5987 recorded in the variable @code{newmark}.
5988
5989 After the body of the outer @code{save-excursion} is evaluated, point
5990 and mark are relocated to their original places.
5991
5992 However, it is convenient to locate a mark at the end of the newly
5993 inserted text and locate point at its beginning. The @code{newmark}
5994 variable records the end of the inserted text. In the last line of
5995 the @code{let} expression, the @code{(push-mark newmark)} expression
5996 function sets a mark to this location. (The previous location of the
5997 mark is still accessible; it is recorded on the mark ring and you can
5998 go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is
5999 located at the beginning of the inserted text, which is where it was
6000 before you called the insert function, the position of which was saved
6001 by the first @code{save-excursion}.
6002
6003 @need 1250
6004 The whole @code{let} expression looks like this:
6005
6006 @smallexample
6007 @group
6008 (let (start end newmark)
6009 (save-excursion
6010 (save-excursion
6011 (set-buffer buffer)
6012 (setq start (point-min) end (point-max)))
6013 (insert-buffer-substring buffer start end)
6014 (setq newmark (point)))
6015 (push-mark newmark))
6016 @end group
6017 @end smallexample
6018
6019 Like the @code{append-to-buffer} function, the @code{insert-buffer}
6020 function uses @code{let}, @code{save-excursion}, and
6021 @code{set-buffer}. In addition, the function illustrates one way to
6022 use @code{or}. All these functions are building blocks that we will
6023 find and use again and again.
6024
6025 @node New insert-buffer
6026 @subsection New Body for @code{insert-buffer}
6027 @findex insert-buffer, new version body
6028 @findex new version body for insert-buffer
6029
6030 The body in the GNU Emacs 22 version is more confusing than the original.
6031
6032 @need 1250
6033 It consists of two expressions,
6034
6035 @smallexample
6036 @group
6037 (push-mark
6038 (save-excursion
6039 (insert-buffer-substring (get-buffer buffer))
6040 (point)))
6041
6042 nil
6043 @end group
6044 @end smallexample
6045
6046 @noindent
6047 except, and this is what confuses novices, very important work is done
6048 inside the @code{push-mark} expression.
6049
6050 The @code{get-buffer} function returns a buffer with the name
6051 provided. You will note that the function is @emph{not} called
6052 @code{get-buffer-create}; it does not create a buffer if one does not
6053 already exist. The buffer returned by @code{get-buffer}, an existing
6054 buffer, is passed to @code{insert-buffer-substring}, which inserts the
6055 whole of the buffer (since you did not specify anything else).
6056
6057 The location into which the buffer is inserted is recorded by
6058 @code{push-mark}. Then the function returns @code{nil}, the value of
6059 its last command. Put another way, the @code{insert-buffer} function
6060 exists only to produce a side effect, inserting another buffer, not to
6061 return any value.
6062
6063 @node beginning-of-buffer
6064 @section Complete Definition of @code{beginning-of-buffer}
6065 @findex beginning-of-buffer
6066
6067 The basic structure of the @code{beginning-of-buffer} function has
6068 already been discussed. (@xref{simplified-beginning-of-buffer, , A
6069 Simplified @code{beginning-of-buffer} Definition}.)
6070 This section describes the complex part of the definition.
6071
6072 As previously described, when invoked without an argument,
6073 @code{beginning-of-buffer} moves the cursor to the beginning of the
6074 buffer (in truth, the beginning of the accessible portion of the
6075 buffer), leaving the mark at the previous position. However, when the
6076 command is invoked with a number between one and ten, the function
6077 considers that number to be a fraction of the length of the buffer,
6078 measured in tenths, and Emacs moves the cursor that fraction of the
6079 way from the beginning of the buffer. Thus, you can either call this
6080 function with the key command @kbd{M-<}, which will move the cursor to
6081 the beginning of the buffer, or with a key command such as @kbd{C-u 7
6082 M-<} which will move the cursor to a point 70% of the way through the
6083 buffer. If a number bigger than ten is used for the argument, it
6084 moves to the end of the buffer.
6085
6086 The @code{beginning-of-buffer} function can be called with or without an
6087 argument. The use of the argument is optional.
6088
6089 @menu
6090 * Optional Arguments::
6091 * beginning-of-buffer opt arg:: Example with optional argument.
6092 * beginning-of-buffer complete::
6093 @end menu
6094
6095 @node Optional Arguments
6096 @subsection Optional Arguments
6097
6098 Unless told otherwise, Lisp expects that a function with an argument in
6099 its function definition will be called with a value for that argument.
6100 If that does not happen, you get an error and a message that says
6101 @samp{Wrong number of arguments}.
6102
6103 @cindex Optional arguments
6104 @cindex Keyword
6105 @findex optional
6106 However, optional arguments are a feature of Lisp: a particular
6107 @dfn{keyword} is used to tell the Lisp interpreter that an argument is
6108 optional. The keyword is @code{&optional}. (The @samp{&} in front of
6109 @samp{optional} is part of the keyword.) In a function definition, if
6110 an argument follows the keyword @code{&optional}, no value need be
6111 passed to that argument when the function is called.
6112
6113 @need 1200
6114 The first line of the function definition of @code{beginning-of-buffer}
6115 therefore looks like this:
6116
6117 @smallexample
6118 (defun beginning-of-buffer (&optional arg)
6119 @end smallexample
6120
6121 @need 1250
6122 In outline, the whole function looks like this:
6123
6124 @smallexample
6125 @group
6126 (defun beginning-of-buffer (&optional arg)
6127 "@var{documentation}@dots{}"
6128 (interactive "P")
6129 (or (@var{is-the-argument-a-cons-cell} arg)
6130 (and @var{are-both-transient-mark-mode-and-mark-active-true})
6131 (push-mark))
6132 (let (@var{determine-size-and-set-it})
6133 (goto-char
6134 (@var{if-there-is-an-argument}
6135 @var{figure-out-where-to-go}
6136 @var{else-go-to}
6137 (point-min))))
6138 @var{do-nicety}
6139 @end group
6140 @end smallexample
6141
6142 The function is similar to the @code{simplified-beginning-of-buffer}
6143 function except that the @code{interactive} expression has @code{"P"}
6144 as an argument and the @code{goto-char} function is followed by an
6145 if-then-else expression that figures out where to put the cursor if
6146 there is an argument that is not a cons cell.
6147
6148 (Since I do not explain a cons cell for many more chapters, please
6149 consider ignoring the function @code{consp}. @xref{List
6150 Implementation, , How Lists are Implemented}, and @ref{Cons Cell Type,
6151 , Cons Cell and List Types, elisp, The GNU Emacs Lisp Reference
6152 Manual}.)
6153
6154 The @code{"P"} in the @code{interactive} expression tells Emacs to
6155 pass a prefix argument, if there is one, to the function in raw form.
6156 A prefix argument is made by typing the @key{META} key followed by a
6157 number, or by typing @kbd{C-u} and then a number. (If you don't type
6158 a number, @kbd{C-u} defaults to a cons cell with a 4. A lowercase
6159 @code{"p"} in the @code{interactive} expression causes the function to
6160 convert a prefix arg to a number.)
6161
6162 The true-or-false-test of the @code{if} expression looks complex, but
6163 it is not: it checks whether @code{arg} has a value that is not
6164 @code{nil} and whether it is a cons cell. (That is what @code{consp}
6165 does; it checks whether its argument is a cons cell.) If @code{arg}
6166 has a value that is not @code{nil} (and is not a cons cell), which
6167 will be the case if @code{beginning-of-buffer} is called with a
6168 numeric argument, then this true-or-false-test will return true and
6169 the then-part of the @code{if} expression will be evaluated. On the
6170 other hand, if @code{beginning-of-buffer} is not called with an
6171 argument, the value of @code{arg} will be @code{nil} and the else-part
6172 of the @code{if} expression will be evaluated. The else-part is
6173 simply @code{point-min}, and when this is the outcome, the whole
6174 @code{goto-char} expression is @code{(goto-char (point-min))}, which
6175 is how we saw the @code{beginning-of-buffer} function in its
6176 simplified form.
6177
6178 @node beginning-of-buffer opt arg
6179 @subsection @code{beginning-of-buffer} with an Argument
6180
6181 When @code{beginning-of-buffer} is called with an argument, an
6182 expression is evaluated which calculates what value to pass to
6183 @code{goto-char}. This expression is rather complicated at first sight.
6184 It includes an inner @code{if} expression and much arithmetic. It looks
6185 like this:
6186
6187 @smallexample
6188 @group
6189 (if (> (buffer-size) 10000)
6190 ;; @r{Avoid overflow for large buffer sizes!}
6191 (* (prefix-numeric-value arg)
6192 (/ size 10))
6193 (/
6194 (+ 10
6195 (*
6196 size (prefix-numeric-value arg))) 10)))
6197 @end group
6198 @end smallexample
6199
6200 @menu
6201 * Disentangle beginning-of-buffer::
6202 * Large buffer case::
6203 * Small buffer case::
6204 @end menu
6205
6206 @ifnottex
6207 @node Disentangle beginning-of-buffer
6208 @unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
6209 @end ifnottex
6210
6211 Like other complex-looking expressions, the conditional expression
6212 within @code{beginning-of-buffer} can be disentangled by looking at it
6213 as parts of a template, in this case, the template for an if-then-else
6214 expression. In skeletal form, the expression looks like this:
6215
6216 @smallexample
6217 @group
6218 (if (@var{buffer-is-large}
6219 @var{divide-buffer-size-by-10-and-multiply-by-arg}
6220 @var{else-use-alternate-calculation}
6221 @end group
6222 @end smallexample
6223
6224 The true-or-false-test of this inner @code{if} expression checks the
6225 size of the buffer. The reason for this is that the old version 18
6226 Emacs used numbers that are no bigger than eight million or so and in
6227 the computation that followed, the programmer feared that Emacs might
6228 try to use over-large numbers if the buffer were large. The term
6229 `overflow', mentioned in the comment, means numbers that are over
6230 large. More recent versions of Emacs use larger numbers, but this
6231 code has not been touched, if only because people now look at buffers
6232 that are far, far larger than ever before.
6233
6234 There are two cases: if the buffer is large and if it is not.
6235
6236 @node Large buffer case
6237 @unnumberedsubsubsec What happens in a large buffer
6238
6239 In @code{beginning-of-buffer}, the inner @code{if} expression tests
6240 whether the size of the buffer is greater than 10,000 characters. To do
6241 this, it uses the @code{>} function and the computation of @code{size}
6242 that comes from the let expression.
6243
6244 In the old days, the function @code{buffer-size} was used. Not only
6245 was that function called several times, it gave the size of the whole
6246 buffer, not the accessible part. The computation makes much more
6247 sense when it handles just the accessible part. (@xref{Narrowing &
6248 Widening, , Narrowing and Widening}, for more information on focusing
6249 attention to an `accessible' part.)
6250
6251 @need 800
6252 The line looks like this:
6253
6254 @smallexample
6255 (if (> size 10000)
6256 @end smallexample
6257
6258 @need 1200
6259 @noindent
6260 When the buffer is large, the then-part of the @code{if} expression is
6261 evaluated. It reads like this (after formatting for easy reading):
6262
6263 @smallexample
6264 @group
6265 (*
6266 (prefix-numeric-value arg)
6267 (/ size 10))
6268 @end group
6269 @end smallexample
6270
6271 @noindent
6272 This expression is a multiplication, with two arguments to the function
6273 @code{*}.
6274
6275 The first argument is @code{(prefix-numeric-value arg)}. When
6276 @code{"P"} is used as the argument for @code{interactive}, the value
6277 passed to the function as its argument is passed a ``raw prefix
6278 argument'', and not a number. (It is a number in a list.) To perform
6279 the arithmetic, a conversion is necessary, and
6280 @code{prefix-numeric-value} does the job.
6281
6282 @findex / @r{(division)}
6283 @cindex Division
6284 The second argument is @code{(/ size 10)}. This expression divides
6285 the numeric value by ten---the numeric value of the size of the
6286 accessible portion of the buffer. This produces a number that tells
6287 how many characters make up one tenth of the buffer size. (In Lisp,
6288 @code{/} is used for division, just as @code{*} is used for
6289 multiplication.)
6290
6291 @need 1200
6292 In the multiplication expression as a whole, this amount is multiplied
6293 by the value of the prefix argument---the multiplication looks like this:
6294
6295 @smallexample
6296 @group
6297 (* @var{numeric-value-of-prefix-arg}
6298 @var{number-of-characters-in-one-tenth-of-the-accessible-buffer})
6299 @end group
6300 @end smallexample
6301
6302 @noindent
6303 If, for example, the prefix argument is @samp{7}, the one-tenth value
6304 will be multiplied by 7 to give a position 70% of the way through.
6305
6306 @need 1200
6307 The result of all this is that if the accessible portion of the buffer
6308 is large, the @code{goto-char} expression reads like this:
6309
6310 @smallexample
6311 @group
6312 (goto-char (* (prefix-numeric-value arg)
6313 (/ size 10)))
6314 @end group
6315 @end smallexample
6316
6317 This puts the cursor where we want it.
6318
6319 @node Small buffer case
6320 @unnumberedsubsubsec What happens in a small buffer
6321
6322 If the buffer contains fewer than 10,000 characters, a slightly
6323 different computation is performed. You might think this is not
6324 necessary, since the first computation could do the job. However, in
6325 a small buffer, the first method may not put the cursor on exactly the
6326 desired line; the second method does a better job.
6327
6328 @need 800
6329 The code looks like this:
6330
6331 @c Keep this on one line.
6332 @smallexample
6333 (/ (+ 10 (* size (prefix-numeric-value arg))) 10))
6334 @end smallexample
6335
6336 @need 1200
6337 @noindent
6338 This is code in which you figure out what happens by discovering how the
6339 functions are embedded in parentheses. It is easier to read if you
6340 reformat it with each expression indented more deeply than its
6341 enclosing expression:
6342
6343 @smallexample
6344 @group
6345 (/
6346 (+ 10
6347 (*
6348 size
6349 (prefix-numeric-value arg)))
6350 10))
6351 @end group
6352 @end smallexample
6353
6354 @need 1200
6355 @noindent
6356 Looking at parentheses, we see that the innermost operation is
6357 @code{(prefix-numeric-value arg)}, which converts the raw argument to
6358 a number. In the following expression, this number is multiplied by
6359 the size of the accessible portion of the buffer:
6360
6361 @smallexample
6362 (* size (prefix-numeric-value arg))
6363 @end smallexample
6364
6365 @noindent
6366 This multiplication creates a number that may be larger than the size of
6367 the buffer---seven times larger if the argument is 7, for example. Ten
6368 is then added to this number and finally the large number is divided by
6369 ten to provide a value that is one character larger than the percentage
6370 position in the buffer.
6371
6372 The number that results from all this is passed to @code{goto-char} and
6373 the cursor is moved to that point.
6374
6375 @need 1500
6376 @node beginning-of-buffer complete
6377 @subsection The Complete @code{beginning-of-buffer}
6378
6379 @need 1000
6380 Here is the complete text of the @code{beginning-of-buffer} function:
6381 @sp 1
6382
6383 @c In GNU Emacs 22
6384 @smallexample
6385 @group
6386 (defun beginning-of-buffer (&optional arg)
6387 "Move point to the beginning of the buffer;
6388 leave mark at previous position.
6389 With \\[universal-argument] prefix,
6390 do not set mark at previous position.
6391 With numeric arg N,
6392 put point N/10 of the way from the beginning.
6393
6394 If the buffer is narrowed,
6395 this command uses the beginning and size
6396 of the accessible part of the buffer.
6397 @end group
6398
6399 @group
6400 Don't use this command in Lisp programs!
6401 \(goto-char (point-min)) is faster
6402 and avoids clobbering the mark."
6403 (interactive "P")
6404 (or (consp arg)
6405 (and transient-mark-mode mark-active)
6406 (push-mark))
6407 @end group
6408 @group
6409 (let ((size (- (point-max) (point-min))))
6410 (goto-char (if (and arg (not (consp arg)))
6411 (+ (point-min)
6412 (if (> size 10000)
6413 ;; Avoid overflow for large buffer sizes!
6414 (* (prefix-numeric-value arg)
6415 (/ size 10))
6416 (/ (+ 10 (* size (prefix-numeric-value arg)))
6417 10)))
6418 (point-min))))
6419 (if arg (forward-line 1)))
6420 @end group
6421 @end smallexample
6422
6423 @ignore
6424 From before GNU Emacs 22
6425 @smallexample
6426 @group
6427 (defun beginning-of-buffer (&optional arg)
6428 "Move point to the beginning of the buffer;
6429 leave mark at previous position.
6430 With arg N, put point N/10 of the way
6431 from the true beginning.
6432 @end group
6433 @group
6434 Don't use this in Lisp programs!
6435 \(goto-char (point-min)) is faster
6436 and does not set the mark."
6437 (interactive "P")
6438 (push-mark)
6439 @end group
6440 @group
6441 (goto-char
6442 (if arg
6443 (if (> (buffer-size) 10000)
6444 ;; @r{Avoid overflow for large buffer sizes!}
6445 (* (prefix-numeric-value arg)
6446 (/ (buffer-size) 10))
6447 @end group
6448 @group
6449 (/ (+ 10 (* (buffer-size)
6450 (prefix-numeric-value arg)))
6451 10))
6452 (point-min)))
6453 (if arg (forward-line 1)))
6454 @end group
6455 @end smallexample
6456 @end ignore
6457
6458 @noindent
6459 Except for two small points, the previous discussion shows how this
6460 function works. The first point deals with a detail in the
6461 documentation string, and the second point concerns the last line of
6462 the function.
6463
6464 @need 800
6465 In the documentation string, there is reference to an expression:
6466
6467 @smallexample
6468 \\[universal-argument]
6469 @end smallexample
6470
6471 @noindent
6472 A @samp{\\} is used before the first square bracket of this
6473 expression. This @samp{\\} tells the Lisp interpreter to substitute
6474 whatever key is currently bound to the @samp{[@dots{}]}. In the case
6475 of @code{universal-argument}, that is usually @kbd{C-u}, but it might
6476 be different. (@xref{Documentation Tips, , Tips for Documentation
6477 Strings, elisp, The GNU Emacs Lisp Reference Manual}, for more
6478 information.)
6479
6480 @need 1200
6481 Finally, the last line of the @code{beginning-of-buffer} command says
6482 to move point to the beginning of the next line if the command is
6483 invoked with an argument:
6484
6485 @smallexample
6486 (if arg (forward-line 1)))
6487 @end smallexample
6488
6489 @noindent
6490 This puts the cursor at the beginning of the first line after the
6491 appropriate tenths position in the buffer. This is a flourish that
6492 means that the cursor is always located @emph{at least} the requested
6493 tenths of the way through the buffer, which is a nicety that is,
6494 perhaps, not necessary, but which, if it did not occur, would be sure
6495 to draw complaints.
6496
6497 On the other hand, it also means that if you specify the command with
6498 a @kbd{C-u}, but without a number, that is to say, if the `raw prefix
6499 argument' is simply a cons cell, then the command puts you at the
6500 beginning of the second line @dots{} I don't know whether this is
6501 intended or whether no one has dealt with the code to avoid this
6502 happening.
6503
6504 @node Second Buffer Related Review
6505 @section Review
6506
6507 Here is a brief summary of some of the topics covered in this chapter.
6508
6509 @table @code
6510 @item or
6511 Evaluate each argument in sequence, and return the value of the first
6512 argument that is not @code{nil}; if none return a value that is not
6513 @code{nil}, return @code{nil}. In brief, return the first true value
6514 of the arguments; return a true value if one @emph{or} any of the
6515 others are true.
6516
6517 @item and
6518 Evaluate each argument in sequence, and if any are @code{nil}, return
6519 @code{nil}; if none are @code{nil}, return the value of the last
6520 argument. In brief, return a true value only if all the arguments are
6521 true; return a true value if one @emph{and} each of the others is
6522 true.
6523
6524 @item &optional
6525 A keyword used to indicate that an argument to a function definition
6526 is optional; this means that the function can be evaluated without the
6527 argument, if desired.
6528
6529 @item prefix-numeric-value
6530 Convert the `raw prefix argument' produced by @code{(interactive
6531 "P")} to a numeric value.
6532
6533 @item forward-line
6534 Move point forward to the beginning of the next line, or if the argument
6535 is greater than one, forward that many lines. If it can't move as far
6536 forward as it is supposed to, @code{forward-line} goes forward as far as
6537 it can and then returns a count of the number of additional lines it was
6538 supposed to move but couldn't.
6539
6540 @item erase-buffer
6541 Delete the entire contents of the current buffer.
6542
6543 @item bufferp
6544 Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6545 @end table
6546
6547 @node optional Exercise
6548 @section @code{optional} Argument Exercise
6549
6550 Write an interactive function with an optional argument that tests
6551 whether its argument, a number, is greater than or equal to, or else,
6552 less than the value of @code{fill-column}, and tells you which, in a
6553 message. However, if you do not pass an argument to the function, use
6554 56 as a default value.
6555
6556 @node Narrowing & Widening
6557 @chapter Narrowing and Widening
6558 @cindex Focusing attention (narrowing)
6559 @cindex Narrowing
6560 @cindex Widening
6561
6562 Narrowing is a feature of Emacs that makes it possible for you to focus
6563 on a specific part of a buffer, and work without accidentally changing
6564 other parts. Narrowing is normally disabled since it can confuse
6565 novices.
6566
6567 @menu
6568 * Narrowing advantages:: The advantages of narrowing
6569 * save-restriction:: The @code{save-restriction} special form.
6570 * what-line:: The number of the line that point is on.
6571 * narrow Exercise::
6572 @end menu
6573
6574 @ifnottex
6575 @node Narrowing advantages
6576 @unnumberedsec The Advantages of Narrowing
6577 @end ifnottex
6578
6579 With narrowing, the rest of a buffer is made invisible, as if it weren't
6580 there. This is an advantage if, for example, you want to replace a word
6581 in one part of a buffer but not in another: you narrow to the part you want
6582 and the replacement is carried out only in that section, not in the rest
6583 of the buffer. Searches will only work within a narrowed region, not
6584 outside of one, so if you are fixing a part of a document, you can keep
6585 yourself from accidentally finding parts you do not need to fix by
6586 narrowing just to the region you want.
6587 (The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6588
6589 However, narrowing does make the rest of the buffer invisible, which
6590 can scare people who inadvertently invoke narrowing and think they
6591 have deleted a part of their file. Moreover, the @code{undo} command
6592 (which is usually bound to @kbd{C-x u}) does not turn off narrowing
6593 (nor should it), so people can become quite desperate if they do not
6594 know that they can return the rest of a buffer to visibility with the
6595 @code{widen} command.
6596 (The key binding for @code{widen} is @kbd{C-x n w}.)
6597
6598 Narrowing is just as useful to the Lisp interpreter as to a human.
6599 Often, an Emacs Lisp function is designed to work on just part of a
6600 buffer; or conversely, an Emacs Lisp function needs to work on all of a
6601 buffer that has been narrowed. The @code{what-line} function, for
6602 example, removes the narrowing from a buffer, if it has any narrowing
6603 and when it has finished its job, restores the narrowing to what it was.
6604 On the other hand, the @code{count-lines} function
6605 uses narrowing to restrict itself to just that portion
6606 of the buffer in which it is interested and then restores the previous
6607 situation.
6608
6609 @node save-restriction
6610 @section The @code{save-restriction} Special Form
6611 @findex save-restriction
6612
6613 In Emacs Lisp, you can use the @code{save-restriction} special form to
6614 keep track of whatever narrowing is in effect, if any. When the Lisp
6615 interpreter meets with @code{save-restriction}, it executes the code
6616 in the body of the @code{save-restriction} expression, and then undoes
6617 any changes to narrowing that the code caused. If, for example, the
6618 buffer is narrowed and the code that follows @code{save-restriction}
6619 gets rid of the narrowing, @code{save-restriction} returns the buffer
6620 to its narrowed region afterwards. In the @code{what-line} command,
6621 any narrowing the buffer may have is undone by the @code{widen}
6622 command that immediately follows the @code{save-restriction} command.
6623 Any original narrowing is restored just before the completion of the
6624 function.
6625
6626 @need 1250
6627 The template for a @code{save-restriction} expression is simple:
6628
6629 @smallexample
6630 @group
6631 (save-restriction
6632 @var{body}@dots{} )
6633 @end group
6634 @end smallexample
6635
6636 @noindent
6637 The body of the @code{save-restriction} is one or more expressions that
6638 will be evaluated in sequence by the Lisp interpreter.
6639
6640 Finally, a point to note: when you use both @code{save-excursion} and
6641 @code{save-restriction}, one right after the other, you should use
6642 @code{save-excursion} outermost. If you write them in reverse order,
6643 you may fail to record narrowing in the buffer to which Emacs switches
6644 after calling @code{save-excursion}. Thus, when written together,
6645 @code{save-excursion} and @code{save-restriction} should be written
6646 like this:
6647
6648 @smallexample
6649 @group
6650 (save-excursion
6651 (save-restriction
6652 @var{body}@dots{}))
6653 @end group
6654 @end smallexample
6655
6656 In other circumstances, when not written together, the
6657 @code{save-excursion} and @code{save-restriction} special forms must
6658 be written in the order appropriate to the function.
6659
6660 @need 1250
6661 For example,
6662
6663 @smallexample
6664 @group
6665 (save-restriction
6666 (widen)
6667 (save-excursion
6668 @var{body}@dots{}))
6669 @end group
6670 @end smallexample
6671
6672 @ignore
6673 Emacs 22
6674 /usr/local/src/emacs/lisp/simple.el
6675
6676 (defun what-line ()
6677 "Print the current buffer line number and narrowed line number of point."
6678 (interactive)
6679 (let ((start (point-min))
6680 (n (line-number-at-pos)))
6681 (if (= start 1)
6682 (message "Line %d" n)
6683 (save-excursion
6684 (save-restriction
6685 (widen)
6686 (message "line %d (narrowed line %d)"
6687 (+ n (line-number-at-pos start) -1) n))))))
6688
6689 (defun line-number-at-pos (&optional pos)
6690 "Return (narrowed) buffer line number at position POS.
6691 If POS is nil, use current buffer location.
6692 Counting starts at (point-min), so the value refers
6693 to the contents of the accessible portion of the buffer."
6694 (let ((opoint (or pos (point))) start)
6695 (save-excursion
6696 (goto-char (point-min))
6697 (setq start (point))
6698 (goto-char opoint)
6699 (forward-line 0)
6700 (1+ (count-lines start (point))))))
6701
6702 (defun count-lines (start end)
6703 "Return number of lines between START and END.
6704 This is usually the number of newlines between them,
6705 but can be one more if START is not equal to END
6706 and the greater of them is not at the start of a line."
6707 (save-excursion
6708 (save-restriction
6709 (narrow-to-region start end)
6710 (goto-char (point-min))
6711 (if (eq selective-display t)
6712 (save-match-data
6713 (let ((done 0))
6714 (while (re-search-forward "[\n\C-m]" nil t 40)
6715 (setq done (+ 40 done)))
6716 (while (re-search-forward "[\n\C-m]" nil t 1)
6717 (setq done (+ 1 done)))
6718 (goto-char (point-max))
6719 (if (and (/= start end)
6720 (not (bolp)))
6721 (1+ done)
6722 done)))
6723 (- (buffer-size) (forward-line (buffer-size)))))))
6724 @end ignore
6725
6726 @node what-line
6727 @section @code{what-line}
6728 @findex what-line
6729 @cindex Widening, example of
6730
6731 The @code{what-line} command tells you the number of the line in which
6732 the cursor is located. The function illustrates the use of the
6733 @code{save-restriction} and @code{save-excursion} commands. Here is the
6734 original text of the function:
6735
6736 @smallexample
6737 @group
6738 (defun what-line ()
6739 "Print the current line number (in the buffer) of point."
6740 (interactive)
6741 (save-restriction
6742 (widen)
6743 (save-excursion
6744 (beginning-of-line)
6745 (message "Line %d"
6746 (1+ (count-lines 1 (point)))))))
6747 @end group
6748 @end smallexample
6749
6750 (In recent versions of GNU Emacs, the @code{what-line} function has
6751 been expanded to tell you your line number in a narrowed buffer as
6752 well as your line number in a widened buffer. The recent version is
6753 more complex than the version shown here. If you feel adventurous,
6754 you might want to look at it after figuring out how this version
6755 works. You will probably need to use @kbd{C-h f}
6756 (@code{describe-function}). The newer version uses a conditional to
6757 determine whether the buffer has been narrowed.
6758
6759 (Also, it uses @code{line-number-at-pos}, which among other simple
6760 expressions, such as @code{(goto-char (point-min))}, moves point to
6761 the beginning of the current line with @code{(forward-line 0)} rather
6762 than @code{beginning-of-line}.)
6763
6764 The @code{what-line} function as shown here has a documentation line
6765 and is interactive, as you would expect. The next two lines use the
6766 functions @code{save-restriction} and @code{widen}.
6767
6768 The @code{save-restriction} special form notes whatever narrowing is in
6769 effect, if any, in the current buffer and restores that narrowing after
6770 the code in the body of the @code{save-restriction} has been evaluated.
6771
6772 The @code{save-restriction} special form is followed by @code{widen}.
6773 This function undoes any narrowing the current buffer may have had
6774 when @code{what-line} was called. (The narrowing that was there is
6775 the narrowing that @code{save-restriction} remembers.) This widening
6776 makes it possible for the line counting commands to count from the
6777 beginning of the buffer. Otherwise, they would have been limited to
6778 counting within the accessible region. Any original narrowing is
6779 restored just before the completion of the function by the
6780 @code{save-restriction} special form.
6781
6782 The call to @code{widen} is followed by @code{save-excursion}, which
6783 saves the location of the cursor (i.e., of point) and of the mark, and
6784 restores them after the code in the body of the @code{save-excursion}
6785 uses the @code{beginning-of-line} function to move point.
6786
6787 (Note that the @code{(widen)} expression comes between the
6788 @code{save-restriction} and @code{save-excursion} special forms. When
6789 you write the two @code{save- @dots{}} expressions in sequence, write
6790 @code{save-excursion} outermost.)
6791
6792 @need 1200
6793 The last two lines of the @code{what-line} function are functions to
6794 count the number of lines in the buffer and then print the number in the
6795 echo area.
6796
6797 @smallexample
6798 @group
6799 (message "Line %d"
6800 (1+ (count-lines 1 (point)))))))
6801 @end group
6802 @end smallexample
6803
6804 The @code{message} function prints a one-line message at the bottom of
6805 the Emacs screen. The first argument is inside of quotation marks and
6806 is printed as a string of characters. However, it may contain a
6807 @samp{%d} expression to print a following argument. @samp{%d} prints
6808 the argument as a decimal, so the message will say something such as
6809 @samp{Line 243}.
6810
6811 @need 1200
6812 The number that is printed in place of the @samp{%d} is computed by the
6813 last line of the function:
6814
6815 @smallexample
6816 (1+ (count-lines 1 (point)))
6817 @end smallexample
6818
6819 @ignore
6820 GNU Emacs 22
6821
6822 (defun count-lines (start end)
6823 "Return number of lines between START and END.
6824 This is usually the number of newlines between them,
6825 but can be one more if START is not equal to END
6826 and the greater of them is not at the start of a line."
6827 (save-excursion
6828 (save-restriction
6829 (narrow-to-region start end)
6830 (goto-char (point-min))
6831 (if (eq selective-display t)
6832 (save-match-data
6833 (let ((done 0))
6834 (while (re-search-forward "[\n\C-m]" nil t 40)
6835 (setq done (+ 40 done)))
6836 (while (re-search-forward "[\n\C-m]" nil t 1)
6837 (setq done (+ 1 done)))
6838 (goto-char (point-max))
6839 (if (and (/= start end)
6840 (not (bolp)))
6841 (1+ done)
6842 done)))
6843 (- (buffer-size) (forward-line (buffer-size)))))))
6844 @end ignore
6845
6846 @noindent
6847 What this does is count the lines from the first position of the
6848 buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6849 one to that number. (The @code{1+} function adds one to its
6850 argument.) We add one to it because line 2 has only one line before
6851 it, and @code{count-lines} counts only the lines @emph{before} the
6852 current line.
6853
6854 After @code{count-lines} has done its job, and the message has been
6855 printed in the echo area, the @code{save-excursion} restores point and
6856 mark to their original positions; and @code{save-restriction} restores
6857 the original narrowing, if any.
6858
6859 @node narrow Exercise
6860 @section Exercise with Narrowing
6861
6862 Write a function that will display the first 60 characters of the
6863 current buffer, even if you have narrowed the buffer to its latter
6864 half so that the first line is inaccessible. Restore point, mark, and
6865 narrowing. For this exercise, you need to use a whole potpourri of
6866 functions, including @code{save-restriction}, @code{widen},
6867 @code{goto-char}, @code{point-min}, @code{message}, and
6868 @code{buffer-substring}.
6869
6870 @cindex Properties, mention of @code{buffer-substring-no-properties}
6871 (@code{buffer-substring} is a previously unmentioned function you will
6872 have to investigate yourself; or perhaps you will have to use
6873 @code{buffer-substring-no-properties} or
6874 @code{filter-buffer-substring} @dots{}, yet other functions. Text
6875 properties are a feature otherwise not discussed here. @xref{Text
6876 Properties, , Text Properties, elisp, The GNU Emacs Lisp Reference
6877 Manual}.)
6878
6879 Additionally, do you really need @code{goto-char} or @code{point-min}?
6880 Or can you write the function without them?
6881
6882 @node car cdr & cons
6883 @chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6884 @findex car, @r{introduced}
6885 @findex cdr, @r{introduced}
6886
6887 In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6888 functions. The @code{cons} function is used to construct lists, and
6889 the @code{car} and @code{cdr} functions are used to take them apart.
6890
6891 In the walk through of the @code{copy-region-as-kill} function, we
6892 will see @code{cons} as well as two variants on @code{cdr},
6893 namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.)
6894
6895 @menu
6896 * Strange Names:: An historical aside: why the strange names?
6897 * car & cdr:: Functions for extracting part of a list.
6898 * cons:: Constructing a list.
6899 * nthcdr:: Calling @code{cdr} repeatedly.
6900 * nth::
6901 * setcar:: Changing the first element of a list.
6902 * setcdr:: Changing the rest of a list.
6903 * cons Exercise::
6904 @end menu
6905
6906 @ifnottex
6907 @node Strange Names
6908 @unnumberedsec Strange Names
6909 @end ifnottex
6910
6911 The name of the @code{cons} function is not unreasonable: it is an
6912 abbreviation of the word `construct'. The origins of the names for
6913 @code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6914 is an acronym from the phrase `Contents of the Address part of the
6915 Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6916 the phrase `Contents of the Decrement part of the Register'. These
6917 phrases refer to specific pieces of hardware on the very early
6918 computer on which the original Lisp was developed. Besides being
6919 obsolete, the phrases have been completely irrelevant for more than 25
6920 years to anyone thinking about Lisp. Nonetheless, although a few
6921 brave scholars have begun to use more reasonable names for these
6922 functions, the old terms are still in use. In particular, since the
6923 terms are used in the Emacs Lisp source code, we will use them in this
6924 introduction.
6925
6926 @node car & cdr
6927 @section @code{car} and @code{cdr}
6928
6929 The @sc{car} of a list is, quite simply, the first item in the list.
6930 Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6931 @code{rose}.
6932
6933 @need 1200
6934 If you are reading this in Info in GNU Emacs, you can see this by
6935 evaluating the following:
6936
6937 @smallexample
6938 (car '(rose violet daisy buttercup))
6939 @end smallexample
6940
6941 @noindent
6942 After evaluating the expression, @code{rose} will appear in the echo
6943 area.
6944
6945 Clearly, a more reasonable name for the @code{car} function would be
6946 @code{first} and this is often suggested.
6947
6948 @code{car} does not remove the first item from the list; it only reports
6949 what it is. After @code{car} has been applied to a list, the list is
6950 still the same as it was. In the jargon, @code{car} is
6951 `non-destructive'. This feature turns out to be important.
6952
6953 The @sc{cdr} of a list is the rest of the list, that is, the
6954 @code{cdr} function returns the part of the list that follows the
6955 first item. Thus, while the @sc{car} of the list @code{'(rose violet
6956 daisy buttercup)} is @code{rose}, the rest of the list, the value
6957 returned by the @code{cdr} function, is @code{(violet daisy
6958 buttercup)}.
6959
6960 @need 800
6961 You can see this by evaluating the following in the usual way:
6962
6963 @smallexample
6964 (cdr '(rose violet daisy buttercup))
6965 @end smallexample
6966
6967 @noindent
6968 When you evaluate this, @code{(violet daisy buttercup)} will appear in
6969 the echo area.
6970
6971 Like @code{car}, @code{cdr} does not remove any elements from the
6972 list---it just returns a report of what the second and subsequent
6973 elements are.
6974
6975 Incidentally, in the example, the list of flowers is quoted. If it were
6976 not, the Lisp interpreter would try to evaluate the list by calling
6977 @code{rose} as a function. In this example, we do not want to do that.
6978
6979 Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6980
6981 (There is a lesson here: when you name new functions, consider very
6982 carefully what you are doing, since you may be stuck with the names
6983 for far longer than you expect. The reason this document perpetuates
6984 these names is that the Emacs Lisp source code uses them, and if I did
6985 not use them, you would have a hard time reading the code; but do,
6986 please, try to avoid using these terms yourself. The people who come
6987 after you will be grateful to you.)
6988
6989 When @code{car} and @code{cdr} are applied to a list made up of symbols,
6990 such as the list @code{(pine fir oak maple)}, the element of the list
6991 returned by the function @code{car} is the symbol @code{pine} without
6992 any parentheses around it. @code{pine} is the first element in the
6993 list. However, the @sc{cdr} of the list is a list itself, @code{(fir
6994 oak maple)}, as you can see by evaluating the following expressions in
6995 the usual way:
6996
6997 @smallexample
6998 @group
6999 (car '(pine fir oak maple))
7000
7001 (cdr '(pine fir oak maple))
7002 @end group
7003 @end smallexample
7004
7005 On the other hand, in a list of lists, the first element is itself a
7006 list. @code{car} returns this first element as a list. For example,
7007 the following list contains three sub-lists, a list of carnivores, a
7008 list of herbivores and a list of sea mammals:
7009
7010 @smallexample
7011 @group
7012 (car '((lion tiger cheetah)
7013 (gazelle antelope zebra)
7014 (whale dolphin seal)))
7015 @end group
7016 @end smallexample
7017
7018 @noindent
7019 In this example, the first element or @sc{car} of the list is the list of
7020 carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
7021 @code{((gazelle antelope zebra) (whale dolphin seal))}.
7022
7023 @smallexample
7024 @group
7025 (cdr '((lion tiger cheetah)
7026 (gazelle antelope zebra)
7027 (whale dolphin seal)))
7028 @end group
7029 @end smallexample
7030
7031 It is worth saying again that @code{car} and @code{cdr} are
7032 non-destructive---that is, they do not modify or change lists to which
7033 they are applied. This is very important for how they are used.
7034
7035 Also, in the first chapter, in the discussion about atoms, I said that
7036 in Lisp, ``certain kinds of atom, such as an array, can be separated
7037 into parts; but the mechanism for doing this is different from the
7038 mechanism for splitting a list. As far as Lisp is concerned, the
7039 atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The
7040 @code{car} and @code{cdr} functions are used for splitting lists and
7041 are considered fundamental to Lisp. Since they cannot split or gain
7042 access to the parts of an array, an array is considered an atom.
7043 Conversely, the other fundamental function, @code{cons}, can put
7044 together or construct a list, but not an array. (Arrays are handled
7045 by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU
7046 Emacs Lisp Reference Manual}.)
7047
7048 @node cons
7049 @section @code{cons}
7050 @findex cons, @r{introduced}
7051
7052 The @code{cons} function constructs lists; it is the inverse of
7053 @code{car} and @code{cdr}. For example, @code{cons} can be used to make
7054 a four element list from the three element list, @code{(fir oak maple)}:
7055
7056 @smallexample
7057 (cons 'pine '(fir oak maple))
7058 @end smallexample
7059
7060 @need 800
7061 @noindent
7062 After evaluating this list, you will see
7063
7064 @smallexample
7065 (pine fir oak maple)
7066 @end smallexample
7067
7068 @noindent
7069 appear in the echo area. @code{cons} causes the creation of a new
7070 list in which the element is followed by the elements of the original
7071 list.
7072
7073 We often say that `@code{cons} puts a new element at the beginning of
7074 a list; it attaches or pushes elements onto the list', but this
7075 phrasing can be misleading, since @code{cons} does not change an
7076 existing list, but creates a new one.
7077
7078 Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
7079
7080 @menu
7081 * Build a list::
7082 * length:: How to find the length of a list.
7083 @end menu
7084
7085 @ifnottex
7086 @node Build a list
7087 @unnumberedsubsec Build a list
7088 @end ifnottex
7089
7090 @code{cons} must have a list to attach to.@footnote{Actually, you can
7091 @code{cons} an element to an atom to produce a dotted pair. Dotted
7092 pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
7093 Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You
7094 cannot start from absolutely nothing. If you are building a list, you
7095 need to provide at least an empty list at the beginning. Here is a
7096 series of @code{cons} expressions that build up a list of flowers. If
7097 you are reading this in Info in GNU Emacs, you can evaluate each of
7098 the expressions in the usual way; the value is printed in this text
7099 after @samp{@result{}}, which you may read as `evaluates to'.
7100
7101 @smallexample
7102 @group
7103 (cons 'buttercup ())
7104 @result{} (buttercup)
7105 @end group
7106
7107 @group
7108 (cons 'daisy '(buttercup))
7109 @result{} (daisy buttercup)
7110 @end group
7111
7112 @group
7113 (cons 'violet '(daisy buttercup))
7114 @result{} (violet daisy buttercup)
7115 @end group
7116
7117 @group
7118 (cons 'rose '(violet daisy buttercup))
7119 @result{} (rose violet daisy buttercup)
7120 @end group
7121 @end smallexample
7122
7123 @noindent
7124 In the first example, the empty list is shown as @code{()} and a list
7125 made up of @code{buttercup} followed by the empty list is constructed.
7126 As you can see, the empty list is not shown in the list that was
7127 constructed. All that you see is @code{(buttercup)}. The empty list is
7128 not counted as an element of a list because there is nothing in an empty
7129 list. Generally speaking, an empty list is invisible.
7130
7131 The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
7132 two element list by putting @code{daisy} in front of @code{buttercup};
7133 and the third example constructs a three element list by putting
7134 @code{violet} in front of @code{daisy} and @code{buttercup}.
7135
7136 @node length
7137 @subsection Find the Length of a List: @code{length}
7138 @findex length
7139
7140 You can find out how many elements there are in a list by using the Lisp
7141 function @code{length}, as in the following examples:
7142
7143 @smallexample
7144 @group
7145 (length '(buttercup))
7146 @result{} 1
7147 @end group
7148
7149 @group
7150 (length '(daisy buttercup))
7151 @result{} 2
7152 @end group
7153
7154 @group
7155 (length (cons 'violet '(daisy buttercup)))
7156 @result{} 3
7157 @end group
7158 @end smallexample
7159
7160 @noindent
7161 In the third example, the @code{cons} function is used to construct a
7162 three element list which is then passed to the @code{length} function as
7163 its argument.
7164
7165 @need 1200
7166 We can also use @code{length} to count the number of elements in an
7167 empty list:
7168
7169 @smallexample
7170 @group
7171 (length ())
7172 @result{} 0
7173 @end group
7174 @end smallexample
7175
7176 @noindent
7177 As you would expect, the number of elements in an empty list is zero.
7178
7179 An interesting experiment is to find out what happens if you try to find
7180 the length of no list at all; that is, if you try to call @code{length}
7181 without giving it an argument, not even an empty list:
7182
7183 @smallexample
7184 (length )
7185 @end smallexample
7186
7187 @need 800
7188 @noindent
7189 What you see, if you evaluate this, is the error message
7190
7191 @smallexample
7192 Lisp error: (wrong-number-of-arguments length 0)
7193 @end smallexample
7194
7195 @noindent
7196 This means that the function receives the wrong number of
7197 arguments, zero, when it expects some other number of arguments. In
7198 this case, one argument is expected, the argument being a list whose
7199 length the function is measuring. (Note that @emph{one} list is
7200 @emph{one} argument, even if the list has many elements inside it.)
7201
7202 The part of the error message that says @samp{length} is the name of
7203 the function.
7204
7205 @ignore
7206 @code{length} is still a subroutine, but you need C-h f to discover that.
7207
7208 In an earlier version:
7209 This is written with a special notation, @samp{#<subr},
7210 that indicates that the function @code{length} is one of the primitive
7211 functions written in C rather than in Emacs Lisp. (@samp{subr} is an
7212 abbreviation for `subroutine'.) @xref{What Is a Function, , What Is a
7213 Function?, elisp , The GNU Emacs Lisp Reference Manual}, for more
7214 about subroutines.
7215 @end ignore
7216
7217 @node nthcdr
7218 @section @code{nthcdr}
7219 @findex nthcdr
7220
7221 The @code{nthcdr} function is associated with the @code{cdr} function.
7222 What it does is take the @sc{cdr} of a list repeatedly.
7223
7224 If you take the @sc{cdr} of the list @code{(pine fir
7225 oak maple)}, you will be returned the list @code{(fir oak maple)}. If you
7226 repeat this on what was returned, you will be returned the list
7227 @code{(oak maple)}. (Of course, repeated @sc{cdr}ing on the original
7228 list will just give you the original @sc{cdr} since the function does
7229 not change the list. You need to evaluate the @sc{cdr} of the
7230 @sc{cdr} and so on.) If you continue this, eventually you will be
7231 returned an empty list, which in this case, instead of being shown as
7232 @code{()} is shown as @code{nil}.
7233
7234 @need 1200
7235 For review, here is a series of repeated @sc{cdr}s, the text following
7236 the @samp{@result{}} shows what is returned.
7237
7238 @smallexample
7239 @group
7240 (cdr '(pine fir oak maple))
7241 @result{}(fir oak maple)
7242 @end group
7243
7244 @group
7245 (cdr '(fir oak maple))
7246 @result{} (oak maple)
7247 @end group
7248
7249 @group
7250 (cdr '(oak maple))
7251 @result{}(maple)
7252 @end group
7253
7254 @group
7255 (cdr '(maple))
7256 @result{} nil
7257 @end group
7258
7259 @group
7260 (cdr 'nil)
7261 @result{} nil
7262 @end group
7263
7264 @group
7265 (cdr ())
7266 @result{} nil
7267 @end group
7268 @end smallexample
7269
7270 @need 1200
7271 You can also do several @sc{cdr}s without printing the values in
7272 between, like this:
7273
7274 @smallexample
7275 @group
7276 (cdr (cdr '(pine fir oak maple)))
7277 @result{} (oak maple)
7278 @end group
7279 @end smallexample
7280
7281 @noindent
7282 In this example, the Lisp interpreter evaluates the innermost list first.
7283 The innermost list is quoted, so it just passes the list as it is to the
7284 innermost @code{cdr}. This @code{cdr} passes a list made up of the
7285 second and subsequent elements of the list to the outermost @code{cdr},
7286 which produces a list composed of the third and subsequent elements of
7287 the original list. In this example, the @code{cdr} function is repeated
7288 and returns a list that consists of the original list without its
7289 first two elements.
7290
7291 The @code{nthcdr} function does the same as repeating the call to
7292 @code{cdr}. In the following example, the argument 2 is passed to the
7293 function @code{nthcdr}, along with the list, and the value returned is
7294 the list without its first two items, which is exactly the same
7295 as repeating @code{cdr} twice on the list:
7296
7297 @smallexample
7298 @group
7299 (nthcdr 2 '(pine fir oak maple))
7300 @result{} (oak maple)
7301 @end group
7302 @end smallexample
7303
7304 @need 1200
7305 Using the original four element list, we can see what happens when
7306 various numeric arguments are passed to @code{nthcdr}, including 0, 1,
7307 and 5:
7308
7309 @smallexample
7310 @group
7311 ;; @r{Leave the list as it was.}
7312 (nthcdr 0 '(pine fir oak maple))
7313 @result{} (pine fir oak maple)
7314 @end group
7315
7316 @group
7317 ;; @r{Return a copy without the first element.}
7318 (nthcdr 1 '(pine fir oak maple))
7319 @result{} (fir oak maple)
7320 @end group
7321
7322 @group
7323 ;; @r{Return a copy of the list without three elements.}
7324 (nthcdr 3 '(pine fir oak maple))
7325 @result{} (maple)
7326 @end group
7327
7328 @group
7329 ;; @r{Return a copy lacking all four elements.}
7330 (nthcdr 4 '(pine fir oak maple))
7331 @result{} nil
7332 @end group
7333
7334 @group
7335 ;; @r{Return a copy lacking all elements.}
7336 (nthcdr 5 '(pine fir oak maple))
7337 @result{} nil
7338 @end group
7339 @end smallexample
7340
7341 @node nth
7342 @section @code{nth}
7343 @findex nth
7344
7345 The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
7346 The @code{nth} function takes the @sc{car} of the result returned by
7347 @code{nthcdr}. It returns the Nth element of the list.
7348
7349 @need 1500
7350 Thus, if it were not defined in C for speed, the definition of
7351 @code{nth} would be:
7352
7353 @smallexample
7354 @group
7355 (defun nth (n list)
7356 "Returns the Nth element of LIST.
7357 N counts from zero. If LIST is not that long, nil is returned."
7358 (car (nthcdr n list)))
7359 @end group
7360 @end smallexample
7361
7362 @noindent
7363 (Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
7364 but its definition was redone in C in the 1980s.)
7365
7366 The @code{nth} function returns a single element of a list.
7367 This can be very convenient.
7368
7369 Note that the elements are numbered from zero, not one. That is to
7370 say, the first element of a list, its @sc{car} is the zeroth element.
7371 This is called `zero-based' counting and often bothers people who
7372 are accustomed to the first element in a list being number one, which
7373 is `one-based'.
7374
7375 @need 1250
7376 For example:
7377
7378 @smallexample
7379 @group
7380 (nth 0 '("one" "two" "three"))
7381 @result{} "one"
7382
7383 (nth 1 '("one" "two" "three"))
7384 @result{} "two"
7385 @end group
7386 @end smallexample
7387
7388 It is worth mentioning that @code{nth}, like @code{nthcdr} and
7389 @code{cdr}, does not change the original list---the function is
7390 non-destructive. This is in sharp contrast to the @code{setcar} and
7391 @code{setcdr} functions.
7392
7393 @node setcar
7394 @section @code{setcar}
7395 @findex setcar
7396
7397 As you might guess from their names, the @code{setcar} and @code{setcdr}
7398 functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7399 They actually change the original list, unlike @code{car} and @code{cdr}
7400 which leave the original list as it was. One way to find out how this
7401 works is to experiment. We will start with the @code{setcar} function.
7402
7403 @need 1200
7404 First, we can make a list and then set the value of a variable to the
7405 list, using the @code{setq} function. Here is a list of animals:
7406
7407 @smallexample
7408 (setq animals '(antelope giraffe lion tiger))
7409 @end smallexample
7410
7411 @noindent
7412 If you are reading this in Info inside of GNU Emacs, you can evaluate
7413 this expression in the usual fashion, by positioning the cursor after
7414 the expression and typing @kbd{C-x C-e}. (I'm doing this right here
7415 as I write this. This is one of the advantages of having the
7416 interpreter built into the computing environment. Incidentally, when
7417 there is nothing on the line after the final parentheses, such as a
7418 comment, point can be on the next line. Thus, if your cursor is in
7419 the first column of the next line, you do not need to move it.
7420 Indeed, Emacs permits any amount of white space after the final
7421 parenthesis.)
7422
7423 @need 1200
7424 When we evaluate the variable @code{animals}, we see that it is bound to
7425 the list @code{(antelope giraffe lion tiger)}:
7426
7427 @smallexample
7428 @group
7429 animals
7430 @result{} (antelope giraffe lion tiger)
7431 @end group
7432 @end smallexample
7433
7434 @noindent
7435 Put another way, the variable @code{animals} points to the list
7436 @code{(antelope giraffe lion tiger)}.
7437
7438 Next, evaluate the function @code{setcar} while passing it two
7439 arguments, the variable @code{animals} and the quoted symbol
7440 @code{hippopotamus}; this is done by writing the three element list
7441 @code{(setcar animals 'hippopotamus)} and then evaluating it in the
7442 usual fashion:
7443
7444 @smallexample
7445 (setcar animals 'hippopotamus)
7446 @end smallexample
7447
7448 @need 1200
7449 @noindent
7450 After evaluating this expression, evaluate the variable @code{animals}
7451 again. You will see that the list of animals has changed:
7452
7453 @smallexample
7454 @group
7455 animals
7456 @result{} (hippopotamus giraffe lion tiger)
7457 @end group
7458 @end smallexample
7459
7460 @noindent
7461 The first element on the list, @code{antelope} is replaced by
7462 @code{hippopotamus}.
7463
7464 So we can see that @code{setcar} did not add a new element to the list
7465 as @code{cons} would have; it replaced @code{antelope} with
7466 @code{hippopotamus}; it @emph{changed} the list.
7467
7468 @node setcdr
7469 @section @code{setcdr}
7470 @findex setcdr
7471
7472 The @code{setcdr} function is similar to the @code{setcar} function,
7473 except that the function replaces the second and subsequent elements of
7474 a list rather than the first element.
7475
7476 (To see how to change the last element of a list, look ahead to
7477 @ref{kill-new function, , The @code{kill-new} function}, which uses
7478 the @code{nthcdr} and @code{setcdr} functions.)
7479
7480 @need 1200
7481 To see how this works, set the value of the variable to a list of
7482 domesticated animals by evaluating the following expression:
7483
7484 @smallexample
7485 (setq domesticated-animals '(horse cow sheep goat))
7486 @end smallexample
7487
7488 @need 1200
7489 @noindent
7490 If you now evaluate the list, you will be returned the list
7491 @code{(horse cow sheep goat)}:
7492
7493 @smallexample
7494 @group
7495 domesticated-animals
7496 @result{} (horse cow sheep goat)
7497 @end group
7498 @end smallexample
7499
7500 @need 1200
7501 Next, evaluate @code{setcdr} with two arguments, the name of the
7502 variable which has a list as its value, and the list to which the
7503 @sc{cdr} of the first list will be set;
7504
7505 @smallexample
7506 (setcdr domesticated-animals '(cat dog))
7507 @end smallexample
7508
7509 @noindent
7510 If you evaluate this expression, the list @code{(cat dog)} will appear
7511 in the echo area. This is the value returned by the function. The
7512 result we are interested in is the ``side effect'', which we can see by
7513 evaluating the variable @code{domesticated-animals}:
7514
7515 @smallexample
7516 @group
7517 domesticated-animals
7518 @result{} (horse cat dog)
7519 @end group
7520 @end smallexample
7521
7522 @noindent
7523 Indeed, the list is changed from @code{(horse cow sheep goat)} to
7524 @code{(horse cat dog)}. The @sc{cdr} of the list is changed from
7525 @code{(cow sheep goat)} to @code{(cat dog)}.
7526
7527 @node cons Exercise
7528 @section Exercise
7529
7530 Construct a list of four birds by evaluating several expressions with
7531 @code{cons}. Find out what happens when you @code{cons} a list onto
7532 itself. Replace the first element of the list of four birds with a
7533 fish. Replace the rest of that list with a list of other fish.
7534
7535 @node Cutting & Storing Text
7536 @chapter Cutting and Storing Text
7537 @cindex Cutting and storing text
7538 @cindex Storing and cutting text
7539 @cindex Killing text
7540 @cindex Clipping text
7541 @cindex Erasing text
7542 @cindex Deleting text
7543
7544 Whenever you cut or clip text out of a buffer with a `kill' command in
7545 GNU Emacs, it is stored in a list and you can bring it back with a
7546 `yank' command.
7547
7548 (The use of the word `kill' in Emacs for processes which specifically
7549 @emph{do not} destroy the values of the entities is an unfortunate
7550 historical accident. A much more appropriate word would be `clip' since
7551 that is what the kill commands do; they clip text out of a buffer and
7552 put it into storage from which it can be brought back. I have often
7553 been tempted to replace globally all occurrences of `kill' in the Emacs
7554 sources with `clip' and all occurrences of `killed' with `clipped'.)
7555
7556 @menu
7557 * Storing Text:: Text is stored in a list.
7558 * zap-to-char:: Cutting out text up to a character.
7559 * kill-region:: Cutting text out of a region.
7560 * copy-region-as-kill:: A definition for copying text.
7561 * Digression into C:: Minor note on C programming language macros.
7562 * defvar:: How to give a variable an initial value.
7563 * cons & search-fwd Review::
7564 * search Exercises::
7565 @end menu
7566
7567 @ifnottex
7568 @node Storing Text
7569 @unnumberedsec Storing Text in a List
7570 @end ifnottex
7571
7572 When text is cut out of a buffer, it is stored on a list. Successive
7573 pieces of text are stored on the list successively, so the list might
7574 look like this:
7575
7576 @smallexample
7577 ("a piece of text" "previous piece")
7578 @end smallexample
7579
7580 @need 1200
7581 @noindent
7582 The function @code{cons} can be used to create a new list from a piece
7583 of text (an `atom', to use the jargon) and an existing list, like
7584 this:
7585
7586 @smallexample
7587 @group
7588 (cons "another piece"
7589 '("a piece of text" "previous piece"))
7590 @end group
7591 @end smallexample
7592
7593 @need 1200
7594 @noindent
7595 If you evaluate this expression, a list of three elements will appear in
7596 the echo area:
7597
7598 @smallexample
7599 ("another piece" "a piece of text" "previous piece")
7600 @end smallexample
7601
7602 With the @code{car} and @code{nthcdr} functions, you can retrieve
7603 whichever piece of text you want. For example, in the following code,
7604 @code{nthcdr 1 @dots{}} returns the list with the first item removed;
7605 and the @code{car} returns the first element of that remainder---the
7606 second element of the original list:
7607
7608 @smallexample
7609 @group
7610 (car (nthcdr 1 '("another piece"
7611 "a piece of text"
7612 "previous piece")))
7613 @result{} "a piece of text"
7614 @end group
7615 @end smallexample
7616
7617 The actual functions in Emacs are more complex than this, of course.
7618 The code for cutting and retrieving text has to be written so that
7619 Emacs can figure out which element in the list you want---the first,
7620 second, third, or whatever. In addition, when you get to the end of
7621 the list, Emacs should give you the first element of the list, rather
7622 than nothing at all.
7623
7624 The list that holds the pieces of text is called the @dfn{kill ring}.
7625 This chapter leads up to a description of the kill ring and how it is
7626 used by first tracing how the @code{zap-to-char} function works. This
7627 function uses (or `calls') a function that invokes a function that
7628 manipulates the kill ring. Thus, before reaching the mountains, we
7629 climb the foothills.
7630
7631 A subsequent chapter describes how text that is cut from the buffer is
7632 retrieved. @xref{Yanking, , Yanking Text Back}.
7633
7634 @node zap-to-char
7635 @section @code{zap-to-char}
7636 @findex zap-to-char
7637
7638 @c FIXME remove obsolete stuff
7639 The @code{zap-to-char} function changed little between GNU Emacs
7640 version 19 and GNU Emacs version 22. However, @code{zap-to-char}
7641 calls another function, @code{kill-region}, which enjoyed a major
7642 rewrite.
7643
7644 The @code{kill-region} function in Emacs 19 is complex, but does not
7645 use code that is important at this time. We will skip it.
7646
7647 The @code{kill-region} function in Emacs 22 is easier to read than the
7648 same function in Emacs 19 and introduces a very important concept,
7649 that of error handling. We will walk through the function.
7650
7651 But first, let us look at the interactive @code{zap-to-char} function.
7652
7653 @menu
7654 * Complete zap-to-char:: The complete implementation.
7655 * zap-to-char interactive:: A three part interactive expression.
7656 * zap-to-char body:: A short overview.
7657 * search-forward:: How to search for a string.
7658 * progn:: The @code{progn} special form.
7659 * Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
7660 @end menu
7661
7662 @ifnottex
7663 @node Complete zap-to-char
7664 @unnumberedsubsec The Complete @code{zap-to-char} Implementation
7665 @end ifnottex
7666
7667 The @code{zap-to-char} function removes the text in the region between
7668 the location of the cursor (i.e., of point) up to and including the
7669 next occurrence of a specified character. The text that
7670 @code{zap-to-char} removes is put in the kill ring; and it can be
7671 retrieved from the kill ring by typing @kbd{C-y} (@code{yank}). If
7672 the command is given an argument, it removes text through that number
7673 of occurrences. Thus, if the cursor were at the beginning of this
7674 sentence and the character were @samp{s}, @samp{Thus} would be
7675 removed. If the argument were two, @samp{Thus, if the curs} would be
7676 removed, up to and including the @samp{s} in @samp{cursor}.
7677
7678 If the specified character is not found, @code{zap-to-char} will say
7679 ``Search failed'', tell you the character you typed, and not remove
7680 any text.
7681
7682 In order to determine how much text to remove, @code{zap-to-char} uses
7683 a search function. Searches are used extensively in code that
7684 manipulates text, and we will focus attention on them as well as on the
7685 deletion command.
7686
7687 @ignore
7688 @c GNU Emacs version 19
7689 (defun zap-to-char (arg char) ; version 19 implementation
7690 "Kill up to and including ARG'th occurrence of CHAR.
7691 Goes backward if ARG is negative; error if CHAR not found."
7692 (interactive "*p\ncZap to char: ")
7693 (kill-region (point)
7694 (progn
7695 (search-forward
7696 (char-to-string char) nil nil arg)
7697 (point))))
7698 @end ignore
7699
7700 @need 1250
7701 Here is the complete text of the version 22 implementation of the function:
7702
7703 @c GNU Emacs 22
7704 @smallexample
7705 @group
7706 (defun zap-to-char (arg char)
7707 "Kill up to and including ARG'th occurrence of CHAR.
7708 Case is ignored if `case-fold-search' is non-nil in the current buffer.
7709 Goes backward if ARG is negative; error if CHAR not found."
7710 (interactive "p\ncZap to char: ")
7711 (if (char-table-p translation-table-for-input)
7712 (setq char (or (aref translation-table-for-input char) char)))
7713 (kill-region (point) (progn
7714 (search-forward (char-to-string char)
7715 nil nil arg)
7716 (point))))
7717 @end group
7718 @end smallexample
7719
7720 The documentation is thorough. You do need to know the jargon meaning
7721 of the word `kill'.
7722
7723 @node zap-to-char interactive
7724 @subsection The @code{interactive} Expression
7725
7726 @need 800
7727 The interactive expression in the @code{zap-to-char} command looks like
7728 this:
7729
7730 @smallexample
7731 (interactive "p\ncZap to char: ")
7732 @end smallexample
7733
7734 The part within quotation marks, @code{"p\ncZap to char:@: "}, specifies
7735 two different things. First, and most simply, is the @samp{p}.
7736 This part is separated from the next part by a newline, @samp{\n}.
7737 The @samp{p} means that the first argument to the function will be
7738 passed the value of a `processed prefix'. The prefix argument is
7739 passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number. If
7740 the function is called interactively without a prefix, 1 is passed to
7741 this argument.
7742
7743 The second part of @code{"p\ncZap to char:@: "} is
7744 @samp{cZap to char:@: }. In this part, the lower case @samp{c}
7745 indicates that @code{interactive} expects a prompt and that the
7746 argument will be a character. The prompt follows the @samp{c} and is
7747 the string @samp{Zap to char:@: } (with a space after the colon to
7748 make it look good).
7749
7750 What all this does is prepare the arguments to @code{zap-to-char} so they
7751 are of the right type, and give the user a prompt.
7752
7753 In a read-only buffer, the @code{zap-to-char} function copies the text
7754 to the kill ring, but does not remove it. The echo area displays a
7755 message saying that the buffer is read-only. Also, the terminal may
7756 beep or blink at you.
7757
7758 @node zap-to-char body
7759 @subsection The Body of @code{zap-to-char}
7760
7761 The body of the @code{zap-to-char} function contains the code that
7762 kills (that is, removes) the text in the region from the current
7763 position of the cursor up to and including the specified character.
7764
7765 The first part of the code looks like this:
7766
7767 @smallexample
7768 (if (char-table-p translation-table-for-input)
7769 (setq char (or (aref translation-table-for-input char) char)))
7770 (kill-region (point) (progn
7771 (search-forward (char-to-string char) nil nil arg)
7772 (point)))
7773 @end smallexample
7774
7775 @noindent
7776 @code{char-table-p} is an hitherto unseen function. It determines
7777 whether its argument is a character table. When it is, it sets the
7778 character passed to @code{zap-to-char} to one of them, if that
7779 character exists, or to the character itself. (This becomes important
7780 for certain characters in non-European languages. The @code{aref}
7781 function extracts an element from an array. It is an array-specific
7782 function that is not described in this document. @xref{Arrays, ,
7783 Arrays, elisp, The GNU Emacs Lisp Reference Manual}.)
7784
7785 @noindent
7786 @code{(point)} is the current position of the cursor.
7787
7788 The next part of the code is an expression using @code{progn}. The body
7789 of the @code{progn} consists of calls to @code{search-forward} and
7790 @code{point}.
7791
7792 It is easier to understand how @code{progn} works after learning about
7793 @code{search-forward}, so we will look at @code{search-forward} and
7794 then at @code{progn}.
7795
7796 @node search-forward
7797 @subsection The @code{search-forward} Function
7798 @findex search-forward
7799
7800 The @code{search-forward} function is used to locate the
7801 zapped-for-character in @code{zap-to-char}. If the search is
7802 successful, @code{search-forward} leaves point immediately after the
7803 last character in the target string. (In @code{zap-to-char}, the
7804 target string is just one character long. @code{zap-to-char} uses the
7805 function @code{char-to-string} to ensure that the computer treats that
7806 character as a string.) If the search is backwards,
7807 @code{search-forward} leaves point just before the first character in
7808 the target. Also, @code{search-forward} returns @code{t} for true.
7809 (Moving point is therefore a `side effect'.)
7810
7811 @need 1250
7812 In @code{zap-to-char}, the @code{search-forward} function looks like this:
7813
7814 @smallexample
7815 (search-forward (char-to-string char) nil nil arg)
7816 @end smallexample
7817
7818 The @code{search-forward} function takes four arguments:
7819
7820 @enumerate
7821 @item
7822 The first argument is the target, what is searched for. This must be a
7823 string, such as @samp{"z"}.
7824
7825 As it happens, the argument passed to @code{zap-to-char} is a single
7826 character. Because of the way computers are built, the Lisp
7827 interpreter may treat a single character as being different from a
7828 string of characters. Inside the computer, a single character has a
7829 different electronic format than a string of one character. (A single
7830 character can often be recorded in the computer using exactly one
7831 byte; but a string may be longer, and the computer needs to be ready
7832 for this.) Since the @code{search-forward} function searches for a
7833 string, the character that the @code{zap-to-char} function receives as
7834 its argument must be converted inside the computer from one format to
7835 the other; otherwise the @code{search-forward} function will fail.
7836 The @code{char-to-string} function is used to make this conversion.
7837
7838 @item
7839 The second argument bounds the search; it is specified as a position in
7840 the buffer. In this case, the search can go to the end of the buffer,
7841 so no bound is set and the second argument is @code{nil}.
7842
7843 @item
7844 The third argument tells the function what it should do if the search
7845 fails---it can signal an error (and print a message) or it can return
7846 @code{nil}. A @code{nil} as the third argument causes the function to
7847 signal an error when the search fails.
7848
7849 @item
7850 The fourth argument to @code{search-forward} is the repeat count---how
7851 many occurrences of the string to look for. This argument is optional
7852 and if the function is called without a repeat count, this argument is
7853 passed the value 1. If this argument is negative, the search goes
7854 backwards.
7855 @end enumerate
7856
7857 @need 800
7858 In template form, a @code{search-forward} expression looks like this:
7859
7860 @smallexample
7861 @group
7862 (search-forward "@var{target-string}"
7863 @var{limit-of-search}
7864 @var{what-to-do-if-search-fails}
7865 @var{repeat-count})
7866 @end group
7867 @end smallexample
7868
7869 We will look at @code{progn} next.
7870
7871 @node progn
7872 @subsection The @code{progn} Special Form
7873 @findex progn
7874
7875 @code{progn} is a special form that causes each of its arguments to be
7876 evaluated in sequence and then returns the value of the last one. The
7877 preceding expressions are evaluated only for the side effects they
7878 perform. The values produced by them are discarded.
7879
7880 @need 800
7881 The template for a @code{progn} expression is very simple:
7882
7883 @smallexample
7884 @group
7885 (progn
7886 @var{body}@dots{})
7887 @end group
7888 @end smallexample
7889
7890 In @code{zap-to-char}, the @code{progn} expression has to do two things:
7891 put point in exactly the right position; and return the location of
7892 point so that @code{kill-region} will know how far to kill to.
7893
7894 The first argument to the @code{progn} is @code{search-forward}. When
7895 @code{search-forward} finds the string, the function leaves point
7896 immediately after the last character in the target string. (In this
7897 case the target string is just one character long.) If the search is
7898 backwards, @code{search-forward} leaves point just before the first
7899 character in the target. The movement of point is a side effect.
7900
7901 The second and last argument to @code{progn} is the expression
7902 @code{(point)}. This expression returns the value of point, which in
7903 this case will be the location to which it has been moved by
7904 @code{search-forward}. (In the source, a line that tells the function
7905 to go to the previous character, if it is going forward, was commented
7906 out in 1999; I don't remember whether that feature or mis-feature was
7907 ever a part of the distributed source.) The value of @code{point} is
7908 returned by the @code{progn} expression and is passed to
7909 @code{kill-region} as @code{kill-region}'s second argument.
7910
7911 @node Summing up zap-to-char
7912 @subsection Summing up @code{zap-to-char}
7913
7914 Now that we have seen how @code{search-forward} and @code{progn} work,
7915 we can see how the @code{zap-to-char} function works as a whole.
7916
7917 The first argument to @code{kill-region} is the position of the cursor
7918 when the @code{zap-to-char} command is given---the value of point at
7919 that time. Within the @code{progn}, the search function then moves
7920 point to just after the zapped-to-character and @code{point} returns the
7921 value of this location. The @code{kill-region} function puts together
7922 these two values of point, the first one as the beginning of the region
7923 and the second one as the end of the region, and removes the region.
7924
7925 The @code{progn} special form is necessary because the
7926 @code{kill-region} command takes two arguments; and it would fail if
7927 @code{search-forward} and @code{point} expressions were written in
7928 sequence as two additional arguments. The @code{progn} expression is
7929 a single argument to @code{kill-region} and returns the one value that
7930 @code{kill-region} needs for its second argument.
7931
7932 @node kill-region
7933 @section @code{kill-region}
7934 @findex kill-region
7935
7936 The @code{zap-to-char} function uses the @code{kill-region} function.
7937 This function clips text from a region and copies that text to
7938 the kill ring, from which it may be retrieved.
7939
7940 @ignore
7941 GNU Emacs 22:
7942
7943 (defun kill-region (beg end &optional yank-handler)
7944 "Kill (\"cut\") text between point and mark.
7945 This deletes the text from the buffer and saves it in the kill ring.
7946 The command \\[yank] can retrieve it from there.
7947 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
7948
7949 If you want to append the killed region to the last killed text,
7950 use \\[append-next-kill] before \\[kill-region].
7951
7952 If the buffer is read-only, Emacs will beep and refrain from deleting
7953 the text, but put the text in the kill ring anyway. This means that
7954 you can use the killing commands to copy text from a read-only buffer.
7955
7956 This is the primitive for programs to kill text (as opposed to deleting it).
7957 Supply two arguments, character positions indicating the stretch of text
7958 to be killed.
7959 Any command that calls this function is a \"kill command\".
7960 If the previous command was also a kill command,
7961 the text killed this time appends to the text killed last time
7962 to make one entry in the kill ring.
7963
7964 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
7965 specifies the yank-handler text property to be set on the killed
7966 text. See `insert-for-yank'."
7967 ;; Pass point first, then mark, because the order matters
7968 ;; when calling kill-append.
7969 (interactive (list (point) (mark)))
7970 (unless (and beg end)
7971 (error "The mark is not set now, so there is no region"))
7972 (condition-case nil
7973 (let ((string (filter-buffer-substring beg end t)))
7974 (when string ;STRING is nil if BEG = END
7975 ;; Add that string to the kill ring, one way or another.
7976 (if (eq last-command 'kill-region)
7977 (kill-append string (< end beg) yank-handler)
7978 (kill-new string nil yank-handler)))
7979 (when (or string (eq last-command 'kill-region))
7980 (setq this-command 'kill-region))
7981 nil)
7982 ((buffer-read-only text-read-only)
7983 ;; The code above failed because the buffer, or some of the characters
7984 ;; in the region, are read-only.
7985 ;; We should beep, in case the user just isn't aware of this.
7986 ;; However, there's no harm in putting
7987 ;; the region's text in the kill ring, anyway.
7988 (copy-region-as-kill beg end)
7989 ;; Set this-command now, so it will be set even if we get an error.
7990 (setq this-command 'kill-region)
7991 ;; This should barf, if appropriate, and give us the correct error.
7992 (if kill-read-only-ok
7993 (progn (message "Read only text copied to kill ring") nil)
7994 ;; Signal an error if the buffer is read-only.
7995 (barf-if-buffer-read-only)
7996 ;; If the buffer isn't read-only, the text is.
7997 (signal 'text-read-only (list (current-buffer)))))))
7998 @end ignore
7999
8000 The Emacs 22 version of that function uses @code{condition-case} and
8001 @code{copy-region-as-kill}, both of which we will explain.
8002 @code{condition-case} is an important special form.
8003
8004 In essence, the @code{kill-region} function calls
8005 @code{condition-case}, which takes three arguments. In this function,
8006 the first argument does nothing. The second argument contains the
8007 code that does the work when all goes well. The third argument
8008 contains the code that is called in the event of an error.
8009
8010 @menu
8011 * Complete kill-region:: The function definition.
8012 * condition-case:: Dealing with a problem.
8013 * Lisp macro::
8014 @end menu
8015
8016 @ifnottex
8017 @node Complete kill-region
8018 @unnumberedsubsec The Complete @code{kill-region} Definition
8019 @end ifnottex
8020
8021 @need 1200
8022 We will go through the @code{condition-case} code in a moment. First,
8023 let us look at the definition of @code{kill-region}, with comments
8024 added:
8025
8026 @c GNU Emacs 22:
8027 @smallexample
8028 @group
8029 (defun kill-region (beg end)
8030 "Kill (\"cut\") text between point and mark.
8031 This deletes the text from the buffer and saves it in the kill ring.
8032 The command \\[yank] can retrieve it from there. @dots{} "
8033 @end group
8034
8035 @group
8036 ;; @bullet{} Since order matters, pass point first.
8037 (interactive (list (point) (mark)))
8038 ;; @bullet{} And tell us if we cannot cut the text.
8039 ;; `unless' is an `if' without a then-part.
8040 (unless (and beg end)
8041 (error "The mark is not set now, so there is no region"))
8042 @end group
8043
8044 @group
8045 ;; @bullet{} `condition-case' takes three arguments.
8046 ;; If the first argument is nil, as it is here,
8047 ;; information about the error signal is not
8048 ;; stored for use by another function.
8049 (condition-case nil
8050 @end group
8051
8052 @group
8053 ;; @bullet{} The second argument to `condition-case' tells the
8054 ;; Lisp interpreter what to do when all goes well.
8055 @end group
8056
8057 @group
8058 ;; It starts with a `let' function that extracts the string
8059 ;; and tests whether it exists. If so (that is what the
8060 ;; `when' checks), it calls an `if' function that determines
8061 ;; whether the previous command was another call to
8062 ;; `kill-region'; if it was, then the new text is appended to
8063 ;; the previous text; if not, then a different function,
8064 ;; `kill-new', is called.
8065 @end group
8066
8067 @group
8068 ;; The `kill-append' function concatenates the new string and
8069 ;; the old. The `kill-new' function inserts text into a new
8070 ;; item in the kill ring.
8071 @end group
8072
8073 @group
8074 ;; `when' is an `if' without an else-part. The second `when'
8075 ;; again checks whether the current string exists; in
8076 ;; addition, it checks whether the previous command was
8077 ;; another call to `kill-region'. If one or the other
8078 ;; condition is true, then it sets the current command to
8079 ;; be `kill-region'.
8080 @end group
8081 @group
8082 (let ((string (filter-buffer-substring beg end t)))
8083 (when string ;STRING is nil if BEG = END
8084 ;; Add that string to the kill ring, one way or another.
8085 (if (eq last-command 'kill-region)
8086 @end group
8087 @group
8088 ;; @minus{} `yank-handler' is an optional argument to
8089 ;; `kill-region' that tells the `kill-append' and
8090 ;; `kill-new' functions how deal with properties
8091 ;; added to the text, such as `bold' or `italics'.
8092 (kill-append string (< end beg) yank-handler)
8093 (kill-new string nil yank-handler)))
8094 (when (or string (eq last-command 'kill-region))
8095 (setq this-command 'kill-region))
8096 nil)
8097 @end group
8098
8099 @group
8100 ;; @bullet{} The third argument to `condition-case' tells the interpreter
8101 ;; what to do with an error.
8102 @end group
8103 @group
8104 ;; The third argument has a conditions part and a body part.
8105 ;; If the conditions are met (in this case,
8106 ;; if text or buffer are read-only)
8107 ;; then the body is executed.
8108 @end group
8109 @group
8110 ;; The first part of the third argument is the following:
8111 ((buffer-read-only text-read-only) ;; the if-part
8112 ;; @dots{} the then-part
8113 (copy-region-as-kill beg end)
8114 @end group
8115 @group
8116 ;; Next, also as part of the then-part, set this-command, so
8117 ;; it will be set in an error
8118 (setq this-command 'kill-region)
8119 ;; Finally, in the then-part, send a message if you may copy
8120 ;; the text to the kill ring without signaling an error, but
8121 ;; don't if you may not.
8122 @end group
8123 @group
8124 (if kill-read-only-ok
8125 (progn (message "Read only text copied to kill ring") nil)
8126 (barf-if-buffer-read-only)
8127 ;; If the buffer isn't read-only, the text is.
8128 (signal 'text-read-only (list (current-buffer)))))
8129 @end group
8130 @end smallexample
8131
8132 @ignore
8133 @c v 21
8134 @smallexample
8135 @group
8136 (defun kill-region (beg end)
8137 "Kill between point and mark.
8138 The text is deleted but saved in the kill ring."
8139 (interactive "r")
8140 @end group
8141
8142 @group
8143 ;; 1. `condition-case' takes three arguments.
8144 ;; If the first argument is nil, as it is here,
8145 ;; information about the error signal is not
8146 ;; stored for use by another function.
8147 (condition-case nil
8148 @end group
8149
8150 @group
8151 ;; 2. The second argument to `condition-case'
8152 ;; tells the Lisp interpreter what to do when all goes well.
8153 @end group
8154
8155 @group
8156 ;; The `delete-and-extract-region' function usually does the
8157 ;; work. If the beginning and ending of the region are both
8158 ;; the same, then the variable `string' will be empty, or nil
8159 (let ((string (delete-and-extract-region beg end)))
8160 @end group
8161
8162 @group
8163 ;; `when' is an `if' clause that cannot take an `else-part'.
8164 ;; Emacs normally sets the value of `last-command' to the
8165 ;; previous command.
8166 @end group
8167 @group
8168 ;; `kill-append' concatenates the new string and the old.
8169 ;; `kill-new' inserts text into a new item in the kill ring.
8170 (when string
8171 (if (eq last-command 'kill-region)
8172 ;; if true, prepend string
8173 (kill-append string (< end beg))
8174 (kill-new string)))
8175 (setq this-command 'kill-region))
8176 @end group
8177
8178 @group
8179 ;; 3. The third argument to `condition-case' tells the interpreter
8180 ;; what to do with an error.
8181 @end group
8182 @group
8183 ;; The third argument has a conditions part and a body part.
8184 ;; If the conditions are met (in this case,
8185 ;; if text or buffer are read-only)
8186 ;; then the body is executed.
8187 @end group
8188 @group
8189 ((buffer-read-only text-read-only) ;; this is the if-part
8190 ;; then...
8191 (copy-region-as-kill beg end)
8192 @end group
8193 @group
8194 (if kill-read-only-ok ;; usually this variable is nil
8195 (message "Read only text copied to kill ring")
8196 ;; or else, signal an error if the buffer is read-only;
8197 (barf-if-buffer-read-only)
8198 ;; and, in any case, signal that the text is read-only.
8199 (signal 'text-read-only (list (current-buffer)))))))
8200 @end group
8201 @end smallexample
8202 @end ignore
8203
8204 @node condition-case
8205 @subsection @code{condition-case}
8206 @findex condition-case
8207
8208 As we have seen earlier (@pxref{Making Errors, , Generate an Error
8209 Message}), when the Emacs Lisp interpreter has trouble evaluating an
8210 expression, it provides you with help; in the jargon, this is called
8211 ``signaling an error''. Usually, the computer stops the program and
8212 shows you a message.
8213
8214 However, some programs undertake complicated actions. They should not
8215 simply stop on an error. In the @code{kill-region} function, the most
8216 likely error is that you will try to kill text that is read-only and
8217 cannot be removed. So the @code{kill-region} function contains code
8218 to handle this circumstance. This code, which makes up the body of
8219 the @code{kill-region} function, is inside of a @code{condition-case}
8220 special form.
8221
8222 @need 800
8223 The template for @code{condition-case} looks like this:
8224
8225 @smallexample
8226 @group
8227 (condition-case
8228 @var{var}
8229 @var{bodyform}
8230 @var{error-handler}@dots{})
8231 @end group
8232 @end smallexample
8233
8234 The second argument, @var{bodyform}, is straightforward. The
8235 @code{condition-case} special form causes the Lisp interpreter to
8236 evaluate the code in @var{bodyform}. If no error occurs, the special
8237 form returns the code's value and produces the side-effects, if any.
8238
8239 In short, the @var{bodyform} part of a @code{condition-case}
8240 expression determines what should happen when everything works
8241 correctly.
8242
8243 However, if an error occurs, among its other actions, the function
8244 generating the error signal will define one or more error condition
8245 names.
8246
8247 An error handler is the third argument to @code{condition case}.
8248 An error handler has two parts, a @var{condition-name} and a
8249 @var{body}. If the @var{condition-name} part of an error handler
8250 matches a condition name generated by an error, then the @var{body}
8251 part of the error handler is run.
8252
8253 As you will expect, the @var{condition-name} part of an error handler
8254 may be either a single condition name or a list of condition names.
8255
8256 Also, a complete @code{condition-case} expression may contain more
8257 than one error handler. When an error occurs, the first applicable
8258 handler is run.
8259
8260 Lastly, the first argument to the @code{condition-case} expression,
8261 the @var{var} argument, is sometimes bound to a variable that
8262 contains information about the error. However, if that argument is
8263 nil, as is the case in @code{kill-region}, that information is
8264 discarded.
8265
8266 @need 1200
8267 In brief, in the @code{kill-region} function, the code
8268 @code{condition-case} works like this:
8269
8270 @smallexample
8271 @group
8272 @var{If no errors}, @var{run only this code}
8273 @var{but}, @var{if errors}, @var{run this other code}.
8274 @end group
8275 @end smallexample
8276
8277 @ignore
8278 2006 Oct 24
8279 In Emacs 22,
8280 copy-region-as-kill is short, 12 lines, and uses
8281 filter-buffer-substring, which is longer, 39 lines
8282 and has delete-and-extract-region in it.
8283 delete-and-extract-region is written in C.
8284
8285 see Initializing a Variable with @code{defvar}
8286 this is line 8054
8287 Initializing a Variable with @code{defvar} includes line 8350
8288 @end ignore
8289
8290 @node Lisp macro
8291 @subsection Lisp macro
8292 @cindex Macro, lisp
8293 @cindex Lisp macro
8294
8295 The part of the @code{condition-case} expression that is evaluated in
8296 the expectation that all goes well has a @code{when}. The code uses
8297 @code{when} to determine whether the @code{string} variable points to
8298 text that exists.
8299
8300 A @code{when} expression is simply a programmers' convenience. It is
8301 an @code{if} without the possibility of an else clause. In your mind,
8302 you can replace @code{when} with @code{if} and understand what goes
8303 on. That is what the Lisp interpreter does.
8304
8305 Technically speaking, @code{when} is a Lisp macro. A Lisp @dfn{macro}
8306 enables you to define new control constructs and other language
8307 features. It tells the interpreter how to compute another Lisp
8308 expression which will in turn compute the value. In this case, the
8309 `other expression' is an @code{if} expression.
8310
8311 The @code{kill-region} function definition also has an @code{unless}
8312 macro; it is the converse of @code{when}. The @code{unless} macro is
8313 an @code{if} without a then clause
8314
8315 For more about Lisp macros, see @ref{Macros, , Macros, elisp, The GNU
8316 Emacs Lisp Reference Manual}. The C programming language also
8317 provides macros. These are different, but also useful.
8318
8319 @ignore
8320 We will briefly look at C macros in
8321 @ref{Digression into C}.
8322 @end ignore
8323
8324 @need 1200
8325 Regarding the @code{when} macro, in the @code{condition-case}
8326 expression, when the string has content, then another conditional
8327 expression is executed. This is an @code{if} with both a then-part
8328 and an else-part.
8329
8330 @smallexample
8331 @group
8332 (if (eq last-command 'kill-region)
8333 (kill-append string (< end beg) yank-handler)
8334 (kill-new string nil yank-handler))
8335 @end group
8336 @end smallexample
8337
8338 The then-part is evaluated if the previous command was another call to
8339 @code{kill-region}; if not, the else-part is evaluated.
8340
8341 @code{yank-handler} is an optional argument to @code{kill-region} that
8342 tells the @code{kill-append} and @code{kill-new} functions how deal
8343 with properties added to the text, such as `bold' or `italics'.
8344
8345 @code{last-command} is a variable that comes with Emacs that we have
8346 not seen before. Normally, whenever a function is executed, Emacs
8347 sets the value of @code{last-command} to the previous command.
8348
8349 @need 1200
8350 In this segment of the definition, the @code{if} expression checks
8351 whether the previous command was @code{kill-region}. If it was,
8352
8353 @smallexample
8354 (kill-append string (< end beg) yank-handler)
8355 @end smallexample
8356
8357 @noindent
8358 concatenates a copy of the newly clipped text to the just previously
8359 clipped text in the kill ring.
8360
8361 @node copy-region-as-kill
8362 @section @code{copy-region-as-kill}
8363 @findex copy-region-as-kill
8364 @findex nthcdr
8365
8366 The @code{copy-region-as-kill} function copies a region of text from a
8367 buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8368 in the @code{kill-ring}.
8369
8370 If you call @code{copy-region-as-kill} immediately after a
8371 @code{kill-region} command, Emacs appends the newly copied text to the
8372 previously copied text. This means that if you yank back the text, you
8373 get it all, from both this and the previous operation. On the other
8374 hand, if some other command precedes the @code{copy-region-as-kill},
8375 the function copies the text into a separate entry in the kill ring.
8376
8377 @menu
8378 * Complete copy-region-as-kill:: The complete function definition.
8379 * copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
8380 @end menu
8381
8382 @ifnottex
8383 @node Complete copy-region-as-kill
8384 @unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8385 @end ifnottex
8386
8387 @need 1200
8388 Here is the complete text of the version 22 @code{copy-region-as-kill}
8389 function:
8390
8391 @smallexample
8392 @group
8393 (defun copy-region-as-kill (beg end)
8394 "Save the region as if killed, but don't kill it.
8395 In Transient Mark mode, deactivate the mark.
8396 If `interprogram-cut-function' is non-nil, also save the text for a window
8397 system cut and paste."
8398 (interactive "r")
8399 @end group
8400 @group
8401 (if (eq last-command 'kill-region)
8402 (kill-append (filter-buffer-substring beg end) (< end beg))
8403 (kill-new (filter-buffer-substring beg end)))
8404 @end group
8405 @group
8406 (if transient-mark-mode
8407 (setq deactivate-mark t))
8408 nil)
8409 @end group
8410 @end smallexample
8411
8412 @need 800
8413 As usual, this function can be divided into its component parts:
8414
8415 @smallexample
8416 @group
8417 (defun copy-region-as-kill (@var{argument-list})
8418 "@var{documentation}@dots{}"
8419 (interactive "r")
8420 @var{body}@dots{})
8421 @end group
8422 @end smallexample
8423
8424 The arguments are @code{beg} and @code{end} and the function is
8425 interactive with @code{"r"}, so the two arguments must refer to the
8426 beginning and end of the region. If you have been reading though this
8427 document from the beginning, understanding these parts of a function is
8428 almost becoming routine.
8429
8430 The documentation is somewhat confusing unless you remember that the
8431 word `kill' has a meaning different from usual. The `Transient Mark'
8432 and @code{interprogram-cut-function} comments explain certain
8433 side-effects.
8434
8435 After you once set a mark, a buffer always contains a region. If you
8436 wish, you can use Transient Mark mode to highlight the region
8437 temporarily. (No one wants to highlight the region all the time, so
8438 Transient Mark mode highlights it only at appropriate times. Many
8439 people turn off Transient Mark mode, so the region is never
8440 highlighted.)
8441
8442 Also, a windowing system allows you to copy, cut, and paste among
8443 different programs. In the X windowing system, for example, the
8444 @code{interprogram-cut-function} function is @code{x-select-text},
8445 which works with the windowing system's equivalent of the Emacs kill
8446 ring.
8447
8448 The body of the @code{copy-region-as-kill} function starts with an
8449 @code{if} clause. What this clause does is distinguish between two
8450 different situations: whether or not this command is executed
8451 immediately after a previous @code{kill-region} command. In the first
8452 case, the new region is appended to the previously copied text.
8453 Otherwise, it is inserted into the beginning of the kill ring as a
8454 separate piece of text from the previous piece.
8455
8456 The last two lines of the function prevent the region from lighting up
8457 if Transient Mark mode is turned on.
8458
8459 The body of @code{copy-region-as-kill} merits discussion in detail.
8460
8461 @node copy-region-as-kill body
8462 @subsection The Body of @code{copy-region-as-kill}
8463
8464 The @code{copy-region-as-kill} function works in much the same way as
8465 the @code{kill-region} function. Both are written so that two or more
8466 kills in a row combine their text into a single entry. If you yank
8467 back the text from the kill ring, you get it all in one piece.
8468 Moreover, kills that kill forward from the current position of the
8469 cursor are added to the end of the previously copied text and commands
8470 that copy text backwards add it to the beginning of the previously
8471 copied text. This way, the words in the text stay in the proper
8472 order.
8473
8474 Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8475 use of the @code{last-command} variable that keeps track of the
8476 previous Emacs command.
8477
8478 @menu
8479 * last-command & this-command::
8480 * kill-append function::
8481 * kill-new function::
8482 @end menu
8483
8484 @ifnottex
8485 @node last-command & this-command
8486 @unnumberedsubsubsec @code{last-command} and @code{this-command}
8487 @end ifnottex
8488
8489 Normally, whenever a function is executed, Emacs sets the value of
8490 @code{this-command} to the function being executed (which in this case
8491 would be @code{copy-region-as-kill}). At the same time, Emacs sets
8492 the value of @code{last-command} to the previous value of
8493 @code{this-command}.
8494
8495 In the first part of the body of the @code{copy-region-as-kill}
8496 function, an @code{if} expression determines whether the value of
8497 @code{last-command} is @code{kill-region}. If so, the then-part of
8498 the @code{if} expression is evaluated; it uses the @code{kill-append}
8499 function to concatenate the text copied at this call to the function
8500 with the text already in the first element (the @sc{car}) of the kill
8501 ring. On the other hand, if the value of @code{last-command} is not
8502 @code{kill-region}, then the @code{copy-region-as-kill} function
8503 attaches a new element to the kill ring using the @code{kill-new}
8504 function.
8505
8506 @need 1250
8507 The @code{if} expression reads as follows; it uses @code{eq}:
8508
8509 @smallexample
8510 @group
8511 (if (eq last-command 'kill-region)
8512 ;; @r{then-part}
8513 (kill-append (filter-buffer-substring beg end) (< end beg))
8514 ;; @r{else-part}
8515 (kill-new (filter-buffer-substring beg end)))
8516 @end group
8517 @end smallexample
8518
8519 @findex filter-buffer-substring
8520 (The @code{filter-buffer-substring} function returns a filtered
8521 substring of the buffer, if any. Optionally---the arguments are not
8522 here, so neither is done---the function may delete the initial text or
8523 return the text without its properties; this function is a replacement
8524 for the older @code{buffer-substring} function, which came before text
8525 properties were implemented.)
8526
8527 @findex eq @r{(example of use)}
8528 @noindent
8529 The @code{eq} function tests whether its first argument is the same Lisp
8530 object as its second argument. The @code{eq} function is similar to the
8531 @code{equal} function in that it is used to test for equality, but
8532 differs in that it determines whether two representations are actually
8533 the same object inside the computer, but with different names.
8534 @code{equal} determines whether the structure and contents of two
8535 expressions are the same.
8536
8537 If the previous command was @code{kill-region}, then the Emacs Lisp
8538 interpreter calls the @code{kill-append} function
8539
8540 @node kill-append function
8541 @unnumberedsubsubsec The @code{kill-append} function
8542 @findex kill-append
8543
8544 @need 800
8545 The @code{kill-append} function looks like this:
8546
8547 @c in GNU Emacs 22
8548 @smallexample
8549 @group
8550 (defun kill-append (string before-p &optional yank-handler)
8551 "Append STRING to the end of the latest kill in the kill ring.
8552 If BEFORE-P is non-nil, prepend STRING to the kill.
8553 @dots{} "
8554 (let* ((cur (car kill-ring)))
8555 (kill-new (if before-p (concat string cur) (concat cur string))
8556 (or (= (length cur) 0)
8557 (equal yank-handler
8558 (get-text-property 0 'yank-handler cur)))
8559 yank-handler)))
8560 @end group
8561 @end smallexample
8562
8563 @ignore
8564 was:
8565 (defun kill-append (string before-p)
8566 "Append STRING to the end of the latest kill in the kill ring.
8567 If BEFORE-P is non-nil, prepend STRING to the kill.
8568 If `interprogram-cut-function' is set, pass the resulting kill to
8569 it."
8570 (kill-new (if before-p
8571 (concat string (car kill-ring))
8572 (concat (car kill-ring) string))
8573 t))
8574 @end ignore
8575
8576 @noindent
8577 The @code{kill-append} function is fairly straightforward. It uses
8578 the @code{kill-new} function, which we will discuss in more detail in
8579 a moment.
8580
8581 (Also, the function provides an optional argument called
8582 @code{yank-handler}; when invoked, this argument tells the function
8583 how to deal with properties added to the text, such as `bold' or
8584 `italics'.)
8585
8586 @c !!! bug in GNU Emacs 22 version of kill-append ?
8587 It has a @code{let*} function to set the value of the first element of
8588 the kill ring to @code{cur}. (I do not know why the function does not
8589 use @code{let} instead; only one value is set in the expression.
8590 Perhaps this is a bug that produces no problems?)
8591
8592 Consider the conditional that is one of the two arguments to
8593 @code{kill-new}. It uses @code{concat} to concatenate the new text to
8594 the @sc{car} of the kill ring. Whether it prepends or appends the
8595 text depends on the results of an @code{if} expression:
8596
8597 @smallexample
8598 @group
8599 (if before-p ; @r{if-part}
8600 (concat string cur) ; @r{then-part}
8601 (concat cur string)) ; @r{else-part}
8602 @end group
8603 @end smallexample
8604
8605 @noindent
8606 If the region being killed is before the region that was killed in the
8607 last command, then it should be prepended before the material that was
8608 saved in the previous kill; and conversely, if the killed text follows
8609 what was just killed, it should be appended after the previous text.
8610 The @code{if} expression depends on the predicate @code{before-p} to
8611 decide whether the newly saved text should be put before or after the
8612 previously saved text.
8613
8614 The symbol @code{before-p} is the name of one of the arguments to
8615 @code{kill-append}. When the @code{kill-append} function is
8616 evaluated, it is bound to the value returned by evaluating the actual
8617 argument. In this case, this is the expression @code{(< end beg)}.
8618 This expression does not directly determine whether the killed text in
8619 this command is located before or after the kill text of the last
8620 command; what it does is determine whether the value of the variable
8621 @code{end} is less than the value of the variable @code{beg}. If it
8622 is, it means that the user is most likely heading towards the
8623 beginning of the buffer. Also, the result of evaluating the predicate
8624 expression, @code{(< end beg)}, will be true and the text will be
8625 prepended before the previous text. On the other hand, if the value of
8626 the variable @code{end} is greater than the value of the variable
8627 @code{beg}, the text will be appended after the previous text.
8628
8629 @need 800
8630 When the newly saved text will be prepended, then the string with the new
8631 text will be concatenated before the old text:
8632
8633 @smallexample
8634 (concat string cur)
8635 @end smallexample
8636
8637 @need 1200
8638 @noindent
8639 But if the text will be appended, it will be concatenated
8640 after the old text:
8641
8642 @smallexample
8643 (concat cur string))
8644 @end smallexample
8645
8646 To understand how this works, we first need to review the
8647 @code{concat} function. The @code{concat} function links together or
8648 unites two strings of text. The result is a string. For example:
8649
8650 @smallexample
8651 @group
8652 (concat "abc" "def")
8653 @result{} "abcdef"
8654 @end group
8655
8656 @group
8657 (concat "new "
8658 (car '("first element" "second element")))
8659 @result{} "new first element"
8660
8661 (concat (car
8662 '("first element" "second element")) " modified")
8663 @result{} "first element modified"
8664 @end group
8665 @end smallexample
8666
8667 We can now make sense of @code{kill-append}: it modifies the contents
8668 of the kill ring. The kill ring is a list, each element of which is
8669 saved text. The @code{kill-append} function uses the @code{kill-new}
8670 function which in turn uses the @code{setcar} function.
8671
8672 @node kill-new function
8673 @unnumberedsubsubsec The @code{kill-new} function
8674 @findex kill-new
8675
8676 @c in GNU Emacs 22, additional documentation to kill-new:
8677 @ignore
8678 Optional third arguments YANK-HANDLER controls how the STRING is later
8679 inserted into a buffer; see `insert-for-yank' for details.
8680 When a yank handler is specified, STRING must be non-empty (the yank
8681 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
8682
8683 When the yank handler has a non-nil PARAM element, the original STRING
8684 argument is not used by `insert-for-yank'. However, since Lisp code
8685 may access and use elements from the kill ring directly, the STRING
8686 argument should still be a \"useful\" string for such uses."
8687 @end ignore
8688 @need 1200
8689 The @code{kill-new} function looks like this:
8690
8691 @smallexample
8692 @group
8693 (defun kill-new (string &optional replace yank-handler)
8694 "Make STRING the latest kill in the kill ring.
8695 Set `kill-ring-yank-pointer' to point to it.
8696
8697 If `interprogram-cut-function' is non-nil, apply it to STRING.
8698 Optional second argument REPLACE non-nil means that STRING will replace
8699 the front of the kill ring, rather than being added to the list.
8700 @dots{}"
8701 @end group
8702 @group
8703 (if (> (length string) 0)
8704 (if yank-handler
8705 (put-text-property 0 (length string)
8706 'yank-handler yank-handler string))
8707 (if yank-handler
8708 (signal 'args-out-of-range
8709 (list string "yank-handler specified for empty string"))))
8710 @end group
8711 @group
8712 (if (fboundp 'menu-bar-update-yank-menu)
8713 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8714 @end group
8715 @group
8716 (if (and replace kill-ring)
8717 (setcar kill-ring string)
8718 (push string kill-ring)
8719 (if (> (length kill-ring) kill-ring-max)
8720 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8721 @end group
8722 @group
8723 (setq kill-ring-yank-pointer kill-ring)
8724 (if interprogram-cut-function
8725 (funcall interprogram-cut-function string (not replace))))
8726 @end group
8727 @end smallexample
8728 @ignore
8729 was:
8730 (defun kill-new (string &optional replace)
8731 "Make STRING the latest kill in the kill ring.
8732 Set the kill-ring-yank pointer to point to it.
8733 If `interprogram-cut-function' is non-nil, apply it to STRING.
8734 Optional second argument REPLACE non-nil means that STRING will replace
8735 the front of the kill ring, rather than being added to the list."
8736 (and (fboundp 'menu-bar-update-yank-menu)
8737 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8738 (if (and replace kill-ring)
8739 (setcar kill-ring string)
8740 (setq kill-ring (cons string kill-ring))
8741 (if (> (length kill-ring) kill-ring-max)
8742 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8743 (setq kill-ring-yank-pointer kill-ring)
8744 (if interprogram-cut-function
8745 (funcall interprogram-cut-function string (not replace))))
8746 @end ignore
8747
8748 (Notice that the function is not interactive.)
8749
8750 As usual, we can look at this function in parts.
8751
8752 The function definition has an optional @code{yank-handler} argument,
8753 which when invoked tells the function how to deal with properties
8754 added to the text, such as `bold' or `italics'. We will skip that.
8755
8756 @need 1200
8757 The first line of the documentation makes sense:
8758
8759 @smallexample
8760 Make STRING the latest kill in the kill ring.
8761 @end smallexample
8762
8763 @noindent
8764 Let's skip over the rest of the documentation for the moment.
8765
8766 @noindent
8767 Also, let's skip over the initial @code{if} expression and those lines
8768 of code involving @code{menu-bar-update-yank-menu}. We will explain
8769 them below.
8770
8771 @need 1200
8772 The critical lines are these:
8773
8774 @smallexample
8775 @group
8776 (if (and replace kill-ring)
8777 ;; @r{then}
8778 (setcar kill-ring string)
8779 @end group
8780 @group
8781 ;; @r{else}
8782 (push string kill-ring)
8783 @end group
8784 @group
8785 (setq kill-ring (cons string kill-ring))
8786 (if (> (length kill-ring) kill-ring-max)
8787 ;; @r{avoid overly long kill ring}
8788 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8789 @end group
8790 @group
8791 (setq kill-ring-yank-pointer kill-ring)
8792 (if interprogram-cut-function
8793 (funcall interprogram-cut-function string (not replace))))
8794 @end group
8795 @end smallexample
8796
8797 The conditional test is @w{@code{(and replace kill-ring)}}.
8798 This will be true when two conditions are met: the kill ring has
8799 something in it, and the @code{replace} variable is true.
8800
8801 @need 1250
8802 When the @code{kill-append} function sets @code{replace} to be true
8803 and when the kill ring has at least one item in it, the @code{setcar}
8804 expression is executed:
8805
8806 @smallexample
8807 (setcar kill-ring string)
8808 @end smallexample
8809
8810 The @code{setcar} function actually changes the first element of the
8811 @code{kill-ring} list to the value of @code{string}. It replaces the
8812 first element.
8813
8814 @need 1250
8815 On the other hand, if the kill ring is empty, or replace is false, the
8816 else-part of the condition is executed:
8817
8818 @smallexample
8819 (push string kill-ring)
8820 @end smallexample
8821
8822 @noindent
8823 @need 1250
8824 @code{push} puts its first argument onto the second. It is similar to
8825 the older
8826
8827 @smallexample
8828 (setq kill-ring (cons string kill-ring))
8829 @end smallexample
8830
8831 @noindent
8832 @need 1250
8833 or the newer
8834
8835 @smallexample
8836 (add-to-list kill-ring string)
8837 @end smallexample
8838
8839 @noindent
8840 When it is false, the expression first constructs a new version of the
8841 kill ring by prepending @code{string} to the existing kill ring as a
8842 new element (that is what the @code{push} does). Then it executes a
8843 second @code{if} clause. This second @code{if} clause keeps the kill
8844 ring from growing too long.
8845
8846 Let's look at these two expressions in order.
8847
8848 The @code{push} line of the else-part sets the new value of the kill
8849 ring to what results from adding the string being killed to the old
8850 kill ring.
8851
8852 We can see how this works with an example.
8853
8854 @need 800
8855 First,
8856
8857 @smallexample
8858 (setq example-list '("here is a clause" "another clause"))
8859 @end smallexample
8860
8861 @need 1200
8862 @noindent
8863 After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8864 @code{example-list} and see what it returns:
8865
8866 @smallexample
8867 @group
8868 example-list
8869 @result{} ("here is a clause" "another clause")
8870 @end group
8871 @end smallexample
8872
8873 @need 1200
8874 @noindent
8875 Now, we can add a new element on to this list by evaluating the
8876 following expression:
8877 @findex push, @r{example}
8878
8879 @smallexample
8880 (push "a third clause" example-list)
8881 @end smallexample
8882
8883 @need 800
8884 @noindent
8885 When we evaluate @code{example-list}, we find its value is:
8886
8887 @smallexample
8888 @group
8889 example-list
8890 @result{} ("a third clause" "here is a clause" "another clause")
8891 @end group
8892 @end smallexample
8893
8894 @noindent
8895 Thus, the third clause is added to the list by @code{push}.
8896
8897 @need 1200
8898 Now for the second part of the @code{if} clause. This expression
8899 keeps the kill ring from growing too long. It looks like this:
8900
8901 @smallexample
8902 @group
8903 (if (> (length kill-ring) kill-ring-max)
8904 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8905 @end group
8906 @end smallexample
8907
8908 The code checks whether the length of the kill ring is greater than
8909 the maximum permitted length. This is the value of
8910 @code{kill-ring-max} (which is 60, by default). If the length of the
8911 kill ring is too long, then this code sets the last element of the
8912 kill ring to @code{nil}. It does this by using two functions,
8913 @code{nthcdr} and @code{setcdr}.
8914
8915 We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8916 It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8917 @sc{car} of a list. In this case, however, @code{setcdr} will not be
8918 setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8919 function is used to cause it to set the @sc{cdr} of the next to last
8920 element of the kill ring---this means that since the @sc{cdr} of the
8921 next to last element is the last element of the kill ring, it will set
8922 the last element of the kill ring.
8923
8924 @findex nthcdr, @r{example}
8925 The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8926 list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8927 @dots{} It does this @var{N} times and returns the results.
8928 (@xref{nthcdr, , @code{nthcdr}}.)
8929
8930 @findex setcdr, @r{example}
8931 Thus, if we had a four element list that was supposed to be three
8932 elements long, we could set the @sc{cdr} of the next to last element
8933 to @code{nil}, and thereby shorten the list. (If you set the last
8934 element to some other value than @code{nil}, which you could do, then
8935 you would not have shortened the list. @xref{setcdr, ,
8936 @code{setcdr}}.)
8937
8938 You can see shortening by evaluating the following three expressions
8939 in turn. First set the value of @code{trees} to @code{(maple oak pine
8940 birch)}, then set the @sc{cdr} of its second @sc{cdr} to @code{nil}
8941 and then find the value of @code{trees}:
8942
8943 @smallexample
8944 @group
8945 (setq trees '(maple oak pine birch))
8946 @result{} (maple oak pine birch)
8947 @end group
8948
8949 @group
8950 (setcdr (nthcdr 2 trees) nil)
8951 @result{} nil
8952
8953 trees
8954 @result{} (maple oak pine)
8955 @end group
8956 @end smallexample
8957
8958 @noindent
8959 (The value returned by the @code{setcdr} expression is @code{nil} since
8960 that is what the @sc{cdr} is set to.)
8961
8962 To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8963 @sc{cdr} a number of times that is one less than the maximum permitted
8964 size of the kill ring and @code{setcdr} sets the @sc{cdr} of that
8965 element (which will be the rest of the elements in the kill ring) to
8966 @code{nil}. This prevents the kill ring from growing too long.
8967
8968 @need 800
8969 The next to last expression in the @code{kill-new} function is
8970
8971 @smallexample
8972 (setq kill-ring-yank-pointer kill-ring)
8973 @end smallexample
8974
8975 The @code{kill-ring-yank-pointer} is a global variable that is set to be
8976 the @code{kill-ring}.
8977
8978 Even though the @code{kill-ring-yank-pointer} is called a
8979 @samp{pointer}, it is a variable just like the kill ring. However, the
8980 name has been chosen to help humans understand how the variable is used.
8981
8982 @need 1200
8983 Now, to return to an early expression in the body of the function:
8984
8985 @smallexample
8986 @group
8987 (if (fboundp 'menu-bar-update-yank-menu)
8988 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8989 @end group
8990 @end smallexample
8991
8992 @noindent
8993 It starts with an @code{if} expression
8994
8995 In this case, the expression tests first to see whether
8996 @code{menu-bar-update-yank-menu} exists as a function, and if so,
8997 calls it. The @code{fboundp} function returns true if the symbol it
8998 is testing has a function definition that `is not void'. If the
8999 symbol's function definition were void, we would receive an error
9000 message, as we did when we created errors intentionally (@pxref{Making
9001 Errors, , Generate an Error Message}).
9002
9003 @noindent
9004 The then-part contains an expression whose first element is the
9005 function @code{and}.
9006
9007 @findex and
9008 The @code{and} special form evaluates each of its arguments until one
9009 of the arguments returns a value of @code{nil}, in which case the
9010 @code{and} expression returns @code{nil}; however, if none of the
9011 arguments returns a value of @code{nil}, the value resulting from
9012 evaluating the last argument is returned. (Since such a value is not
9013 @code{nil}, it is considered true in Emacs Lisp.) In other words, an
9014 @code{and} expression returns a true value only if all its arguments
9015 are true. (@xref{Second Buffer Related Review}.)
9016
9017 The expression determines whether the second argument to
9018 @code{menu-bar-update-yank-menu} is true or not.
9019 @ignore
9020 ;; If we're supposed to be extending an existing string, and that
9021 ;; string really is at the front of the menu, then update it in place.
9022 @end ignore
9023
9024 @code{menu-bar-update-yank-menu} is one of the functions that make it
9025 possible to use the `Select and Paste' menu in the Edit item of a menu
9026 bar; using a mouse, you can look at the various pieces of text you
9027 have saved and select one piece to paste.
9028
9029 The last expression in the @code{kill-new} function adds the newly
9030 copied string to whatever facility exists for copying and pasting
9031 among different programs running in a windowing system. In the X
9032 Windowing system, for example, the @code{x-select-text} function takes
9033 the string and stores it in memory operated by X@. You can paste the
9034 string in another program, such as an Xterm.
9035
9036 @need 1200
9037 The expression looks like this:
9038
9039 @smallexample
9040 @group
9041 (if interprogram-cut-function
9042 (funcall interprogram-cut-function string (not replace))))
9043 @end group
9044 @end smallexample
9045
9046 If an @code{interprogram-cut-function} exists, then Emacs executes
9047 @code{funcall}, which in turn calls its first argument as a function
9048 and passes the remaining arguments to it. (Incidentally, as far as I
9049 can see, this @code{if} expression could be replaced by an @code{and}
9050 expression similar to the one in the first part of the function.)
9051
9052 We are not going to discuss windowing systems and other programs
9053 further, but merely note that this is a mechanism that enables GNU
9054 Emacs to work easily and well with other programs.
9055
9056 This code for placing text in the kill ring, either concatenated with
9057 an existing element or as a new element, leads us to the code for
9058 bringing back text that has been cut out of the buffer---the yank
9059 commands. However, before discussing the yank commands, it is better
9060 to learn how lists are implemented in a computer. This will make
9061 clear such mysteries as the use of the term `pointer'. But before
9062 that, we will digress into C.
9063
9064 @ignore
9065 @c is this true in Emacs 22? Does not seems to be
9066
9067 (If the @w{@code{(< end beg))}}
9068 expression is true, @code{kill-append} prepends the string to the just
9069 previously clipped text. For a detailed discussion, see
9070 @ref{kill-append function, , The @code{kill-append} function}.)
9071
9072 If you then yank back the text, i.e., `paste' it, you get both
9073 pieces of text at once. That way, if you delete two words in a row,
9074 and then yank them back, you get both words, in their proper order,
9075 with one yank. (The @w{@code{(< end beg))}} expression makes sure the
9076 order is correct.)
9077
9078 On the other hand, if the previous command is not @code{kill-region},
9079 then the @code{kill-new} function is called, which adds the text to
9080 the kill ring as the latest item, and sets the
9081 @code{kill-ring-yank-pointer} variable to point to it.
9082 @end ignore
9083 @ignore
9084
9085 @c Evidently, changed for Emacs 22. The zap-to-char command does not
9086 @c use the delete-and-extract-region function
9087
9088 2006 Oct 26, the Digression into C is now OK but should come after
9089 copy-region-as-kill and filter-buffer-substring
9090
9091 2006 Oct 24
9092 In Emacs 22,
9093 copy-region-as-kill is short, 12 lines, and uses
9094 filter-buffer-substring, which is longer, 39 lines
9095 and has delete-and-extract-region in it.
9096 delete-and-extract-region is written in C.
9097
9098 see Initializing a Variable with @code{defvar}
9099 @end ignore
9100
9101 @node Digression into C
9102 @section Digression into C
9103 @findex delete-and-extract-region
9104 @cindex C, a digression into
9105 @cindex Digression into C
9106
9107 The @code{copy-region-as-kill} function (@pxref{copy-region-as-kill, ,
9108 @code{copy-region-as-kill}}) uses the @code{filter-buffer-substring}
9109 function, which in turn uses the @code{delete-and-extract-region}
9110 function. It removes the contents of a region and you cannot get them
9111 back.
9112
9113 Unlike the other code discussed here, the
9114 @code{delete-and-extract-region} function is not written in Emacs
9115 Lisp; it is written in C and is one of the primitives of the GNU Emacs
9116 system. Since it is very simple, I will digress briefly from Lisp and
9117 describe it here.
9118
9119 @c GNU Emacs 22 in /usr/local/src/emacs/src/editfns.c
9120 @c the DEFUN for buffer-substring-no-properties
9121
9122 @need 1500
9123 Like many of the other Emacs primitives,
9124 @code{delete-and-extract-region} is written as an instance of a C
9125 macro, a macro being a template for code. The complete macro looks
9126 like this:
9127
9128 @smallexample
9129 @group
9130 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
9131 Sbuffer_substring_no_properties, 2, 2, 0,
9132 doc: /* Return the characters of part of the buffer,
9133 without the text properties.
9134 The two arguments START and END are character positions;
9135 they can be in either order. */)
9136 (start, end)
9137 Lisp_Object start, end;
9138 @{
9139 register int b, e;
9140
9141 validate_region (&start, &end);
9142 b = XINT (start);
9143 e = XINT (end);
9144
9145 return make_buffer_string (b, e, 0);
9146 @}
9147 @end group
9148 @end smallexample
9149
9150 Without going into the details of the macro writing process, let me
9151 point out that this macro starts with the word @code{DEFUN}. The word
9152 @code{DEFUN} was chosen since the code serves the same purpose as
9153 @code{defun} does in Lisp. (The @code{DEFUN} C macro is defined in
9154 @file{emacs/src/lisp.h}.)
9155
9156 The word @code{DEFUN} is followed by seven parts inside of
9157 parentheses:
9158
9159 @itemize @bullet
9160 @item
9161 The first part is the name given to the function in Lisp,
9162 @code{delete-and-extract-region}.
9163
9164 @item
9165 The second part is the name of the function in C,
9166 @code{Fdelete_and_extract_region}. By convention, it starts with
9167 @samp{F}. Since C does not use hyphens in names, underscores are used
9168 instead.
9169
9170 @item
9171 The third part is the name for the C constant structure that records
9172 information on this function for internal use. It is the name of the
9173 function in C but begins with an @samp{S} instead of an @samp{F}.
9174
9175 @item
9176 The fourth and fifth parts specify the minimum and maximum number of
9177 arguments the function can have. This function demands exactly 2
9178 arguments.
9179
9180 @item
9181 The sixth part is nearly like the argument that follows the
9182 @code{interactive} declaration in a function written in Lisp: a letter
9183 followed, perhaps, by a prompt. The only difference from the Lisp is
9184 when the macro is called with no arguments. Then you write a @code{0}
9185 (which is a `null string'), as in this macro.
9186
9187 If you were to specify arguments, you would place them between
9188 quotation marks. The C macro for @code{goto-char} includes
9189 @code{"NGoto char: "} in this position to indicate that the function
9190 expects a raw prefix, in this case, a numerical location in a buffer,
9191 and provides a prompt.
9192
9193 @item
9194 The seventh part is a documentation string, just like the one for a
9195 function written in Emacs Lisp, except that every newline must be
9196 written explicitly as @samp{\n} followed by a backslash and carriage
9197 return.
9198
9199 @need 1000
9200 Thus, the first two lines of documentation for @code{goto-char} are
9201 written like this:
9202
9203 @smallexample
9204 @group
9205 "Set point to POSITION, a number or marker.\n\
9206 Beginning of buffer is position (point-min), end is (point-max)."
9207 @end group
9208 @end smallexample
9209 @end itemize
9210
9211 @need 1200
9212 In a C macro, the formal parameters come next, with a statement of
9213 what kind of object they are, followed by what might be called the `body'
9214 of the macro. For @code{delete-and-extract-region} the `body'
9215 consists of the following four lines:
9216
9217 @smallexample
9218 @group
9219 validate_region (&start, &end);
9220 if (XINT (start) == XINT (end))
9221 return build_string ("");
9222 return del_range_1 (XINT (start), XINT (end), 1, 1);
9223 @end group
9224 @end smallexample
9225
9226 The @code{validate_region} function checks whether the values
9227 passed as the beginning and end of the region are the proper type and
9228 are within range. If the beginning and end positions are the same,
9229 then return and empty string.
9230
9231 The @code{del_range_1} function actually deletes the text. It is a
9232 complex function we will not look into. It updates the buffer and
9233 does other things. However, it is worth looking at the two arguments
9234 passed to @code{del_range}. These are @w{@code{XINT (start)}} and
9235 @w{@code{XINT (end)}}.
9236
9237 As far as the C language is concerned, @code{start} and @code{end} are
9238 two integers that mark the beginning and end of the region to be
9239 deleted@footnote{More precisely, and requiring more expert knowledge
9240 to understand, the two integers are of type `Lisp_Object', which can
9241 also be a C union instead of an integer type.}.
9242
9243 In early versions of Emacs, these two numbers were thirty-two bits
9244 long, but the code is slowly being generalized to handle other
9245 lengths. Three of the available bits are used to specify the type of
9246 information; the remaining bits are used as `content'.
9247
9248 @samp{XINT} is a C macro that extracts the relevant number from the
9249 longer collection of bits; the three other bits are discarded.
9250
9251 @need 800
9252 The command in @code{delete-and-extract-region} looks like this:
9253
9254 @smallexample
9255 del_range_1 (XINT (start), XINT (end), 1, 1);
9256 @end smallexample
9257
9258 @noindent
9259 It deletes the region between the beginning position, @code{start},
9260 and the ending position, @code{end}.
9261
9262 From the point of view of the person writing Lisp, Emacs is all very
9263 simple; but hidden underneath is a great deal of complexity to make it
9264 all work.
9265
9266 @node defvar
9267 @section Initializing a Variable with @code{defvar}
9268 @findex defvar
9269 @cindex Initializing a variable
9270 @cindex Variable initialization
9271
9272 @ignore
9273 2006 Oct 24
9274 In Emacs 22,
9275 copy-region-as-kill is short, 12 lines, and uses
9276 filter-buffer-substring, which is longer, 39 lines
9277 and has delete-and-extract-region in it.
9278 delete-and-extract-region is written in C.
9279
9280 see Initializing a Variable with @code{defvar}
9281
9282 @end ignore
9283
9284 The @code{copy-region-as-kill} function is written in Emacs Lisp. Two
9285 functions within it, @code{kill-append} and @code{kill-new}, copy a
9286 region in a buffer and save it in a variable called the
9287 @code{kill-ring}. This section describes how the @code{kill-ring}
9288 variable is created and initialized using the @code{defvar} special
9289 form.
9290
9291 (Again we note that the term @code{kill-ring} is a misnomer. The text
9292 that is clipped out of the buffer can be brought back; it is not a ring
9293 of corpses, but a ring of resurrectable text.)
9294
9295 In Emacs Lisp, a variable such as the @code{kill-ring} is created and
9296 given an initial value by using the @code{defvar} special form. The
9297 name comes from ``define variable''.
9298
9299 The @code{defvar} special form is similar to @code{setq} in that it sets
9300 the value of a variable. It is unlike @code{setq} in two ways: first,
9301 it only sets the value of the variable if the variable does not already
9302 have a value. If the variable already has a value, @code{defvar} does
9303 not override the existing value. Second, @code{defvar} has a
9304 documentation string.
9305
9306 (Another special form, @code{defcustom}, is designed for variables
9307 that people customize. It has more features than @code{defvar}.
9308 (@xref{defcustom, , Setting Variables with @code{defcustom}}.)
9309
9310 @menu
9311 * See variable current value::
9312 * defvar and asterisk::
9313 @end menu
9314
9315 @ifnottex
9316 @node See variable current value
9317 @unnumberedsubsec Seeing the Current Value of a Variable
9318 @end ifnottex
9319
9320 You can see the current value of a variable, any variable, by using
9321 the @code{describe-variable} function, which is usually invoked by
9322 typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
9323 (followed by @key{RET}) when prompted, you will see what is in your
9324 current kill ring---this may be quite a lot! Conversely, if you have
9325 been doing nothing this Emacs session except read this document, you
9326 may have nothing in it. Also, you will see the documentation for
9327 @code{kill-ring}:
9328
9329 @smallexample
9330 @group
9331 Documentation:
9332 List of killed text sequences.
9333 Since the kill ring is supposed to interact nicely with cut-and-paste
9334 facilities offered by window systems, use of this variable should
9335 @end group
9336 @group
9337 interact nicely with `interprogram-cut-function' and
9338 `interprogram-paste-function'. The functions `kill-new',
9339 `kill-append', and `current-kill' are supposed to implement this
9340 interaction; you may want to use them instead of manipulating the kill
9341 ring directly.
9342 @end group
9343 @end smallexample
9344
9345 @need 800
9346 The kill ring is defined by a @code{defvar} in the following way:
9347
9348 @smallexample
9349 @group
9350 (defvar kill-ring nil
9351 "List of killed text sequences.
9352 @dots{}")
9353 @end group
9354 @end smallexample
9355
9356 @noindent
9357 In this variable definition, the variable is given an initial value of
9358 @code{nil}, which makes sense, since if you have saved nothing, you want
9359 nothing back if you give a @code{yank} command. The documentation
9360 string is written just like the documentation string of a @code{defun}.
9361 As with the documentation string of the @code{defun}, the first line of
9362 the documentation should be a complete sentence, since some commands,
9363 like @code{apropos}, print only the first line of documentation.
9364 Succeeding lines should not be indented; otherwise they look odd when
9365 you use @kbd{C-h v} (@code{describe-variable}).
9366
9367 @node defvar and asterisk
9368 @subsection @code{defvar} and an asterisk
9369 @findex defvar @r{for a user customizable variable}
9370 @findex defvar @r{with an asterisk}
9371
9372 In the past, Emacs used the @code{defvar} special form both for
9373 internal variables that you would not expect a user to change and for
9374 variables that you do expect a user to change. Although you can still
9375 use @code{defvar} for user customizable variables, please use
9376 @code{defcustom} instead, since that special form provides a path into
9377 the Customization commands. (@xref{defcustom, , Specifying Variables
9378 using @code{defcustom}}.)
9379
9380 When you specified a variable using the @code{defvar} special form,
9381 you could distinguish a variable that a user might want to change from
9382 others by typing an asterisk, @samp{*}, in the first column of its
9383 documentation string. For example:
9384
9385 @smallexample
9386 @group
9387 (defvar shell-command-default-error-buffer nil
9388 "*Buffer name for `shell-command' @dots{} error output.
9389 @dots{} ")
9390 @end group
9391 @end smallexample
9392
9393 @findex set-variable
9394 @noindent
9395 You could (and still can) use the @code{set-variable} command to
9396 change the value of @code{shell-command-default-error-buffer}
9397 temporarily. However, options set using @code{set-variable} are set
9398 only for the duration of your editing session. The new values are not
9399 saved between sessions. Each time Emacs starts, it reads the original
9400 value, unless you change the value within your @file{.emacs} file,
9401 either by setting it manually or by using @code{customize}.
9402 @xref{Emacs Initialization, , Your @file{.emacs} File}.
9403
9404 For me, the major use of the @code{set-variable} command is to suggest
9405 variables that I might want to set in my @file{.emacs} file. There
9406 are now more than 700 such variables, far too many to remember
9407 readily. Fortunately, you can press @key{TAB} after calling the
9408 @code{M-x set-variable} command to see the list of variables.
9409 (@xref{Examining, , Examining and Setting Variables, emacs,
9410 The GNU Emacs Manual}.)
9411
9412 @need 1250
9413 @node cons & search-fwd Review
9414 @section Review
9415
9416 Here is a brief summary of some recently introduced functions.
9417
9418 @table @code
9419 @item car
9420 @itemx cdr
9421 @code{car} returns the first element of a list; @code{cdr} returns the
9422 second and subsequent elements of a list.
9423
9424 @need 1250
9425 For example:
9426
9427 @smallexample
9428 @group
9429 (car '(1 2 3 4 5 6 7))
9430 @result{} 1
9431 (cdr '(1 2 3 4 5 6 7))
9432 @result{} (2 3 4 5 6 7)
9433 @end group
9434 @end smallexample
9435
9436 @item cons
9437 @code{cons} constructs a list by prepending its first argument to its
9438 second argument.
9439
9440 @need 1250
9441 For example:
9442
9443 @smallexample
9444 @group
9445 (cons 1 '(2 3 4))
9446 @result{} (1 2 3 4)
9447 @end group
9448 @end smallexample
9449
9450 @item funcall
9451 @code{funcall} evaluates its first argument as a function. It passes
9452 its remaining arguments to its first argument.
9453
9454 @item nthcdr
9455 Return the result of taking @sc{cdr} `n' times on a list.
9456 @iftex
9457 The
9458 @tex
9459 $n^{th}$
9460 @end tex
9461 @code{cdr}.
9462 @end iftex
9463 The `rest of the rest', as it were.
9464
9465 @need 1250
9466 For example:
9467
9468 @smallexample
9469 @group
9470 (nthcdr 3 '(1 2 3 4 5 6 7))
9471 @result{} (4 5 6 7)
9472 @end group
9473 @end smallexample
9474
9475 @item setcar
9476 @itemx setcdr
9477 @code{setcar} changes the first element of a list; @code{setcdr}
9478 changes the second and subsequent elements of a list.
9479
9480 @need 1250
9481 For example:
9482
9483 @smallexample
9484 @group
9485 (setq triple '(1 2 3))
9486
9487 (setcar triple '37)
9488
9489 triple
9490 @result{} (37 2 3)
9491
9492 (setcdr triple '("foo" "bar"))
9493
9494 triple
9495 @result{} (37 "foo" "bar")
9496 @end group
9497 @end smallexample
9498
9499 @item progn
9500 Evaluate each argument in sequence and then return the value of the
9501 last.
9502
9503 @need 1250
9504 For example:
9505
9506 @smallexample
9507 @group
9508 (progn 1 2 3 4)
9509 @result{} 4
9510 @end group
9511 @end smallexample
9512
9513 @item save-restriction
9514 Record whatever narrowing is in effect in the current buffer, if any,
9515 and restore that narrowing after evaluating the arguments.
9516
9517 @item search-forward
9518 Search for a string, and if the string is found, move point. With a
9519 regular expression, use the similar @code{re-search-forward}.
9520 (@xref{Regexp Search, , Regular Expression Searches}, for an
9521 explanation of regular expression patterns and searches.)
9522
9523 @need 1250
9524 @noindent
9525 @code{search-forward} and @code{re-search-forward} take four
9526 arguments:
9527
9528 @enumerate
9529 @item
9530 The string or regular expression to search for.
9531
9532 @item
9533 Optionally, the limit of the search.
9534
9535 @item
9536 Optionally, what to do if the search fails, return @code{nil} or an
9537 error message.
9538
9539 @item
9540 Optionally, how many times to repeat the search; if negative, the
9541 search goes backwards.
9542 @end enumerate
9543
9544 @item kill-region
9545 @itemx delete-and-extract-region
9546 @itemx copy-region-as-kill
9547
9548 @code{kill-region} cuts the text between point and mark from the
9549 buffer and stores that text in the kill ring, so you can get it back
9550 by yanking.
9551
9552 @code{copy-region-as-kill} copies the text between point and mark into
9553 the kill ring, from which you can get it by yanking. The function
9554 does not cut or remove the text from the buffer.
9555 @end table
9556
9557 @code{delete-and-extract-region} removes the text between point and
9558 mark from the buffer and throws it away. You cannot get it back.
9559 (This is not an interactive command.)
9560
9561 @need 1500
9562 @node search Exercises
9563 @section Searching Exercises
9564
9565 @itemize @bullet
9566 @item
9567 Write an interactive function that searches for a string. If the
9568 search finds the string, leave point after it and display a message
9569 that says ``Found!''. (Do not use @code{search-forward} for the name
9570 of this function; if you do, you will overwrite the existing version of
9571 @code{search-forward} that comes with Emacs. Use a name such as
9572 @code{test-search} instead.)
9573
9574 @item
9575 Write a function that prints the third element of the kill ring in the
9576 echo area, if any; if the kill ring does not contain a third element,
9577 print an appropriate message.
9578 @end itemize
9579
9580 @node List Implementation
9581 @chapter How Lists are Implemented
9582 @cindex Lists in a computer
9583
9584 In Lisp, atoms are recorded in a straightforward fashion; if the
9585 implementation is not straightforward in practice, it is, nonetheless,
9586 straightforward in theory. The atom @samp{rose}, for example, is
9587 recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
9588 @samp{e}. A list, on the other hand, is kept differently. The mechanism
9589 is equally simple, but it takes a moment to get used to the idea. A
9590 list is kept using a series of pairs of pointers. In the series, the
9591 first pointer in each pair points to an atom or to another list, and the
9592 second pointer in each pair points to the next pair, or to the symbol
9593 @code{nil}, which marks the end of the list.
9594
9595 A pointer itself is quite simply the electronic address of what is
9596 pointed to. Hence, a list is kept as a series of electronic addresses.
9597
9598 @menu
9599 * Lists diagrammed::
9600 * Symbols as Chest:: Exploring a powerful metaphor.
9601 * List Exercise::
9602 @end menu
9603
9604 @ifnottex
9605 @node Lists diagrammed
9606 @unnumberedsec Lists diagrammed
9607 @end ifnottex
9608
9609 For example, the list @code{(rose violet buttercup)} has three elements,
9610 @samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
9611 electronic address of @samp{rose} is recorded in a segment of computer
9612 memory along with the address that gives the electronic address of where
9613 the atom @samp{violet} is located; and that address (the one that tells
9614 where @samp{violet} is located) is kept along with an address that tells
9615 where the address for the atom @samp{buttercup} is located.
9616
9617 @need 1200
9618 This sounds more complicated than it is and is easier seen in a diagram:
9619
9620 @c clear print-postscript-figures
9621 @c !!! cons-cell-diagram #1
9622 @ifnottex
9623 @smallexample
9624 @group
9625 ___ ___ ___ ___ ___ ___
9626 |___|___|--> |___|___|--> |___|___|--> nil
9627 | | |
9628 | | |
9629 --> rose --> violet --> buttercup
9630 @end group
9631 @end smallexample
9632 @end ifnottex
9633 @ifset print-postscript-figures
9634 @sp 1
9635 @tex
9636 @center @image{cons-1}
9637 %%%% old method of including an image
9638 % \input /usr/local/lib/tex/inputs/psfig.tex
9639 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
9640 % \catcode`\@=0 %
9641 @end tex
9642 @sp 1
9643 @end ifset
9644 @ifclear print-postscript-figures
9645 @iftex
9646 @smallexample
9647 @group
9648 ___ ___ ___ ___ ___ ___
9649 |___|___|--> |___|___|--> |___|___|--> nil
9650 | | |
9651 | | |
9652 --> rose --> violet --> buttercup
9653 @end group
9654 @end smallexample
9655 @end iftex
9656 @end ifclear
9657
9658 @noindent
9659 In the diagram, each box represents a word of computer memory that
9660 holds a Lisp object, usually in the form of a memory address. The boxes,
9661 i.e., the addresses, are in pairs. Each arrow points to what the address
9662 is the address of, either an atom or another pair of addresses. The
9663 first box is the electronic address of @samp{rose} and the arrow points
9664 to @samp{rose}; the second box is the address of the next pair of boxes,
9665 the first part of which is the address of @samp{violet} and the second
9666 part of which is the address of the next pair. The very last box
9667 points to the symbol @code{nil}, which marks the end of the list.
9668
9669 @need 1200
9670 When a variable is set to a list with a function such as @code{setq},
9671 it stores the address of the first box in the variable. Thus,
9672 evaluation of the expression
9673
9674 @smallexample
9675 (setq bouquet '(rose violet buttercup))
9676 @end smallexample
9677
9678 @need 1250
9679 @noindent
9680 creates a situation like this:
9681
9682 @c cons-cell-diagram #2
9683 @ifnottex
9684 @smallexample
9685 @group
9686 bouquet
9687 |
9688 | ___ ___ ___ ___ ___ ___
9689 --> |___|___|--> |___|___|--> |___|___|--> nil
9690 | | |
9691 | | |
9692 --> rose --> violet --> buttercup
9693 @end group
9694 @end smallexample
9695 @end ifnottex
9696 @ifset print-postscript-figures
9697 @sp 1
9698 @tex
9699 @center @image{cons-2}
9700 %%%% old method of including an image
9701 % \input /usr/local/lib/tex/inputs/psfig.tex
9702 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
9703 % \catcode`\@=0 %
9704 @end tex
9705 @sp 1
9706 @end ifset
9707 @ifclear print-postscript-figures
9708 @iftex
9709 @smallexample
9710 @group
9711 bouquet
9712 |
9713 | ___ ___ ___ ___ ___ ___
9714 --> |___|___|--> |___|___|--> |___|___|--> nil
9715 | | |
9716 | | |
9717 --> rose --> violet --> buttercup
9718 @end group
9719 @end smallexample
9720 @end iftex
9721 @end ifclear
9722
9723 @noindent
9724 In this example, the symbol @code{bouquet} holds the address of the first
9725 pair of boxes.
9726
9727 @need 1200
9728 This same list can be illustrated in a different sort of box notation
9729 like this:
9730
9731 @c cons-cell-diagram #2a
9732 @ifnottex
9733 @smallexample
9734 @group
9735 bouquet
9736 |
9737 | -------------- --------------- ----------------
9738 | | car | cdr | | car | cdr | | car | cdr |
9739 -->| rose | o------->| violet | o------->| butter- | nil |
9740 | | | | | | | cup | |
9741 -------------- --------------- ----------------
9742 @end group
9743 @end smallexample
9744 @end ifnottex
9745 @ifset print-postscript-figures
9746 @sp 1
9747 @tex
9748 @center @image{cons-2a}
9749 %%%% old method of including an image
9750 % \input /usr/local/lib/tex/inputs/psfig.tex
9751 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9752 % \catcode`\@=0 %
9753 @end tex
9754 @sp 1
9755 @end ifset
9756 @ifclear print-postscript-figures
9757 @iftex
9758 @smallexample
9759 @group
9760 bouquet
9761 |
9762 | -------------- --------------- ----------------
9763 | | car | cdr | | car | cdr | | car | cdr |
9764 -->| rose | o------->| violet | o------->| butter- | nil |
9765 | | | | | | | cup | |
9766 -------------- --------------- ----------------
9767 @end group
9768 @end smallexample
9769 @end iftex
9770 @end ifclear
9771
9772 (Symbols consist of more than pairs of addresses, but the structure of
9773 a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9774 consists of a group of address-boxes, one of which is the address of
9775 the printed word @samp{bouquet}, a second of which is the address of a
9776 function definition attached to the symbol, if any, a third of which
9777 is the address of the first pair of address-boxes for the list
9778 @code{(rose violet buttercup)}, and so on. Here we are showing that
9779 the symbol's third address-box points to the first pair of
9780 address-boxes for the list.)
9781
9782 If a symbol is set to the @sc{cdr} of a list, the list itself is not
9783 changed; the symbol simply has an address further down the list. (In
9784 the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9785 evaluation of the following expression
9786
9787 @smallexample
9788 (setq flowers (cdr bouquet))
9789 @end smallexample
9790
9791 @need 800
9792 @noindent
9793 produces this:
9794
9795 @c cons-cell-diagram #3
9796 @ifnottex
9797 @sp 1
9798 @smallexample
9799 @group
9800 bouquet flowers
9801 | |
9802 | ___ ___ | ___ ___ ___ ___
9803 --> | | | --> | | | | | |
9804 |___|___|----> |___|___|--> |___|___|--> nil
9805 | | |
9806 | | |
9807 --> rose --> violet --> buttercup
9808 @end group
9809 @end smallexample
9810 @sp 1
9811 @end ifnottex
9812 @ifset print-postscript-figures
9813 @sp 1
9814 @tex
9815 @center @image{cons-3}
9816 %%%% old method of including an image
9817 % \input /usr/local/lib/tex/inputs/psfig.tex
9818 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9819 % \catcode`\@=0 %
9820 @end tex
9821 @sp 1
9822 @end ifset
9823 @ifclear print-postscript-figures
9824 @iftex
9825 @sp 1
9826 @smallexample
9827 @group
9828 bouquet flowers
9829 | |
9830 | ___ ___ | ___ ___ ___ ___
9831 --> | | | --> | | | | | |
9832 |___|___|----> |___|___|--> |___|___|--> nil
9833 | | |
9834 | | |
9835 --> rose --> violet --> buttercup
9836 @end group
9837 @end smallexample
9838 @sp 1
9839 @end iftex
9840 @end ifclear
9841
9842 @noindent
9843 The value of @code{flowers} is @code{(violet buttercup)}, which is
9844 to say, the symbol @code{flowers} holds the address of the pair of
9845 address-boxes, the first of which holds the address of @code{violet},
9846 and the second of which holds the address of @code{buttercup}.
9847
9848 A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9849 pair}. @xref{Cons Cell Type, , Cons Cell and List Types, elisp, The GNU Emacs Lisp
9850 Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9851 Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9852 information about cons cells and dotted pairs.
9853
9854 @need 1200
9855 The function @code{cons} adds a new pair of addresses to the front of
9856 a series of addresses like that shown above. For example, evaluating
9857 the expression
9858
9859 @smallexample
9860 (setq bouquet (cons 'lily bouquet))
9861 @end smallexample
9862
9863 @need 1500
9864 @noindent
9865 produces:
9866
9867 @c cons-cell-diagram #4
9868 @ifnottex
9869 @sp 1
9870 @smallexample
9871 @group
9872 bouquet flowers
9873 | |
9874 | ___ ___ ___ ___ | ___ ___ ___ ___
9875 --> | | | | | | --> | | | | | |
9876 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9877 | | | |
9878 | | | |
9879 --> lily --> rose --> violet --> buttercup
9880 @end group
9881 @end smallexample
9882 @sp 1
9883 @end ifnottex
9884 @ifset print-postscript-figures
9885 @sp 1
9886 @tex
9887 @center @image{cons-4}
9888 %%%% old method of including an image
9889 % \input /usr/local/lib/tex/inputs/psfig.tex
9890 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9891 % \catcode`\@=0 %
9892 @end tex
9893 @sp 1
9894 @end ifset
9895 @ifclear print-postscript-figures
9896 @iftex
9897 @sp 1
9898 @smallexample
9899 @group
9900 bouquet flowers
9901 | |
9902 | ___ ___ ___ ___ | ___ ___ ___ ___
9903 --> | | | | | | --> | | | | | |
9904 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9905 | | | |
9906 | | | |
9907 --> lily --> rose --> violet --> buttercup
9908 @end group
9909 @end smallexample
9910 @sp 1
9911 @end iftex
9912 @end ifclear
9913
9914 @need 1200
9915 @noindent
9916 However, this does not change the value of the symbol
9917 @code{flowers}, as you can see by evaluating the following,
9918
9919 @smallexample
9920 (eq (cdr (cdr bouquet)) flowers)
9921 @end smallexample
9922
9923 @noindent
9924 which returns @code{t} for true.
9925
9926 Until it is reset, @code{flowers} still has the value
9927 @code{(violet buttercup)}; that is, it has the address of the cons
9928 cell whose first address is of @code{violet}. Also, this does not
9929 alter any of the pre-existing cons cells; they are all still there.
9930
9931 Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9932 of the next cons cell in the series; to get the @sc{car} of a list,
9933 you get the address of the first element of the list; to @code{cons} a
9934 new element on a list, you add a new cons cell to the front of the list.
9935 That is all there is to it! The underlying structure of Lisp is
9936 brilliantly simple!
9937
9938 And what does the last address in a series of cons cells refer to? It
9939 is the address of the empty list, of @code{nil}.
9940
9941 In summary, when a Lisp variable is set to a value, it is provided with
9942 the address of the list to which the variable refers.
9943
9944 @node Symbols as Chest
9945 @section Symbols as a Chest of Drawers
9946 @cindex Symbols as a Chest of Drawers
9947 @cindex Chest of Drawers, metaphor for a symbol
9948 @cindex Drawers, Chest of, metaphor for a symbol
9949
9950 In an earlier section, I suggested that you might imagine a symbol as
9951 being a chest of drawers. The function definition is put in one
9952 drawer, the value in another, and so on. What is put in the drawer
9953 holding the value can be changed without affecting the contents of the
9954 drawer holding the function definition, and vice-verse.
9955
9956 Actually, what is put in each drawer is the address of the value or
9957 function definition. It is as if you found an old chest in the attic,
9958 and in one of its drawers you found a map giving you directions to
9959 where the buried treasure lies.
9960
9961 (In addition to its name, symbol definition, and variable value, a
9962 symbol has a `drawer' for a @dfn{property list} which can be used to
9963 record other information. Property lists are not discussed here; see
9964 @ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9965 Reference Manual}.)
9966
9967 @need 1500
9968 Here is a fanciful representation:
9969
9970 @c chest-of-drawers diagram
9971 @ifnottex
9972 @sp 1
9973 @smallexample
9974 @group
9975 Chest of Drawers Contents of Drawers
9976
9977 __ o0O0o __
9978 / \
9979 ---------------------
9980 | directions to | [map to]
9981 | symbol name | bouquet
9982 | |
9983 +---------------------+
9984 | directions to |
9985 | symbol definition | [none]
9986 | |
9987 +---------------------+
9988 | directions to | [map to]
9989 | variable value | (rose violet buttercup)
9990 | |
9991 +---------------------+
9992 | directions to |
9993 | property list | [not described here]
9994 | |
9995 +---------------------+
9996 |/ \|
9997 @end group
9998 @end smallexample
9999 @sp 1
10000 @end ifnottex
10001 @ifset print-postscript-figures
10002 @sp 1
10003 @tex
10004 @center @image{drawers}
10005 %%%% old method of including an image
10006 % \input /usr/local/lib/tex/inputs/psfig.tex
10007 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
10008 % \catcode`\@=0 %
10009 @end tex
10010 @sp 1
10011 @end ifset
10012 @ifclear print-postscript-figures
10013 @iftex
10014 @sp 1
10015 @smallexample
10016 @group
10017 Chest of Drawers Contents of Drawers
10018
10019 __ o0O0o __
10020 / \
10021 ---------------------
10022 | directions to | [map to]
10023 | symbol name | bouquet
10024 | |
10025 +---------------------+
10026 | directions to |
10027 | symbol definition | [none]
10028 | |
10029 +---------------------+
10030 | directions to | [map to]
10031 | variable value | (rose violet buttercup)
10032 | |
10033 +---------------------+
10034 | directions to |
10035 | property list | [not described here]
10036 | |
10037 +---------------------+
10038 |/ \|
10039 @end group
10040 @end smallexample
10041 @sp 1
10042 @end iftex
10043 @end ifclear
10044
10045 @node List Exercise
10046 @section Exercise
10047
10048 Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
10049 more flowers on to this list and set this new list to
10050 @code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
10051 What does the @code{more-flowers} list now contain?
10052
10053 @node Yanking
10054 @chapter Yanking Text Back
10055 @findex yank
10056 @cindex Text retrieval
10057 @cindex Retrieving text
10058 @cindex Pasting text
10059
10060 Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
10061 you can bring it back with a `yank' command. The text that is cut out of
10062 the buffer is put in the kill ring and the yank commands insert the
10063 appropriate contents of the kill ring back into a buffer (not necessarily
10064 the original buffer).
10065
10066 A simple @kbd{C-y} (@code{yank}) command inserts the first item from
10067 the kill ring into the current buffer. If the @kbd{C-y} command is
10068 followed immediately by @kbd{M-y}, the first element is replaced by
10069 the second element. Successive @kbd{M-y} commands replace the second
10070 element with the third, fourth, or fifth element, and so on. When the
10071 last element in the kill ring is reached, it is replaced by the first
10072 element and the cycle is repeated. (Thus the kill ring is called a
10073 `ring' rather than just a `list'. However, the actual data structure
10074 that holds the text is a list.
10075 @xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
10076 list is handled as a ring.)
10077
10078 @menu
10079 * Kill Ring Overview::
10080 * kill-ring-yank-pointer:: The kill ring is a list.
10081 * yank nthcdr Exercises:: The @code{kill-ring-yank-pointer} variable.
10082 @end menu
10083
10084 @node Kill Ring Overview
10085 @section Kill Ring Overview
10086 @cindex Kill ring overview
10087
10088 The kill ring is a list of textual strings. This is what it looks like:
10089
10090 @smallexample
10091 ("some text" "a different piece of text" "yet more text")
10092 @end smallexample
10093
10094 If this were the contents of my kill ring and I pressed @kbd{C-y}, the
10095 string of characters saying @samp{some text} would be inserted in this
10096 buffer where my cursor is located.
10097
10098 The @code{yank} command is also used for duplicating text by copying it.
10099 The copied text is not cut from the buffer, but a copy of it is put on the
10100 kill ring and is inserted by yanking it back.
10101
10102 Three functions are used for bringing text back from the kill ring:
10103 @code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
10104 which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
10105 which is used by the two other functions.
10106
10107 These functions refer to the kill ring through a variable called the
10108 @code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
10109 @code{yank} and @code{yank-pop} functions is:
10110
10111 @smallexample
10112 (insert (car kill-ring-yank-pointer))
10113 @end smallexample
10114
10115 @noindent
10116 (Well, no more. In GNU Emacs 22, the function has been replaced by
10117 @code{insert-for-yank} which calls @code{insert-for-yank-1}
10118 repetitively for each @code{yank-handler} segment. In turn,
10119 @code{insert-for-yank-1} strips text properties from the inserted text
10120 according to @code{yank-excluded-properties}. Otherwise, it is just
10121 like @code{insert}. We will stick with plain @code{insert} since it
10122 is easier to understand.)
10123
10124 To begin to understand how @code{yank} and @code{yank-pop} work, it is
10125 first necessary to look at the @code{kill-ring-yank-pointer} variable.
10126
10127 @node kill-ring-yank-pointer
10128 @section The @code{kill-ring-yank-pointer} Variable
10129
10130 @code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
10131 a variable. It points to something by being bound to the value of what
10132 it points to, like any other Lisp variable.
10133
10134 @need 1000
10135 Thus, if the value of the kill ring is:
10136
10137 @smallexample
10138 ("some text" "a different piece of text" "yet more text")
10139 @end smallexample
10140
10141 @need 1250
10142 @noindent
10143 and the @code{kill-ring-yank-pointer} points to the second clause, the
10144 value of @code{kill-ring-yank-pointer} is:
10145
10146 @smallexample
10147 ("a different piece of text" "yet more text")
10148 @end smallexample
10149
10150 As explained in the previous chapter (@pxref{List Implementation}), the
10151 computer does not keep two different copies of the text being pointed to
10152 by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
10153 words ``a different piece of text'' and ``yet more text'' are not
10154 duplicated. Instead, the two Lisp variables point to the same pieces of
10155 text. Here is a diagram:
10156
10157 @c cons-cell-diagram #5
10158 @ifnottex
10159 @smallexample
10160 @group
10161 kill-ring kill-ring-yank-pointer
10162 | |
10163 | ___ ___ | ___ ___ ___ ___
10164 ---> | | | --> | | | | | |
10165 |___|___|----> |___|___|--> |___|___|--> nil
10166 | | |
10167 | | |
10168 | | --> "yet more text"
10169 | |
10170 | --> "a different piece of text"
10171 |
10172 --> "some text"
10173 @end group
10174 @end smallexample
10175 @sp 1
10176 @end ifnottex
10177 @ifset print-postscript-figures
10178 @sp 1
10179 @tex
10180 @center @image{cons-5}
10181 %%%% old method of including an image
10182 % \input /usr/local/lib/tex/inputs/psfig.tex
10183 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
10184 % \catcode`\@=0 %
10185 @end tex
10186 @sp 1
10187 @end ifset
10188 @ifclear print-postscript-figures
10189 @iftex
10190 @smallexample
10191 @group
10192 kill-ring kill-ring-yank-pointer
10193 | |
10194 | ___ ___ | ___ ___ ___ ___
10195 ---> | | | --> | | | | | |
10196 |___|___|----> |___|___|--> |___|___|--> nil
10197 | | |
10198 | | |
10199 | | --> "yet more text"
10200 | |
10201 | --> "a different piece of text
10202 |
10203 --> "some text"
10204 @end group
10205 @end smallexample
10206 @sp 1
10207 @end iftex
10208 @end ifclear
10209
10210 Both the variable @code{kill-ring} and the variable
10211 @code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
10212 usually described as if it were actually what it is composed of. The
10213 @code{kill-ring} is spoken of as if it were the list rather than that it
10214 points to the list. Conversely, the @code{kill-ring-yank-pointer} is
10215 spoken of as pointing to a list.
10216
10217 These two ways of talking about the same thing sound confusing at first but
10218 make sense on reflection. The kill ring is generally thought of as the
10219 complete structure of data that holds the information of what has recently
10220 been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
10221 on the other hand, serves to indicate---that is, to `point to'---that part
10222 of the kill ring of which the first element (the @sc{car}) will be
10223 inserted.
10224
10225 @ignore
10226 In GNU Emacs 22, the @code{kill-new} function calls
10227
10228 @code{(setq kill-ring-yank-pointer kill-ring)}
10229
10230 (defun rotate-yank-pointer (arg)
10231 "Rotate the yanking point in the kill ring.
10232 With argument, rotate that many kills forward (or backward, if negative)."
10233 (interactive "p")
10234 (current-kill arg))
10235
10236 (defun current-kill (n &optional do-not-move)
10237 "Rotate the yanking point by N places, and then return that kill.
10238 If N is zero, `interprogram-paste-function' is set, and calling it
10239 returns a string, then that string is added to the front of the
10240 kill ring and returned as the latest kill.
10241 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
10242 yanking point; just return the Nth kill forward."
10243 (let ((interprogram-paste (and (= n 0)
10244 interprogram-paste-function
10245 (funcall interprogram-paste-function))))
10246 (if interprogram-paste
10247 (progn
10248 ;; Disable the interprogram cut function when we add the new
10249 ;; text to the kill ring, so Emacs doesn't try to own the
10250 ;; selection, with identical text.
10251 (let ((interprogram-cut-function nil))
10252 (kill-new interprogram-paste))
10253 interprogram-paste)
10254 (or kill-ring (error "Kill ring is empty"))
10255 (let ((ARGth-kill-element
10256 (nthcdr (mod (- n (length kill-ring-yank-pointer))
10257 (length kill-ring))
10258 kill-ring)))
10259 (or do-not-move
10260 (setq kill-ring-yank-pointer ARGth-kill-element))
10261 (car ARGth-kill-element)))))
10262
10263 @end ignore
10264
10265 @need 1500
10266 @node yank nthcdr Exercises
10267 @section Exercises with @code{yank} and @code{nthcdr}
10268
10269 @itemize @bullet
10270 @item
10271 Using @kbd{C-h v} (@code{describe-variable}), look at the value of
10272 your kill ring. Add several items to your kill ring; look at its
10273 value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
10274 around the kill ring. How many items were in your kill ring? Find
10275 the value of @code{kill-ring-max}. Was your kill ring full, or could
10276 you have kept more blocks of text within it?
10277
10278 @item
10279 Using @code{nthcdr} and @code{car}, construct a series of expressions
10280 to return the first, second, third, and fourth elements of a list.
10281 @end itemize
10282
10283 @node Loops & Recursion
10284 @chapter Loops and Recursion
10285 @cindex Loops and recursion
10286 @cindex Recursion and loops
10287 @cindex Repetition (loops)
10288
10289 Emacs Lisp has two primary ways to cause an expression, or a series of
10290 expressions, to be evaluated repeatedly: one uses a @code{while}
10291 loop, and the other uses @dfn{recursion}.
10292
10293 Repetition can be very valuable. For example, to move forward four
10294 sentences, you need only write a program that will move forward one
10295 sentence and then repeat the process four times. Since a computer does
10296 not get bored or tired, such repetitive action does not have the
10297 deleterious effects that excessive or the wrong kinds of repetition can
10298 have on humans.
10299
10300 People mostly write Emacs Lisp functions using @code{while} loops and
10301 their kin; but you can use recursion, which provides a very powerful
10302 way to think about and then to solve problems@footnote{You can write
10303 recursive functions to be frugal or wasteful of mental or computer
10304 resources; as it happens, methods that people find easy---that are
10305 frugal of `mental resources'---sometimes use considerable computer
10306 resources. Emacs was designed to run on machines that we now consider
10307 limited and its default settings are conservative. You may want to
10308 increase the values of @code{max-specpdl-size} and
10309 @code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
10310 15 and 30 times their default value.}.
10311
10312 @menu
10313 * while:: Causing a stretch of code to repeat.
10314 * dolist dotimes::
10315 * Recursion:: Causing a function to call itself.
10316 * Looping exercise::
10317 @end menu
10318
10319 @node while
10320 @section @code{while}
10321 @cindex Loops
10322 @findex while
10323
10324 The @code{while} special form tests whether the value returned by
10325 evaluating its first argument is true or false. This is similar to what
10326 the Lisp interpreter does with an @code{if}; what the interpreter does
10327 next, however, is different.
10328
10329 In a @code{while} expression, if the value returned by evaluating the
10330 first argument is false, the Lisp interpreter skips the rest of the
10331 expression (the @dfn{body} of the expression) and does not evaluate it.
10332 However, if the value is true, the Lisp interpreter evaluates the body
10333 of the expression and then again tests whether the first argument to
10334 @code{while} is true or false. If the value returned by evaluating the
10335 first argument is again true, the Lisp interpreter again evaluates the
10336 body of the expression.
10337
10338 @need 1200
10339 The template for a @code{while} expression looks like this:
10340
10341 @smallexample
10342 @group
10343 (while @var{true-or-false-test}
10344 @var{body}@dots{})
10345 @end group
10346 @end smallexample
10347
10348 @menu
10349 * Looping with while:: Repeat so long as test returns true.
10350 * Loop Example:: A @code{while} loop that uses a list.
10351 * print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
10352 * Incrementing Loop:: A loop with an incrementing counter.
10353 * Incrementing Loop Details::
10354 * Decrementing Loop:: A loop with a decrementing counter.
10355 @end menu
10356
10357 @ifnottex
10358 @node Looping with while
10359 @unnumberedsubsec Looping with @code{while}
10360 @end ifnottex
10361
10362 So long as the true-or-false-test of the @code{while} expression
10363 returns a true value when it is evaluated, the body is repeatedly
10364 evaluated. This process is called a loop since the Lisp interpreter
10365 repeats the same thing again and again, like an airplane doing a loop.
10366 When the result of evaluating the true-or-false-test is false, the
10367 Lisp interpreter does not evaluate the rest of the @code{while}
10368 expression and `exits the loop'.
10369
10370 Clearly, if the value returned by evaluating the first argument to
10371 @code{while} is always true, the body following will be evaluated
10372 again and again @dots{} and again @dots{} forever. Conversely, if the
10373 value returned is never true, the expressions in the body will never
10374 be evaluated. The craft of writing a @code{while} loop consists of
10375 choosing a mechanism such that the true-or-false-test returns true
10376 just the number of times that you want the subsequent expressions to
10377 be evaluated, and then have the test return false.
10378
10379 The value returned by evaluating a @code{while} is the value of the
10380 true-or-false-test. An interesting consequence of this is that a
10381 @code{while} loop that evaluates without error will return @code{nil}
10382 or false regardless of whether it has looped 1 or 100 times or none at
10383 all. A @code{while} expression that evaluates successfully never
10384 returns a true value! What this means is that @code{while} is always
10385 evaluated for its side effects, which is to say, the consequences of
10386 evaluating the expressions within the body of the @code{while} loop.
10387 This makes sense. It is not the mere act of looping that is desired,
10388 but the consequences of what happens when the expressions in the loop
10389 are repeatedly evaluated.
10390
10391 @node Loop Example
10392 @subsection A @code{while} Loop and a List
10393
10394 A common way to control a @code{while} loop is to test whether a list
10395 has any elements. If it does, the loop is repeated; but if it does not,
10396 the repetition is ended. Since this is an important technique, we will
10397 create a short example to illustrate it.
10398
10399 A simple way to test whether a list has elements is to evaluate the
10400 list: if it has no elements, it is an empty list and will return the
10401 empty list, @code{()}, which is a synonym for @code{nil} or false. On
10402 the other hand, a list with elements will return those elements when it
10403 is evaluated. Since Emacs Lisp considers as true any value that is not
10404 @code{nil}, a list that returns elements will test true in a
10405 @code{while} loop.
10406
10407 @need 1200
10408 For example, you can set the variable @code{empty-list} to @code{nil} by
10409 evaluating the following @code{setq} expression:
10410
10411 @smallexample
10412 (setq empty-list ())
10413 @end smallexample
10414
10415 @noindent
10416 After evaluating the @code{setq} expression, you can evaluate the
10417 variable @code{empty-list} in the usual way, by placing the cursor after
10418 the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
10419 echo area:
10420
10421 @smallexample
10422 empty-list
10423 @end smallexample
10424
10425 On the other hand, if you set a variable to be a list with elements, the
10426 list will appear when you evaluate the variable, as you can see by
10427 evaluating the following two expressions:
10428
10429 @smallexample
10430 @group
10431 (setq animals '(gazelle giraffe lion tiger))
10432
10433 animals
10434 @end group
10435 @end smallexample
10436
10437 Thus, to create a @code{while} loop that tests whether there are any
10438 items in the list @code{animals}, the first part of the loop will be
10439 written like this:
10440
10441 @smallexample
10442 @group
10443 (while animals
10444 @dots{}
10445 @end group
10446 @end smallexample
10447
10448 @noindent
10449 When the @code{while} tests its first argument, the variable
10450 @code{animals} is evaluated. It returns a list. So long as the list
10451 has elements, the @code{while} considers the results of the test to be
10452 true; but when the list is empty, it considers the results of the test
10453 to be false.
10454
10455 To prevent the @code{while} loop from running forever, some mechanism
10456 needs to be provided to empty the list eventually. An oft-used
10457 technique is to have one of the subsequent forms in the @code{while}
10458 expression set the value of the list to be the @sc{cdr} of the list.
10459 Each time the @code{cdr} function is evaluated, the list will be made
10460 shorter, until eventually only the empty list will be left. At this
10461 point, the test of the @code{while} loop will return false, and the
10462 arguments to the @code{while} will no longer be evaluated.
10463
10464 For example, the list of animals bound to the variable @code{animals}
10465 can be set to be the @sc{cdr} of the original list with the
10466 following expression:
10467
10468 @smallexample
10469 (setq animals (cdr animals))
10470 @end smallexample
10471
10472 @noindent
10473 If you have evaluated the previous expressions and then evaluate this
10474 expression, you will see @code{(giraffe lion tiger)} appear in the echo
10475 area. If you evaluate the expression again, @code{(lion tiger)} will
10476 appear in the echo area. If you evaluate it again and yet again,
10477 @code{(tiger)} appears and then the empty list, shown by @code{nil}.
10478
10479 A template for a @code{while} loop that uses the @code{cdr} function
10480 repeatedly to cause the true-or-false-test eventually to test false
10481 looks like this:
10482
10483 @smallexample
10484 @group
10485 (while @var{test-whether-list-is-empty}
10486 @var{body}@dots{}
10487 @var{set-list-to-cdr-of-list})
10488 @end group
10489 @end smallexample
10490
10491 This test and use of @code{cdr} can be put together in a function that
10492 goes through a list and prints each element of the list on a line of its
10493 own.
10494
10495 @node print-elements-of-list
10496 @subsection An Example: @code{print-elements-of-list}
10497 @findex print-elements-of-list
10498
10499 The @code{print-elements-of-list} function illustrates a @code{while}
10500 loop with a list.
10501
10502 @cindex @file{*scratch*} buffer
10503 The function requires several lines for its output. If you are
10504 reading this in a recent instance of GNU Emacs,
10505 @c GNU Emacs 21, GNU Emacs 22, or a later version,
10506 you can evaluate the following expression inside of Info, as usual.
10507
10508 If you are using an earlier version of Emacs, you need to copy the
10509 necessary expressions to your @file{*scratch*} buffer and evaluate
10510 them there. This is because the echo area had only one line in the
10511 earlier versions.
10512
10513 You can copy the expressions by marking the beginning of the region
10514 with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
10515 the end of the region and then copying the region using @kbd{M-w}
10516 (@code{kill-ring-save}, which calls @code{copy-region-as-kill} and
10517 then provides visual feedback). In the @file{*scratch*}
10518 buffer, you can yank the expressions back by typing @kbd{C-y}
10519 (@code{yank}).
10520
10521 After you have copied the expressions to the @file{*scratch*} buffer,
10522 evaluate each expression in turn. Be sure to evaluate the last
10523 expression, @code{(print-elements-of-list animals)}, by typing
10524 @kbd{C-u C-x C-e}, that is, by giving an argument to
10525 @code{eval-last-sexp}. This will cause the result of the evaluation
10526 to be printed in the @file{*scratch*} buffer instead of being printed
10527 in the echo area. (Otherwise you will see something like this in your
10528 echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
10529 each @samp{^J} stands for a `newline'.)
10530
10531 @need 1500
10532 In a recent instance of GNU Emacs, you can evaluate these expressions
10533 directly in the Info buffer, and the echo area will grow to show the
10534 results.
10535
10536 @smallexample
10537 @group
10538 (setq animals '(gazelle giraffe lion tiger))
10539
10540 (defun print-elements-of-list (list)
10541 "Print each element of LIST on a line of its own."
10542 (while list
10543 (print (car list))
10544 (setq list (cdr list))))
10545
10546 (print-elements-of-list animals)
10547 @end group
10548 @end smallexample
10549
10550 @need 1200
10551 @noindent
10552 When you evaluate the three expressions in sequence, you will see
10553 this:
10554
10555 @smallexample
10556 @group
10557 gazelle
10558
10559 giraffe
10560
10561 lion
10562
10563 tiger
10564 nil
10565 @end group
10566 @end smallexample
10567
10568 Each element of the list is printed on a line of its own (that is what
10569 the function @code{print} does) and then the value returned by the
10570 function is printed. Since the last expression in the function is the
10571 @code{while} loop, and since @code{while} loops always return
10572 @code{nil}, a @code{nil} is printed after the last element of the list.
10573
10574 @node Incrementing Loop
10575 @subsection A Loop with an Incrementing Counter
10576
10577 A loop is not useful unless it stops when it ought. Besides
10578 controlling a loop with a list, a common way of stopping a loop is to
10579 write the first argument as a test that returns false when the correct
10580 number of repetitions are complete. This means that the loop must
10581 have a counter---an expression that counts how many times the loop
10582 repeats itself.
10583
10584 @ifnottex
10585 @node Incrementing Loop Details
10586 @unnumberedsubsec Details of an Incrementing Loop
10587 @end ifnottex
10588
10589 The test for a loop with an incrementing counter can be an expression
10590 such as @code{(< count desired-number)} which returns @code{t} for
10591 true if the value of @code{count} is less than the
10592 @code{desired-number} of repetitions and @code{nil} for false if the
10593 value of @code{count} is equal to or is greater than the
10594 @code{desired-number}. The expression that increments the count can
10595 be a simple @code{setq} such as @code{(setq count (1+ count))}, where
10596 @code{1+} is a built-in function in Emacs Lisp that adds 1 to its
10597 argument. (The expression @w{@code{(1+ count)}} has the same result
10598 as @w{@code{(+ count 1)}}, but is easier for a human to read.)
10599
10600 @need 1250
10601 The template for a @code{while} loop controlled by an incrementing
10602 counter looks like this:
10603
10604 @smallexample
10605 @group
10606 @var{set-count-to-initial-value}
10607 (while (< count desired-number) ; @r{true-or-false-test}
10608 @var{body}@dots{}
10609 (setq count (1+ count))) ; @r{incrementer}
10610 @end group
10611 @end smallexample
10612
10613 @noindent
10614 Note that you need to set the initial value of @code{count}; usually it
10615 is set to 1.
10616
10617 @menu
10618 * Incrementing Example:: Counting pebbles in a triangle.
10619 * Inc Example parts:: The parts of the function definition.
10620 * Inc Example altogether:: Putting the function definition together.
10621 @end menu
10622
10623 @node Incrementing Example
10624 @unnumberedsubsubsec Example with incrementing counter
10625
10626 Suppose you are playing on the beach and decide to make a triangle of
10627 pebbles, putting one pebble in the first row, two in the second row,
10628 three in the third row and so on, like this:
10629
10630 @sp 1
10631 @c pebble diagram
10632 @ifnottex
10633 @smallexample
10634 @group
10635 *
10636 * *
10637 * * *
10638 * * * *
10639 @end group
10640 @end smallexample
10641 @end ifnottex
10642 @iftex
10643 @smallexample
10644 @group
10645 @bullet{}
10646 @bullet{} @bullet{}
10647 @bullet{} @bullet{} @bullet{}
10648 @bullet{} @bullet{} @bullet{} @bullet{}
10649 @end group
10650 @end smallexample
10651 @end iftex
10652 @sp 1
10653
10654 @noindent
10655 (About 2500 years ago, Pythagoras and others developed the beginnings of
10656 number theory by considering questions such as this.)
10657
10658 Suppose you want to know how many pebbles you will need to make a
10659 triangle with 7 rows?
10660
10661 Clearly, what you need to do is add up the numbers from 1 to 7. There
10662 are two ways to do this; start with the smallest number, one, and add up
10663 the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
10664 number and add the list going down: 7, 6, 5, 4 and so on. Because both
10665 mechanisms illustrate common ways of writing @code{while} loops, we will
10666 create two examples, one counting up and the other counting down. In
10667 this first example, we will start with 1 and add 2, 3, 4 and so on.
10668
10669 If you are just adding up a short list of numbers, the easiest way to do
10670 it is to add up all the numbers at once. However, if you do not know
10671 ahead of time how many numbers your list will have, or if you want to be
10672 prepared for a very long list, then you need to design your addition so
10673 that what you do is repeat a simple process many times instead of doing
10674 a more complex process once.
10675
10676 For example, instead of adding up all the pebbles all at once, what you
10677 can do is add the number of pebbles in the first row, 1, to the number
10678 in the second row, 2, and then add the total of those two rows to the
10679 third row, 3. Then you can add the number in the fourth row, 4, to the
10680 total of the first three rows; and so on.
10681
10682 The critical characteristic of the process is that each repetitive
10683 action is simple. In this case, at each step we add only two numbers,
10684 the number of pebbles in the row and the total already found. This
10685 process of adding two numbers is repeated again and again until the last
10686 row has been added to the total of all the preceding rows. In a more
10687 complex loop the repetitive action might not be so simple, but it will
10688 be simpler than doing everything all at once.
10689
10690 @node Inc Example parts
10691 @unnumberedsubsubsec The parts of the function definition
10692
10693 The preceding analysis gives us the bones of our function definition:
10694 first, we will need a variable that we can call @code{total} that will
10695 be the total number of pebbles. This will be the value returned by
10696 the function.
10697
10698 Second, we know that the function will require an argument: this
10699 argument will be the total number of rows in the triangle. It can be
10700 called @code{number-of-rows}.
10701
10702 Finally, we need a variable to use as a counter. We could call this
10703 variable @code{counter}, but a better name is @code{row-number}. That
10704 is because what the counter does in this function is count rows, and a
10705 program should be written to be as understandable as possible.
10706
10707 When the Lisp interpreter first starts evaluating the expressions in the
10708 function, the value of @code{total} should be set to zero, since we have
10709 not added anything to it. Then the function should add the number of
10710 pebbles in the first row to the total, and then add the number of
10711 pebbles in the second to the total, and then add the number of
10712 pebbles in the third row to the total, and so on, until there are no
10713 more rows left to add.
10714
10715 Both @code{total} and @code{row-number} are used only inside the
10716 function, so they can be declared as local variables with @code{let}
10717 and given initial values. Clearly, the initial value for @code{total}
10718 should be 0. The initial value of @code{row-number} should be 1,
10719 since we start with the first row. This means that the @code{let}
10720 statement will look like this:
10721
10722 @smallexample
10723 @group
10724 (let ((total 0)
10725 (row-number 1))
10726 @var{body}@dots{})
10727 @end group
10728 @end smallexample
10729
10730 After the internal variables are declared and bound to their initial
10731 values, we can begin the @code{while} loop. The expression that serves
10732 as the test should return a value of @code{t} for true so long as the
10733 @code{row-number} is less than or equal to the @code{number-of-rows}.
10734 (If the expression tests true only so long as the row number is less
10735 than the number of rows in the triangle, the last row will never be
10736 added to the total; hence the row number has to be either less than or
10737 equal to the number of rows.)
10738
10739 @need 1500
10740 @findex <= @r{(less than or equal)}
10741 Lisp provides the @code{<=} function that returns true if the value of
10742 its first argument is less than or equal to the value of its second
10743 argument and false otherwise. So the expression that the @code{while}
10744 will evaluate as its test should look like this:
10745
10746 @smallexample
10747 (<= row-number number-of-rows)
10748 @end smallexample
10749
10750 The total number of pebbles can be found by repeatedly adding the number
10751 of pebbles in a row to the total already found. Since the number of
10752 pebbles in the row is equal to the row number, the total can be found by
10753 adding the row number to the total. (Clearly, in a more complex
10754 situation, the number of pebbles in the row might be related to the row
10755 number in a more complicated way; if this were the case, the row number
10756 would be replaced by the appropriate expression.)
10757
10758 @smallexample
10759 (setq total (+ total row-number))
10760 @end smallexample
10761
10762 @noindent
10763 What this does is set the new value of @code{total} to be equal to the
10764 sum of adding the number of pebbles in the row to the previous total.
10765
10766 After setting the value of @code{total}, the conditions need to be
10767 established for the next repetition of the loop, if there is one. This
10768 is done by incrementing the value of the @code{row-number} variable,
10769 which serves as a counter. After the @code{row-number} variable has
10770 been incremented, the true-or-false-test at the beginning of the
10771 @code{while} loop tests whether its value is still less than or equal to
10772 the value of the @code{number-of-rows} and if it is, adds the new value
10773 of the @code{row-number} variable to the @code{total} of the previous
10774 repetition of the loop.
10775
10776 @need 1200
10777 The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10778 @code{row-number} variable can be incremented with this expression:
10779
10780 @smallexample
10781 (setq row-number (1+ row-number))
10782 @end smallexample
10783
10784 @node Inc Example altogether
10785 @unnumberedsubsubsec Putting the function definition together
10786
10787 We have created the parts for the function definition; now we need to
10788 put them together.
10789
10790 @need 800
10791 First, the contents of the @code{while} expression:
10792
10793 @smallexample
10794 @group
10795 (while (<= row-number number-of-rows) ; @r{true-or-false-test}
10796 (setq total (+ total row-number))
10797 (setq row-number (1+ row-number))) ; @r{incrementer}
10798 @end group
10799 @end smallexample
10800
10801 Along with the @code{let} expression varlist, this very nearly
10802 completes the body of the function definition. However, it requires
10803 one final element, the need for which is somewhat subtle.
10804
10805 The final touch is to place the variable @code{total} on a line by
10806 itself after the @code{while} expression. Otherwise, the value returned
10807 by the whole function is the value of the last expression that is
10808 evaluated in the body of the @code{let}, and this is the value
10809 returned by the @code{while}, which is always @code{nil}.
10810
10811 This may not be evident at first sight. It almost looks as if the
10812 incrementing expression is the last expression of the whole function.
10813 But that expression is part of the body of the @code{while}; it is the
10814 last element of the list that starts with the symbol @code{while}.
10815 Moreover, the whole of the @code{while} loop is a list within the body
10816 of the @code{let}.
10817
10818 @need 1250
10819 In outline, the function will look like this:
10820
10821 @smallexample
10822 @group
10823 (defun @var{name-of-function} (@var{argument-list})
10824 "@var{documentation}@dots{}"
10825 (let (@var{varlist})
10826 (while (@var{true-or-false-test})
10827 @var{body-of-while}@dots{} )
10828 @dots{} )) ; @r{Need final expression here.}
10829 @end group
10830 @end smallexample
10831
10832 The result of evaluating the @code{let} is what is going to be returned
10833 by the @code{defun} since the @code{let} is not embedded within any
10834 containing list, except for the @code{defun} as a whole. However, if
10835 the @code{while} is the last element of the @code{let} expression, the
10836 function will always return @code{nil}. This is not what we want!
10837 Instead, what we want is the value of the variable @code{total}. This
10838 is returned by simply placing the symbol as the last element of the list
10839 starting with @code{let}. It gets evaluated after the preceding
10840 elements of the list are evaluated, which means it gets evaluated after
10841 it has been assigned the correct value for the total.
10842
10843 It may be easier to see this by printing the list starting with
10844 @code{let} all on one line. This format makes it evident that the
10845 @var{varlist} and @code{while} expressions are the second and third
10846 elements of the list starting with @code{let}, and the @code{total} is
10847 the last element:
10848
10849 @smallexample
10850 @group
10851 (let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10852 @end group
10853 @end smallexample
10854
10855 @need 1200
10856 Putting everything together, the @code{triangle} function definition
10857 looks like this:
10858
10859 @smallexample
10860 @group
10861 (defun triangle (number-of-rows) ; @r{Version with}
10862 ; @r{ incrementing counter.}
10863 "Add up the number of pebbles in a triangle.
10864 The first row has one pebble, the second row two pebbles,
10865 the third row three pebbles, and so on.
10866 The argument is NUMBER-OF-ROWS."
10867 @end group
10868 @group
10869 (let ((total 0)
10870 (row-number 1))
10871 (while (<= row-number number-of-rows)
10872 (setq total (+ total row-number))
10873 (setq row-number (1+ row-number)))
10874 total))
10875 @end group
10876 @end smallexample
10877
10878 @need 1200
10879 After you have installed @code{triangle} by evaluating the function, you
10880 can try it out. Here are two examples:
10881
10882 @smallexample
10883 @group
10884 (triangle 4)
10885
10886 (triangle 7)
10887 @end group
10888 @end smallexample
10889
10890 @noindent
10891 The sum of the first four numbers is 10 and the sum of the first seven
10892 numbers is 28.
10893
10894 @node Decrementing Loop
10895 @subsection Loop with a Decrementing Counter
10896
10897 Another common way to write a @code{while} loop is to write the test
10898 so that it determines whether a counter is greater than zero. So long
10899 as the counter is greater than zero, the loop is repeated. But when
10900 the counter is equal to or less than zero, the loop is stopped. For
10901 this to work, the counter has to start out greater than zero and then
10902 be made smaller and smaller by a form that is evaluated
10903 repeatedly.
10904
10905 The test will be an expression such as @code{(> counter 0)} which
10906 returns @code{t} for true if the value of @code{counter} is greater
10907 than zero, and @code{nil} for false if the value of @code{counter} is
10908 equal to or less than zero. The expression that makes the number
10909 smaller and smaller can be a simple @code{setq} such as @code{(setq
10910 counter (1- counter))}, where @code{1-} is a built-in function in
10911 Emacs Lisp that subtracts 1 from its argument.
10912
10913 @need 1250
10914 The template for a decrementing @code{while} loop looks like this:
10915
10916 @smallexample
10917 @group
10918 (while (> counter 0) ; @r{true-or-false-test}
10919 @var{body}@dots{}
10920 (setq counter (1- counter))) ; @r{decrementer}
10921 @end group
10922 @end smallexample
10923
10924 @menu
10925 * Decrementing Example:: More pebbles on the beach.
10926 * Dec Example parts:: The parts of the function definition.
10927 * Dec Example altogether:: Putting the function definition together.
10928 @end menu
10929
10930 @node Decrementing Example
10931 @unnumberedsubsubsec Example with decrementing counter
10932
10933 To illustrate a loop with a decrementing counter, we will rewrite the
10934 @code{triangle} function so the counter decreases to zero.
10935
10936 This is the reverse of the earlier version of the function. In this
10937 case, to find out how many pebbles are needed to make a triangle with
10938 3 rows, add the number of pebbles in the third row, 3, to the number
10939 in the preceding row, 2, and then add the total of those two rows to
10940 the row that precedes them, which is 1.
10941
10942 Likewise, to find the number of pebbles in a triangle with 7 rows, add
10943 the number of pebbles in the seventh row, 7, to the number in the
10944 preceding row, which is 6, and then add the total of those two rows to
10945 the row that precedes them, which is 5, and so on. As in the previous
10946 example, each addition only involves adding two numbers, the total of
10947 the rows already added up and the number of pebbles in the row that is
10948 being added to the total. This process of adding two numbers is
10949 repeated again and again until there are no more pebbles to add.
10950
10951 We know how many pebbles to start with: the number of pebbles in the
10952 last row is equal to the number of rows. If the triangle has seven
10953 rows, the number of pebbles in the last row is 7. Likewise, we know how
10954 many pebbles are in the preceding row: it is one less than the number in
10955 the row.
10956
10957 @node Dec Example parts
10958 @unnumberedsubsubsec The parts of the function definition
10959
10960 We start with three variables: the total number of rows in the
10961 triangle; the number of pebbles in a row; and the total number of
10962 pebbles, which is what we want to calculate. These variables can be
10963 named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10964 @code{total}, respectively.
10965
10966 Both @code{total} and @code{number-of-pebbles-in-row} are used only
10967 inside the function and are declared with @code{let}. The initial
10968 value of @code{total} should, of course, be zero. However, the
10969 initial value of @code{number-of-pebbles-in-row} should be equal to
10970 the number of rows in the triangle, since the addition will start with
10971 the longest row.
10972
10973 @need 1250
10974 This means that the beginning of the @code{let} expression will look
10975 like this:
10976
10977 @smallexample
10978 @group
10979 (let ((total 0)
10980 (number-of-pebbles-in-row number-of-rows))
10981 @var{body}@dots{})
10982 @end group
10983 @end smallexample
10984
10985 The total number of pebbles can be found by repeatedly adding the number
10986 of pebbles in a row to the total already found, that is, by repeatedly
10987 evaluating the following expression:
10988
10989 @smallexample
10990 (setq total (+ total number-of-pebbles-in-row))
10991 @end smallexample
10992
10993 @noindent
10994 After the @code{number-of-pebbles-in-row} is added to the @code{total},
10995 the @code{number-of-pebbles-in-row} should be decremented by one, since
10996 the next time the loop repeats, the preceding row will be
10997 added to the total.
10998
10999 The number of pebbles in a preceding row is one less than the number of
11000 pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
11001 used to compute the number of pebbles in the preceding row. This can be
11002 done with the following expression:
11003
11004 @smallexample
11005 @group
11006 (setq number-of-pebbles-in-row
11007 (1- number-of-pebbles-in-row))
11008 @end group
11009 @end smallexample
11010
11011 Finally, we know that the @code{while} loop should stop making repeated
11012 additions when there are no pebbles in a row. So the test for
11013 the @code{while} loop is simply:
11014
11015 @smallexample
11016 (while (> number-of-pebbles-in-row 0)
11017 @end smallexample
11018
11019 @node Dec Example altogether
11020 @unnumberedsubsubsec Putting the function definition together
11021
11022 We can put these expressions together to create a function definition
11023 that works. However, on examination, we find that one of the local
11024 variables is unneeded!
11025
11026 @need 1250
11027 The function definition looks like this:
11028
11029 @smallexample
11030 @group
11031 ;;; @r{First subtractive version.}
11032 (defun triangle (number-of-rows)
11033 "Add up the number of pebbles in a triangle."
11034 (let ((total 0)
11035 (number-of-pebbles-in-row number-of-rows))
11036 (while (> number-of-pebbles-in-row 0)
11037 (setq total (+ total number-of-pebbles-in-row))
11038 (setq number-of-pebbles-in-row
11039 (1- number-of-pebbles-in-row)))
11040 total))
11041 @end group
11042 @end smallexample
11043
11044 As written, this function works.
11045
11046 However, we do not need @code{number-of-pebbles-in-row}.
11047
11048 @cindex Argument as local variable
11049 When the @code{triangle} function is evaluated, the symbol
11050 @code{number-of-rows} will be bound to a number, giving it an initial
11051 value. That number can be changed in the body of the function as if
11052 it were a local variable, without any fear that such a change will
11053 effect the value of the variable outside of the function. This is a
11054 very useful characteristic of Lisp; it means that the variable
11055 @code{number-of-rows} can be used anywhere in the function where
11056 @code{number-of-pebbles-in-row} is used.
11057
11058 @need 800
11059 Here is a second version of the function written a bit more cleanly:
11060
11061 @smallexample
11062 @group
11063 (defun triangle (number) ; @r{Second version.}
11064 "Return sum of numbers 1 through NUMBER inclusive."
11065 (let ((total 0))
11066 (while (> number 0)
11067 (setq total (+ total number))
11068 (setq number (1- number)))
11069 total))
11070 @end group
11071 @end smallexample
11072
11073 In brief, a properly written @code{while} loop will consist of three parts:
11074
11075 @enumerate
11076 @item
11077 A test that will return false after the loop has repeated itself the
11078 correct number of times.
11079
11080 @item
11081 An expression the evaluation of which will return the value desired
11082 after being repeatedly evaluated.
11083
11084 @item
11085 An expression to change the value passed to the true-or-false-test so
11086 that the test returns false after the loop has repeated itself the right
11087 number of times.
11088 @end enumerate
11089
11090 @node dolist dotimes
11091 @section Save your time: @code{dolist} and @code{dotimes}
11092
11093 In addition to @code{while}, both @code{dolist} and @code{dotimes}
11094 provide for looping. Sometimes these are quicker to write than the
11095 equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
11096 Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
11097
11098 @code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
11099 list': @code{dolist} automatically shortens the list each time it
11100 loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
11101 each shorter version of the list to the first of its arguments.
11102
11103 @code{dotimes} loops a specific number of times: you specify the number.
11104
11105 @menu
11106 * dolist::
11107 * dotimes::
11108 @end menu
11109
11110 @node dolist
11111 @unnumberedsubsec The @code{dolist} Macro
11112 @findex dolist
11113
11114 Suppose, for example, you want to reverse a list, so that
11115 ``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
11116
11117 @need 1250
11118 In practice, you would use the @code{reverse} function, like this:
11119
11120 @smallexample
11121 @group
11122 (setq animals '(gazelle giraffe lion tiger))
11123
11124 (reverse animals)
11125 @end group
11126 @end smallexample
11127
11128 @need 800
11129 @noindent
11130 Here is how you could reverse the list using a @code{while} loop:
11131
11132 @smallexample
11133 @group
11134 (setq animals '(gazelle giraffe lion tiger))
11135
11136 (defun reverse-list-with-while (list)
11137 "Using while, reverse the order of LIST."
11138 (let (value) ; make sure list starts empty
11139 (while list
11140 (setq value (cons (car list) value))
11141 (setq list (cdr list)))
11142 value))
11143
11144 (reverse-list-with-while animals)
11145 @end group
11146 @end smallexample
11147
11148 @need 800
11149 @noindent
11150 And here is how you could use the @code{dolist} macro:
11151
11152 @smallexample
11153 @group
11154 (setq animals '(gazelle giraffe lion tiger))
11155
11156 (defun reverse-list-with-dolist (list)
11157 "Using dolist, reverse the order of LIST."
11158 (let (value) ; make sure list starts empty
11159 (dolist (element list value)
11160 (setq value (cons element value)))))
11161
11162 (reverse-list-with-dolist animals)
11163 @end group
11164 @end smallexample
11165
11166 @need 1250
11167 @noindent
11168 In Info, you can place your cursor after the closing parenthesis of
11169 each expression and type @kbd{C-x C-e}; in each case, you should see
11170
11171 @smallexample
11172 (tiger lion giraffe gazelle)
11173 @end smallexample
11174
11175 @noindent
11176 in the echo area.
11177
11178 For this example, the existing @code{reverse} function is obviously best.
11179 The @code{while} loop is just like our first example (@pxref{Loop
11180 Example, , A @code{while} Loop and a List}). The @code{while} first
11181 checks whether the list has elements; if so, it constructs a new list
11182 by adding the first element of the list to the existing list (which in
11183 the first iteration of the loop is @code{nil}). Since the second
11184 element is prepended in front of the first element, and the third
11185 element is prepended in front of the second element, the list is reversed.
11186
11187 In the expression using a @code{while} loop,
11188 the @w{@code{(setq list (cdr list))}}
11189 expression shortens the list, so the @code{while} loop eventually
11190 stops. In addition, it provides the @code{cons} expression with a new
11191 first element by creating a new and shorter list at each repetition of
11192 the loop.
11193
11194 The @code{dolist} expression does very much the same as the
11195 @code{while} expression, except that the @code{dolist} macro does some
11196 of the work you have to do when writing a @code{while} expression.
11197
11198 Like a @code{while} loop, a @code{dolist} loops. What is different is
11199 that it automatically shortens the list each time it loops---it
11200 `@sc{cdr}s down the list' on its own---and it automatically binds
11201 the @sc{car} of each shorter version of the list to the first of its
11202 arguments.
11203
11204 In the example, the @sc{car} of each shorter version of the list is
11205 referred to using the symbol @samp{element}, the list itself is called
11206 @samp{list}, and the value returned is called @samp{value}. The
11207 remainder of the @code{dolist} expression is the body.
11208
11209 The @code{dolist} expression binds the @sc{car} of each shorter
11210 version of the list to @code{element} and then evaluates the body of
11211 the expression; and repeats the loop. The result is returned in
11212 @code{value}.
11213
11214 @node dotimes
11215 @unnumberedsubsec The @code{dotimes} Macro
11216 @findex dotimes
11217
11218 The @code{dotimes} macro is similar to @code{dolist}, except that it
11219 loops a specific number of times.
11220
11221 The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
11222 and so forth each time around the loop, and the value of the third
11223 argument is returned. You need to provide the value of the second
11224 argument, which is how many times the macro loops.
11225
11226 @need 1250
11227 For example, the following binds the numbers from 0 up to, but not
11228 including, the number 3 to the first argument, @var{number}, and then
11229 constructs a list of the three numbers. (The first number is 0, the
11230 second number is 1, and the third number is 2; this makes a total of
11231 three numbers in all, starting with zero as the first number.)
11232
11233 @smallexample
11234 @group
11235 (let (value) ; otherwise a value is a void variable
11236 (dotimes (number 3 value)
11237 (setq value (cons number value))))
11238
11239 @result{} (2 1 0)
11240 @end group
11241 @end smallexample
11242
11243 @noindent
11244 @code{dotimes} returns @code{value}, so the way to use
11245 @code{dotimes} is to operate on some expression @var{number} number of
11246 times and then return the result, either as a list or an atom.
11247
11248 @need 1250
11249 Here is an example of a @code{defun} that uses @code{dotimes} to add
11250 up the number of pebbles in a triangle.
11251
11252 @smallexample
11253 @group
11254 (defun triangle-using-dotimes (number-of-rows)
11255 "Using dotimes, add up the number of pebbles in a triangle."
11256 (let ((total 0)) ; otherwise a total is a void variable
11257 (dotimes (number number-of-rows total)
11258 (setq total (+ total (1+ number))))))
11259
11260 (triangle-using-dotimes 4)
11261 @end group
11262 @end smallexample
11263
11264 @node Recursion
11265 @section Recursion
11266 @cindex Recursion
11267
11268 A recursive function contains code that tells the Lisp interpreter to
11269 call a program that runs exactly like itself, but with slightly
11270 different arguments. The code runs exactly the same because it has
11271 the same name. However, even though the program has the same name, it
11272 is not the same entity. It is different. In the jargon, it is a
11273 different `instance'.
11274
11275 Eventually, if the program is written correctly, the `slightly
11276 different arguments' will become sufficiently different from the first
11277 arguments that the final instance will stop.
11278
11279 @menu
11280 * Building Robots:: Same model, different serial number ...
11281 * Recursive Definition Parts:: Walk until you stop ...
11282 * Recursion with list:: Using a list as the test whether to recurse.
11283 * Recursive triangle function::
11284 * Recursion with cond::
11285 * Recursive Patterns:: Often used templates.
11286 * No Deferment:: Don't store up work ...
11287 * No deferment solution::
11288 @end menu
11289
11290 @node Building Robots
11291 @subsection Building Robots: Extending the Metaphor
11292 @cindex Building robots
11293 @cindex Robots, building
11294
11295 It is sometimes helpful to think of a running program as a robot that
11296 does a job. In doing its job, a recursive function calls on a second
11297 robot to help it. The second robot is identical to the first in every
11298 way, except that the second robot helps the first and has been
11299 passed different arguments than the first.
11300
11301 In a recursive function, the second robot may call a third; and the
11302 third may call a fourth, and so on. Each of these is a different
11303 entity; but all are clones.
11304
11305 Since each robot has slightly different instructions---the arguments
11306 will differ from one robot to the next---the last robot should know
11307 when to stop.
11308
11309 Let's expand on the metaphor in which a computer program is a robot.
11310
11311 A function definition provides the blueprints for a robot. When you
11312 install a function definition, that is, when you evaluate a
11313 @code{defun} special form, you install the necessary equipment to
11314 build robots. It is as if you were in a factory, setting up an
11315 assembly line. Robots with the same name are built according to the
11316 same blueprints. So they have, as it were, the same `model number',
11317 but a different `serial number'.
11318
11319 We often say that a recursive function `calls itself'. What we mean
11320 is that the instructions in a recursive function cause the Lisp
11321 interpreter to run a different function that has the same name and
11322 does the same job as the first, but with different arguments.
11323
11324 It is important that the arguments differ from one instance to the
11325 next; otherwise, the process will never stop.
11326
11327 @node Recursive Definition Parts
11328 @subsection The Parts of a Recursive Definition
11329 @cindex Parts of a Recursive Definition
11330 @cindex Recursive Definition Parts
11331
11332 A recursive function typically contains a conditional expression which
11333 has three parts:
11334
11335 @enumerate
11336 @item
11337 A true-or-false-test that determines whether the function is called
11338 again, here called the @dfn{do-again-test}.
11339
11340 @item
11341 The name of the function. When this name is called, a new instance of
11342 the function---a new robot, as it were---is created and told what to do.
11343
11344 @item
11345 An expression that returns a different value each time the function is
11346 called, here called the @dfn{next-step-expression}. Consequently, the
11347 argument (or arguments) passed to the new instance of the function
11348 will be different from that passed to the previous instance. This
11349 causes the conditional expression, the @dfn{do-again-test}, to test
11350 false after the correct number of repetitions.
11351 @end enumerate
11352
11353 Recursive functions can be much simpler than any other kind of
11354 function. Indeed, when people first start to use them, they often look
11355 so mysteriously simple as to be incomprehensible. Like riding a
11356 bicycle, reading a recursive function definition takes a certain knack
11357 which is hard at first but then seems simple.
11358
11359 @need 1200
11360 There are several different common recursive patterns. A very simple
11361 pattern looks like this:
11362
11363 @smallexample
11364 @group
11365 (defun @var{name-of-recursive-function} (@var{argument-list})
11366 "@var{documentation}@dots{}"
11367 (if @var{do-again-test}
11368 @var{body}@dots{}
11369 (@var{name-of-recursive-function}
11370 @var{next-step-expression})))
11371 @end group
11372 @end smallexample
11373
11374 Each time a recursive function is evaluated, a new instance of it is
11375 created and told what to do. The arguments tell the instance what to do.
11376
11377 An argument is bound to the value of the next-step-expression. Each
11378 instance runs with a different value of the next-step-expression.
11379
11380 The value in the next-step-expression is used in the do-again-test.
11381
11382 The value returned by the next-step-expression is passed to the new
11383 instance of the function, which evaluates it (or some
11384 transmogrification of it) to determine whether to continue or stop.
11385 The next-step-expression is designed so that the do-again-test returns
11386 false when the function should no longer be repeated.
11387
11388 The do-again-test is sometimes called the @dfn{stop condition},
11389 since it stops the repetitions when it tests false.
11390
11391 @node Recursion with list
11392 @subsection Recursion with a List
11393
11394 The example of a @code{while} loop that printed the elements of a list
11395 of numbers can be written recursively. Here is the code, including
11396 an expression to set the value of the variable @code{animals} to a list.
11397
11398 If you are reading this in Info in Emacs, you can evaluate this
11399 expression directly in Info. Otherwise, you must copy the example
11400 to the @file{*scratch*} buffer and evaluate each expression there.
11401 Use @kbd{C-u C-x C-e} to evaluate the
11402 @code{(print-elements-recursively animals)} expression so that the
11403 results are printed in the buffer; otherwise the Lisp interpreter will
11404 try to squeeze the results into the one line of the echo area.
11405
11406 Also, place your cursor immediately after the last closing parenthesis
11407 of the @code{print-elements-recursively} function, before the comment.
11408 Otherwise, the Lisp interpreter will try to evaluate the comment.
11409
11410 @findex print-elements-recursively
11411 @smallexample
11412 @group
11413 (setq animals '(gazelle giraffe lion tiger))
11414
11415 (defun print-elements-recursively (list)
11416 "Print each element of LIST on a line of its own.
11417 Uses recursion."
11418 (when list ; @r{do-again-test}
11419 (print (car list)) ; @r{body}
11420 (print-elements-recursively ; @r{recursive call}
11421 (cdr list)))) ; @r{next-step-expression}
11422
11423 (print-elements-recursively animals)
11424 @end group
11425 @end smallexample
11426
11427 The @code{print-elements-recursively} function first tests whether
11428 there is any content in the list; if there is, the function prints the
11429 first element of the list, the @sc{car} of the list. Then the
11430 function `invokes itself', but gives itself as its argument, not the
11431 whole list, but the second and subsequent elements of the list, the
11432 @sc{cdr} of the list.
11433
11434 Put another way, if the list is not empty, the function invokes
11435 another instance of code that is similar to the initial code, but is a
11436 different thread of execution, with different arguments than the first
11437 instance.
11438
11439 Put in yet another way, if the list is not empty, the first robot
11440 assembles a second robot and tells it what to do; the second robot is
11441 a different individual from the first, but is the same model.
11442
11443 When the second evaluation occurs, the @code{when} expression is
11444 evaluated and if true, prints the first element of the list it
11445 receives as its argument (which is the second element of the original
11446 list). Then the function `calls itself' with the @sc{cdr} of the list
11447 it is invoked with, which (the second time around) is the @sc{cdr} of
11448 the @sc{cdr} of the original list.
11449
11450 Note that although we say that the function `calls itself', what we
11451 mean is that the Lisp interpreter assembles and instructs a new
11452 instance of the program. The new instance is a clone of the first,
11453 but is a separate individual.
11454
11455 Each time the function `invokes itself', it invokes itself on a
11456 shorter version of the original list. It creates a new instance that
11457 works on a shorter list.
11458
11459 Eventually, the function invokes itself on an empty list. It creates
11460 a new instance whose argument is @code{nil}. The conditional expression
11461 tests the value of @code{list}. Since the value of @code{list} is
11462 @code{nil}, the @code{when} expression tests false so the then-part is
11463 not evaluated. The function as a whole then returns @code{nil}.
11464
11465 @need 1200
11466 When you evaluate the expression @code{(print-elements-recursively
11467 animals)} in the @file{*scratch*} buffer, you see this result:
11468
11469 @smallexample
11470 @group
11471 gazelle
11472
11473 giraffe
11474
11475 lion
11476
11477 tiger
11478 nil
11479 @end group
11480 @end smallexample
11481
11482 @need 2000
11483 @node Recursive triangle function
11484 @subsection Recursion in Place of a Counter
11485 @findex triangle-recursively
11486
11487 @need 1200
11488 The @code{triangle} function described in a previous section can also
11489 be written recursively. It looks like this:
11490
11491 @smallexample
11492 @group
11493 (defun triangle-recursively (number)
11494 "Return the sum of the numbers 1 through NUMBER inclusive.
11495 Uses recursion."
11496 (if (= number 1) ; @r{do-again-test}
11497 1 ; @r{then-part}
11498 (+ number ; @r{else-part}
11499 (triangle-recursively ; @r{recursive call}
11500 (1- number))))) ; @r{next-step-expression}
11501
11502 (triangle-recursively 7)
11503 @end group
11504 @end smallexample
11505
11506 @noindent
11507 You can install this function by evaluating it and then try it by
11508 evaluating @code{(triangle-recursively 7)}. (Remember to put your
11509 cursor immediately after the last parenthesis of the function
11510 definition, before the comment.) The function evaluates to 28.
11511
11512 To understand how this function works, let's consider what happens in the
11513 various cases when the function is passed 1, 2, 3, or 4 as the value of
11514 its argument.
11515
11516 @menu
11517 * Recursive Example arg of 1 or 2::
11518 * Recursive Example arg of 3 or 4::
11519 @end menu
11520
11521 @ifnottex
11522 @node Recursive Example arg of 1 or 2
11523 @unnumberedsubsubsec An argument of 1 or 2
11524 @end ifnottex
11525
11526 First, what happens if the value of the argument is 1?
11527
11528 The function has an @code{if} expression after the documentation
11529 string. It tests whether the value of @code{number} is equal to 1; if
11530 so, Emacs evaluates the then-part of the @code{if} expression, which
11531 returns the number 1 as the value of the function. (A triangle with
11532 one row has one pebble in it.)
11533
11534 Suppose, however, that the value of the argument is 2. In this case,
11535 Emacs evaluates the else-part of the @code{if} expression.
11536
11537 @need 1200
11538 The else-part consists of an addition, the recursive call to
11539 @code{triangle-recursively} and a decrementing action; and it looks like
11540 this:
11541
11542 @smallexample
11543 (+ number (triangle-recursively (1- number)))
11544 @end smallexample
11545
11546 When Emacs evaluates this expression, the innermost expression is
11547 evaluated first; then the other parts in sequence. Here are the steps
11548 in detail:
11549
11550 @table @i
11551 @item Step 1 @w{ } Evaluate the innermost expression.
11552
11553 The innermost expression is @code{(1- number)} so Emacs decrements the
11554 value of @code{number} from 2 to 1.
11555
11556 @item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
11557
11558 The Lisp interpreter creates an individual instance of
11559 @code{triangle-recursively}. It does not matter that this function is
11560 contained within itself. Emacs passes the result Step 1 as the
11561 argument used by this instance of the @code{triangle-recursively}
11562 function
11563
11564 In this case, Emacs evaluates @code{triangle-recursively} with an
11565 argument of 1. This means that this evaluation of
11566 @code{triangle-recursively} returns 1.
11567
11568 @item Step 3 @w{ } Evaluate the value of @code{number}.
11569
11570 The variable @code{number} is the second element of the list that
11571 starts with @code{+}; its value is 2.
11572
11573 @item Step 4 @w{ } Evaluate the @code{+} expression.
11574
11575 The @code{+} expression receives two arguments, the first
11576 from the evaluation of @code{number} (Step 3) and the second from the
11577 evaluation of @code{triangle-recursively} (Step 2).
11578
11579 The result of the addition is the sum of 2 plus 1, and the number 3 is
11580 returned, which is correct. A triangle with two rows has three
11581 pebbles in it.
11582 @end table
11583
11584 @node Recursive Example arg of 3 or 4
11585 @unnumberedsubsubsec An argument of 3 or 4
11586
11587 Suppose that @code{triangle-recursively} is called with an argument of
11588 3.
11589
11590 @table @i
11591 @item Step 1 @w{ } Evaluate the do-again-test.
11592
11593 The @code{if} expression is evaluated first. This is the do-again
11594 test and returns false, so the else-part of the @code{if} expression
11595 is evaluated. (Note that in this example, the do-again-test causes
11596 the function to call itself when it tests false, not when it tests
11597 true.)
11598
11599 @item Step 2 @w{ } Evaluate the innermost expression of the else-part.
11600
11601 The innermost expression of the else-part is evaluated, which decrements
11602 3 to 2. This is the next-step-expression.
11603
11604 @item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
11605
11606 The number 2 is passed to the @code{triangle-recursively} function.
11607
11608 We already know what happens when Emacs evaluates @code{triangle-recursively} with
11609 an argument of 2. After going through the sequence of actions described
11610 earlier, it returns a value of 3. So that is what will happen here.
11611
11612 @item Step 4 @w{ } Evaluate the addition.
11613
11614 3 will be passed as an argument to the addition and will be added to the
11615 number with which the function was called, which is 3.
11616 @end table
11617
11618 @noindent
11619 The value returned by the function as a whole will be 6.
11620
11621 Now that we know what will happen when @code{triangle-recursively} is
11622 called with an argument of 3, it is evident what will happen if it is
11623 called with an argument of 4:
11624
11625 @quotation
11626 @need 800
11627 In the recursive call, the evaluation of
11628
11629 @smallexample
11630 (triangle-recursively (1- 4))
11631 @end smallexample
11632
11633 @need 800
11634 @noindent
11635 will return the value of evaluating
11636
11637 @smallexample
11638 (triangle-recursively 3)
11639 @end smallexample
11640
11641 @noindent
11642 which is 6 and this value will be added to 4 by the addition in the
11643 third line.
11644 @end quotation
11645
11646 @noindent
11647 The value returned by the function as a whole will be 10.
11648
11649 Each time @code{triangle-recursively} is evaluated, it evaluates a
11650 version of itself---a different instance of itself---with a smaller
11651 argument, until the argument is small enough so that it does not
11652 evaluate itself.
11653
11654 Note that this particular design for a recursive function
11655 requires that operations be deferred.
11656
11657 Before @code{(triangle-recursively 7)} can calculate its answer, it
11658 must call @code{(triangle-recursively 6)}; and before
11659 @code{(triangle-recursively 6)} can calculate its answer, it must call
11660 @code{(triangle-recursively 5)}; and so on. That is to say, the
11661 calculation that @code{(triangle-recursively 7)} makes must be
11662 deferred until @code{(triangle-recursively 6)} makes its calculation;
11663 and @code{(triangle-recursively 6)} must defer until
11664 @code{(triangle-recursively 5)} completes; and so on.
11665
11666 If each of these instances of @code{triangle-recursively} are thought
11667 of as different robots, the first robot must wait for the second to
11668 complete its job, which must wait until the third completes, and so
11669 on.
11670
11671 There is a way around this kind of waiting, which we will discuss in
11672 @ref{No Deferment, , Recursion without Deferments}.
11673
11674 @node Recursion with cond
11675 @subsection Recursion Example Using @code{cond}
11676 @findex cond
11677
11678 The version of @code{triangle-recursively} described earlier is written
11679 with the @code{if} special form. It can also be written using another
11680 special form called @code{cond}. The name of the special form
11681 @code{cond} is an abbreviation of the word @samp{conditional}.
11682
11683 Although the @code{cond} special form is not used as often in the
11684 Emacs Lisp sources as @code{if}, it is used often enough to justify
11685 explaining it.
11686
11687 @need 800
11688 The template for a @code{cond} expression looks like this:
11689
11690 @smallexample
11691 @group
11692 (cond
11693 @var{body}@dots{})
11694 @end group
11695 @end smallexample
11696
11697 @noindent
11698 where the @var{body} is a series of lists.
11699
11700 @need 800
11701 Written out more fully, the template looks like this:
11702
11703 @smallexample
11704 @group
11705 (cond
11706 (@var{first-true-or-false-test} @var{first-consequent})
11707 (@var{second-true-or-false-test} @var{second-consequent})
11708 (@var{third-true-or-false-test} @var{third-consequent})
11709 @dots{})
11710 @end group
11711 @end smallexample
11712
11713 When the Lisp interpreter evaluates the @code{cond} expression, it
11714 evaluates the first element (the @sc{car} or true-or-false-test) of
11715 the first expression in a series of expressions within the body of the
11716 @code{cond}.
11717
11718 If the true-or-false-test returns @code{nil} the rest of that
11719 expression, the consequent, is skipped and the true-or-false-test of the
11720 next expression is evaluated. When an expression is found whose
11721 true-or-false-test returns a value that is not @code{nil}, the
11722 consequent of that expression is evaluated. The consequent can be one
11723 or more expressions. If the consequent consists of more than one
11724 expression, the expressions are evaluated in sequence and the value of
11725 the last one is returned. If the expression does not have a consequent,
11726 the value of the true-or-false-test is returned.
11727
11728 If none of the true-or-false-tests test true, the @code{cond} expression
11729 returns @code{nil}.
11730
11731 @need 1250
11732 Written using @code{cond}, the @code{triangle} function looks like this:
11733
11734 @smallexample
11735 @group
11736 (defun triangle-using-cond (number)
11737 (cond ((<= number 0) 0)
11738 ((= number 1) 1)
11739 ((> number 1)
11740 (+ number (triangle-using-cond (1- number))))))
11741 @end group
11742 @end smallexample
11743
11744 @noindent
11745 In this example, the @code{cond} returns 0 if the number is less than or
11746 equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11747 number (triangle-using-cond (1- number)))} if the number is greater than
11748 1.
11749
11750 @node Recursive Patterns
11751 @subsection Recursive Patterns
11752 @cindex Recursive Patterns
11753
11754 Here are three common recursive patterns. Each involves a list.
11755 Recursion does not need to involve lists, but Lisp is designed for lists
11756 and this provides a sense of its primal capabilities.
11757
11758 @menu
11759 * Every::
11760 * Accumulate::
11761 * Keep::
11762 @end menu
11763
11764 @node Every
11765 @unnumberedsubsubsec Recursive Pattern: @emph{every}
11766 @cindex Every, type of recursive pattern
11767 @cindex Recursive pattern: every
11768
11769 In the @code{every} recursive pattern, an action is performed on every
11770 element of a list.
11771
11772 @need 1500
11773 The basic pattern is:
11774
11775 @itemize @bullet
11776 @item
11777 If a list be empty, return @code{nil}.
11778 @item
11779 Else, act on the beginning of the list (the @sc{car} of the list)
11780 @itemize @minus
11781 @item
11782 through a recursive call by the function on the rest (the
11783 @sc{cdr}) of the list,
11784 @item
11785 and, optionally, combine the acted-on element, using @code{cons},
11786 with the results of acting on the rest.
11787 @end itemize
11788 @end itemize
11789
11790 @need 1500
11791 Here is example:
11792
11793 @smallexample
11794 @group
11795 (defun square-each (numbers-list)
11796 "Square each of a NUMBERS LIST, recursively."
11797 (if (not numbers-list) ; do-again-test
11798 nil
11799 (cons
11800 (* (car numbers-list) (car numbers-list))
11801 (square-each (cdr numbers-list))))) ; next-step-expression
11802 @end group
11803
11804 @group
11805 (square-each '(1 2 3))
11806 @result{} (1 4 9)
11807 @end group
11808 @end smallexample
11809
11810 @need 1200
11811 @noindent
11812 If @code{numbers-list} is empty, do nothing. But if it has content,
11813 construct a list combining the square of the first number in the list
11814 with the result of the recursive call.
11815
11816 (The example follows the pattern exactly: @code{nil} is returned if
11817 the numbers' list is empty. In practice, you would write the
11818 conditional so it carries out the action when the numbers' list is not
11819 empty.)
11820
11821 The @code{print-elements-recursively} function (@pxref{Recursion with
11822 list, , Recursion with a List}) is another example of an @code{every}
11823 pattern, except in this case, rather than bring the results together
11824 using @code{cons}, we print each element of output.
11825
11826 @need 1250
11827 The @code{print-elements-recursively} function looks like this:
11828
11829 @smallexample
11830 @group
11831 (setq animals '(gazelle giraffe lion tiger))
11832 @end group
11833
11834 @group
11835 (defun print-elements-recursively (list)
11836 "Print each element of LIST on a line of its own.
11837 Uses recursion."
11838 (when list ; @r{do-again-test}
11839 (print (car list)) ; @r{body}
11840 (print-elements-recursively ; @r{recursive call}
11841 (cdr list)))) ; @r{next-step-expression}
11842
11843 (print-elements-recursively animals)
11844 @end group
11845 @end smallexample
11846
11847 @need 1500
11848 The pattern for @code{print-elements-recursively} is:
11849
11850 @itemize @bullet
11851 @item
11852 When the list is empty, do nothing.
11853 @item
11854 But when the list has at least one element,
11855 @itemize @minus
11856 @item
11857 act on the beginning of the list (the @sc{car} of the list),
11858 @item
11859 and make a recursive call on the rest (the @sc{cdr}) of the list.
11860 @end itemize
11861 @end itemize
11862
11863 @node Accumulate
11864 @unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11865 @cindex Accumulate, type of recursive pattern
11866 @cindex Recursive pattern: accumulate
11867
11868 Another recursive pattern is called the @code{accumulate} pattern. In
11869 the @code{accumulate} recursive pattern, an action is performed on
11870 every element of a list and the result of that action is accumulated
11871 with the results of performing the action on the other elements.
11872
11873 This is very like the `every' pattern using @code{cons}, except that
11874 @code{cons} is not used, but some other combiner.
11875
11876 @need 1500
11877 The pattern is:
11878
11879 @itemize @bullet
11880 @item
11881 If a list be empty, return zero or some other constant.
11882 @item
11883 Else, act on the beginning of the list (the @sc{car} of the list),
11884 @itemize @minus
11885 @item
11886 and combine that acted-on element, using @code{+} or
11887 some other combining function, with
11888 @item
11889 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11890 @end itemize
11891 @end itemize
11892
11893 @need 1500
11894 Here is an example:
11895
11896 @smallexample
11897 @group
11898 (defun add-elements (numbers-list)
11899 "Add the elements of NUMBERS-LIST together."
11900 (if (not numbers-list)
11901 0
11902 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11903 @end group
11904
11905 @group
11906 (add-elements '(1 2 3 4))
11907 @result{} 10
11908 @end group
11909 @end smallexample
11910
11911 @xref{Files List, , Making a List of Files}, for an example of the
11912 accumulate pattern.
11913
11914 @node Keep
11915 @unnumberedsubsubsec Recursive Pattern: @emph{keep}
11916 @cindex Keep, type of recursive pattern
11917 @cindex Recursive pattern: keep
11918
11919 A third recursive pattern is called the @code{keep} pattern.
11920 In the @code{keep} recursive pattern, each element of a list is tested;
11921 the element is acted on and the results are kept only if the element
11922 meets a criterion.
11923
11924 Again, this is very like the `every' pattern, except the element is
11925 skipped unless it meets a criterion.
11926
11927 @need 1500
11928 The pattern has three parts:
11929
11930 @itemize @bullet
11931 @item
11932 If a list be empty, return @code{nil}.
11933 @item
11934 Else, if the beginning of the list (the @sc{car} of the list) passes
11935 a test
11936 @itemize @minus
11937 @item
11938 act on that element and combine it, using @code{cons} with
11939 @item
11940 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11941 @end itemize
11942 @item
11943 Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11944 the test
11945 @itemize @minus
11946 @item
11947 skip on that element,
11948 @item
11949 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11950 @end itemize
11951 @end itemize
11952
11953 @need 1500
11954 Here is an example that uses @code{cond}:
11955
11956 @smallexample
11957 @group
11958 (defun keep-three-letter-words (word-list)
11959 "Keep three letter words in WORD-LIST."
11960 (cond
11961 ;; First do-again-test: stop-condition
11962 ((not word-list) nil)
11963
11964 ;; Second do-again-test: when to act
11965 ((eq 3 (length (symbol-name (car word-list))))
11966 ;; combine acted-on element with recursive call on shorter list
11967 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11968
11969 ;; Third do-again-test: when to skip element;
11970 ;; recursively call shorter list with next-step expression
11971 (t (keep-three-letter-words (cdr word-list)))))
11972 @end group
11973
11974 @group
11975 (keep-three-letter-words '(one two three four five six))
11976 @result{} (one two six)
11977 @end group
11978 @end smallexample
11979
11980 It goes without saying that you need not use @code{nil} as the test for
11981 when to stop; and you can, of course, combine these patterns.
11982
11983 @node No Deferment
11984 @subsection Recursion without Deferments
11985 @cindex Deferment in recursion
11986 @cindex Recursion without Deferments
11987
11988 Let's consider again what happens with the @code{triangle-recursively}
11989 function. We will find that the intermediate calculations are
11990 deferred until all can be done.
11991
11992 @need 800
11993 Here is the function definition:
11994
11995 @smallexample
11996 @group
11997 (defun triangle-recursively (number)
11998 "Return the sum of the numbers 1 through NUMBER inclusive.
11999 Uses recursion."
12000 (if (= number 1) ; @r{do-again-test}
12001 1 ; @r{then-part}
12002 (+ number ; @r{else-part}
12003 (triangle-recursively ; @r{recursive call}
12004 (1- number))))) ; @r{next-step-expression}
12005 @end group
12006 @end smallexample
12007
12008 What happens when we call this function with a argument of 7?
12009
12010 The first instance of the @code{triangle-recursively} function adds
12011 the number 7 to the value returned by a second instance of
12012 @code{triangle-recursively}, an instance that has been passed an
12013 argument of 6. That is to say, the first calculation is:
12014
12015 @smallexample
12016 (+ 7 (triangle-recursively 6))
12017 @end smallexample
12018
12019 @noindent
12020 The first instance of @code{triangle-recursively}---you may want to
12021 think of it as a little robot---cannot complete its job. It must hand
12022 off the calculation for @code{(triangle-recursively 6)} to a second
12023 instance of the program, to a second robot. This second individual is
12024 completely different from the first one; it is, in the jargon, a
12025 `different instantiation'. Or, put another way, it is a different
12026 robot. It is the same model as the first; it calculates triangle
12027 numbers recursively; but it has a different serial number.
12028
12029 And what does @code{(triangle-recursively 6)} return? It returns the
12030 number 6 added to the value returned by evaluating
12031 @code{triangle-recursively} with an argument of 5. Using the robot
12032 metaphor, it asks yet another robot to help it.
12033
12034 @need 800
12035 Now the total is:
12036
12037 @smallexample
12038 (+ 7 6 (triangle-recursively 5))
12039 @end smallexample
12040
12041 @need 800
12042 And what happens next?
12043
12044 @smallexample
12045 (+ 7 6 5 (triangle-recursively 4))
12046 @end smallexample
12047
12048 Each time @code{triangle-recursively} is called, except for the last
12049 time, it creates another instance of the program---another robot---and
12050 asks it to make a calculation.
12051
12052 @need 800
12053 Eventually, the full addition is set up and performed:
12054
12055 @smallexample
12056 (+ 7 6 5 4 3 2 1)
12057 @end smallexample
12058
12059 This design for the function defers the calculation of the first step
12060 until the second can be done, and defers that until the third can be
12061 done, and so on. Each deferment means the computer must remember what
12062 is being waited on. This is not a problem when there are only a few
12063 steps, as in this example. But it can be a problem when there are
12064 more steps.
12065
12066 @node No deferment solution
12067 @subsection No Deferment Solution
12068 @cindex No deferment solution
12069 @cindex Defermentless solution
12070 @cindex Solution without deferment
12071
12072 The solution to the problem of deferred operations is to write in a
12073 manner that does not defer operations@footnote{The phrase @dfn{tail
12074 recursive} is used to describe such a process, one that uses
12075 `constant space'.}. This requires
12076 writing to a different pattern, often one that involves writing two
12077 function definitions, an `initialization' function and a `helper'
12078 function.
12079
12080 The `initialization' function sets up the job; the `helper' function
12081 does the work.
12082
12083 @need 1200
12084 Here are the two function definitions for adding up numbers. They are
12085 so simple, I find them hard to understand.
12086
12087 @smallexample
12088 @group
12089 (defun triangle-initialization (number)
12090 "Return the sum of the numbers 1 through NUMBER inclusive.
12091 This is the `initialization' component of a two function
12092 duo that uses recursion."
12093 (triangle-recursive-helper 0 0 number))
12094 @end group
12095 @end smallexample
12096
12097 @smallexample
12098 @group
12099 (defun triangle-recursive-helper (sum counter number)
12100 "Return SUM, using COUNTER, through NUMBER inclusive.
12101 This is the `helper' component of a two function duo
12102 that uses recursion."
12103 (if (> counter number)
12104 sum
12105 (triangle-recursive-helper (+ sum counter) ; @r{sum}
12106 (1+ counter) ; @r{counter}
12107 number))) ; @r{number}
12108 @end group
12109 @end smallexample
12110
12111 @need 1250
12112 Install both function definitions by evaluating them, then call
12113 @code{triangle-initialization} with 2 rows:
12114
12115 @smallexample
12116 @group
12117 (triangle-initialization 2)
12118 @result{} 3
12119 @end group
12120 @end smallexample
12121
12122 The `initialization' function calls the first instance of the `helper'
12123 function with three arguments: zero, zero, and a number which is the
12124 number of rows in the triangle.
12125
12126 The first two arguments passed to the `helper' function are
12127 initialization values. These values are changed when
12128 @code{triangle-recursive-helper} invokes new instances.@footnote{The
12129 jargon is mildly confusing: @code{triangle-recursive-helper} uses a
12130 process that is iterative in a procedure that is recursive. The
12131 process is called iterative because the computer need only record the
12132 three values, @code{sum}, @code{counter}, and @code{number}; the
12133 procedure is recursive because the function `calls itself'. On the
12134 other hand, both the process and the procedure used by
12135 @code{triangle-recursively} are called recursive. The word
12136 `recursive' has different meanings in the two contexts.}
12137
12138 Let's see what happens when we have a triangle that has one row. (This
12139 triangle will have one pebble in it!)
12140
12141 @need 1200
12142 @code{triangle-initialization} will call its helper with
12143 the arguments @w{@code{0 0 1}}. That function will run the conditional
12144 test whether @code{(> counter number)}:
12145
12146 @smallexample
12147 (> 0 1)
12148 @end smallexample
12149
12150 @need 1200
12151 @noindent
12152 and find that the result is false, so it will invoke
12153 the else-part of the @code{if} clause:
12154
12155 @smallexample
12156 @group
12157 (triangle-recursive-helper
12158 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12159 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12160 number) ; @r{number stays the same}
12161 @end group
12162 @end smallexample
12163
12164 @need 800
12165 @noindent
12166 which will first compute:
12167
12168 @smallexample
12169 @group
12170 (triangle-recursive-helper (+ 0 0) ; @r{sum}
12171 (1+ 0) ; @r{counter}
12172 1) ; @r{number}
12173 @exdent which is:
12174
12175 (triangle-recursive-helper 0 1 1)
12176 @end group
12177 @end smallexample
12178
12179 Again, @code{(> counter number)} will be false, so again, the Lisp
12180 interpreter will evaluate @code{triangle-recursive-helper}, creating a
12181 new instance with new arguments.
12182
12183 @need 800
12184 This new instance will be;
12185
12186 @smallexample
12187 @group
12188 (triangle-recursive-helper
12189 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12190 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12191 number) ; @r{number stays the same}
12192
12193 @exdent which is:
12194
12195 (triangle-recursive-helper 1 2 1)
12196 @end group
12197 @end smallexample
12198
12199 In this case, the @code{(> counter number)} test will be true! So the
12200 instance will return the value of the sum, which will be 1, as
12201 expected.
12202
12203 Now, let's pass @code{triangle-initialization} an argument
12204 of 2, to find out how many pebbles there are in a triangle with two rows.
12205
12206 That function calls @code{(triangle-recursive-helper 0 0 2)}.
12207
12208 @need 800
12209 In stages, the instances called will be:
12210
12211 @smallexample
12212 @group
12213 @r{sum counter number}
12214 (triangle-recursive-helper 0 1 2)
12215
12216 (triangle-recursive-helper 1 2 2)
12217
12218 (triangle-recursive-helper 3 3 2)
12219 @end group
12220 @end smallexample
12221
12222 When the last instance is called, the @code{(> counter number)} test
12223 will be true, so the instance will return the value of @code{sum},
12224 which will be 3.
12225
12226 This kind of pattern helps when you are writing functions that can use
12227 many resources in a computer.
12228
12229 @need 1500
12230 @node Looping exercise
12231 @section Looping Exercise
12232
12233 @itemize @bullet
12234 @item
12235 Write a function similar to @code{triangle} in which each row has a
12236 value which is the square of the row number. Use a @code{while} loop.
12237
12238 @item
12239 Write a function similar to @code{triangle} that multiplies instead of
12240 adds the values.
12241
12242 @item
12243 Rewrite these two functions recursively. Rewrite these functions
12244 using @code{cond}.
12245
12246 @c comma in printed title causes problem in Info cross reference
12247 @item
12248 Write a function for Texinfo mode that creates an index entry at the
12249 beginning of a paragraph for every @samp{@@dfn} within the paragraph.
12250 (In a Texinfo file, @samp{@@dfn} marks a definition. This book is
12251 written in Texinfo.)
12252
12253 Many of the functions you will need are described in two of the
12254 previous chapters, @ref{Cutting & Storing Text, , Cutting and Storing
12255 Text}, and @ref{Yanking, , Yanking Text Back}. If you use
12256 @code{forward-paragraph} to put the index entry at the beginning of
12257 the paragraph, you will have to use @w{@kbd{C-h f}}
12258 (@code{describe-function}) to find out how to make the command go
12259 backwards.
12260
12261 For more information, see
12262 @ifinfo
12263 @ref{Indicating, , Indicating Definitions, texinfo}.
12264 @end ifinfo
12265 @ifhtml
12266 @ref{Indicating, , Indicating, texinfo, Texinfo Manual}, which goes to
12267 a Texinfo manual in the current directory. Or, if you are on the
12268 Internet, see
12269 @uref{http://www.gnu.org/software/texinfo/manual/texinfo/}
12270 @end ifhtml
12271 @iftex
12272 ``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
12273 Documentation Format}.
12274 @end iftex
12275 @end itemize
12276
12277 @node Regexp Search
12278 @chapter Regular Expression Searches
12279 @cindex Searches, illustrating
12280 @cindex Regular expression searches
12281 @cindex Patterns, searching for
12282 @cindex Motion by sentence and paragraph
12283 @cindex Sentences, movement by
12284 @cindex Paragraphs, movement by
12285
12286 Regular expression searches are used extensively in GNU Emacs. The
12287 two functions, @code{forward-sentence} and @code{forward-paragraph},
12288 illustrate these searches well. They use regular expressions to find
12289 where to move point. The phrase `regular expression' is often written
12290 as `regexp'.
12291
12292 Regular expression searches are described in @ref{Regexp Search, ,
12293 Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
12294 @ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
12295 Manual}. In writing this chapter, I am presuming that you have at
12296 least a mild acquaintance with them. The major point to remember is
12297 that regular expressions permit you to search for patterns as well as
12298 for literal strings of characters. For example, the code in
12299 @code{forward-sentence} searches for the pattern of possible
12300 characters that could mark the end of a sentence, and moves point to
12301 that spot.
12302
12303 Before looking at the code for the @code{forward-sentence} function, it
12304 is worth considering what the pattern that marks the end of a sentence
12305 must be. The pattern is discussed in the next section; following that
12306 is a description of the regular expression search function,
12307 @code{re-search-forward}. The @code{forward-sentence} function
12308 is described in the section following. Finally, the
12309 @code{forward-paragraph} function is described in the last section of
12310 this chapter. @code{forward-paragraph} is a complex function that
12311 introduces several new features.
12312
12313 @menu
12314 * sentence-end:: The regular expression for @code{sentence-end}.
12315 * re-search-forward:: Very similar to @code{search-forward}.
12316 * forward-sentence:: A straightforward example of regexp search.
12317 * forward-paragraph:: A somewhat complex example.
12318 * etags:: How to create your own @file{TAGS} table.
12319 * Regexp Review::
12320 * re-search Exercises::
12321 @end menu
12322
12323 @node sentence-end
12324 @section The Regular Expression for @code{sentence-end}
12325 @findex sentence-end
12326
12327 The symbol @code{sentence-end} is bound to the pattern that marks the
12328 end of a sentence. What should this regular expression be?
12329
12330 Clearly, a sentence may be ended by a period, a question mark, or an
12331 exclamation mark. Indeed, in English, only clauses that end with one
12332 of those three characters should be considered the end of a sentence.
12333 This means that the pattern should include the character set:
12334
12335 @smallexample
12336 [.?!]
12337 @end smallexample
12338
12339 However, we do not want @code{forward-sentence} merely to jump to a
12340 period, a question mark, or an exclamation mark, because such a character
12341 might be used in the middle of a sentence. A period, for example, is
12342 used after abbreviations. So other information is needed.
12343
12344 According to convention, you type two spaces after every sentence, but
12345 only one space after a period, a question mark, or an exclamation mark in
12346 the body of a sentence. So a period, a question mark, or an exclamation
12347 mark followed by two spaces is a good indicator of an end of sentence.
12348 However, in a file, the two spaces may instead be a tab or the end of a
12349 line. This means that the regular expression should include these three
12350 items as alternatives.
12351
12352 @need 800
12353 This group of alternatives will look like this:
12354
12355 @smallexample
12356 @group
12357 \\($\\| \\| \\)
12358 ^ ^^
12359 TAB SPC
12360 @end group
12361 @end smallexample
12362
12363 @noindent
12364 Here, @samp{$} indicates the end of the line, and I have pointed out
12365 where the tab and two spaces are inserted in the expression. Both are
12366 inserted by putting the actual characters into the expression.
12367
12368 Two backslashes, @samp{\\}, are required before the parentheses and
12369 vertical bars: the first backslash quotes the following backslash in
12370 Emacs; and the second indicates that the following character, the
12371 parenthesis or the vertical bar, is special.
12372
12373 @need 1000
12374 Also, a sentence may be followed by one or more carriage returns, like
12375 this:
12376
12377 @smallexample
12378 @group
12379 [
12380 ]*
12381 @end group
12382 @end smallexample
12383
12384 @noindent
12385 Like tabs and spaces, a carriage return is inserted into a regular
12386 expression by inserting it literally. The asterisk indicates that the
12387 @key{RET} is repeated zero or more times.
12388
12389 But a sentence end does not consist only of a period, a question mark or
12390 an exclamation mark followed by appropriate space: a closing quotation
12391 mark or a closing brace of some kind may precede the space. Indeed more
12392 than one such mark or brace may precede the space. These require a
12393 expression that looks like this:
12394
12395 @smallexample
12396 []\"')@}]*
12397 @end smallexample
12398
12399 In this expression, the first @samp{]} is the first character in the
12400 expression; the second character is @samp{"}, which is preceded by a
12401 @samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
12402 three characters are @samp{'}, @samp{)}, and @samp{@}}.
12403
12404 All this suggests what the regular expression pattern for matching the
12405 end of a sentence should be; and, indeed, if we evaluate
12406 @code{sentence-end} we find that it returns the following value:
12407
12408 @smallexample
12409 @group
12410 sentence-end
12411 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
12412 ]*"
12413 @end group
12414 @end smallexample
12415
12416 @noindent
12417 (Well, not in GNU Emacs 22; that is because of an effort to make the
12418 process simpler and to handle more glyphs and languages. When the
12419 value of @code{sentence-end} is @code{nil}, then use the value defined
12420 by the function @code{sentence-end}. (Here is a use of the difference
12421 between a value and a function in Emacs Lisp.) The function returns a
12422 value constructed from the variables @code{sentence-end-base},
12423 @code{sentence-end-double-space}, @code{sentence-end-without-period},
12424 and @code{sentence-end-without-space}. The critical variable is
12425 @code{sentence-end-base}; its global value is similar to the one
12426 described above but it also contains two additional quotation marks.
12427 These have differing degrees of curliness. The
12428 @code{sentence-end-without-period} variable, when true, tells Emacs
12429 that a sentence may end without a period, such as text in Thai.)
12430
12431 @ignore
12432 @noindent
12433 (Note that here the @key{TAB}, two spaces, and @key{RET} are shown
12434 literally in the pattern.)
12435
12436 This regular expression can be deciphered as follows:
12437
12438 @table @code
12439 @item [.?!]
12440 The first part of the pattern is the three characters, a period, a question
12441 mark and an exclamation mark, within square brackets. The pattern must
12442 begin with one or other of these characters.
12443
12444 @item []\"')@}]*
12445 The second part of the pattern is the group of closing braces and
12446 quotation marks, which can appear zero or more times. These may follow
12447 the period, question mark or exclamation mark. In a regular expression,
12448 the backslash, @samp{\}, followed by the double quotation mark,
12449 @samp{"}, indicates the class of string-quote characters. Usually, the
12450 double quotation mark is the only character in this class. The
12451 asterisk, @samp{*}, indicates that the items in the previous group (the
12452 group surrounded by square brackets, @samp{[]}) may be repeated zero or
12453 more times.
12454
12455 @item \\($\\| \\| \\)
12456 The third part of the pattern is one or other of: either the end of a
12457 line, or two blank spaces, or a tab. The double back-slashes are used
12458 to prevent Emacs from reading the parentheses and vertical bars as part
12459 of the search pattern; the parentheses are used to mark the group and
12460 the vertical bars are used to indicated that the patterns to either side
12461 of them are alternatives. The dollar sign is used to indicate the end
12462 of a line and both the two spaces and the tab are each inserted as is to
12463 indicate what they are.
12464
12465 @item [@key{RET}]*
12466 Finally, the last part of the pattern indicates that the end of the line
12467 or the whitespace following the period, question mark or exclamation
12468 mark may, but need not, be followed by one or more carriage returns. In
12469 the pattern, the carriage return is inserted as an actual carriage
12470 return between square brackets but here it is shown as @key{RET}.
12471 @end table
12472 @end ignore
12473
12474 @node re-search-forward
12475 @section The @code{re-search-forward} Function
12476 @findex re-search-forward
12477
12478 The @code{re-search-forward} function is very like the
12479 @code{search-forward} function. (@xref{search-forward, , The
12480 @code{search-forward} Function}.)
12481
12482 @code{re-search-forward} searches for a regular expression. If the
12483 search is successful, it leaves point immediately after the last
12484 character in the target. If the search is backwards, it leaves point
12485 just before the first character in the target. You may tell
12486 @code{re-search-forward} to return @code{t} for true. (Moving point
12487 is therefore a `side effect'.)
12488
12489 Like @code{search-forward}, the @code{re-search-forward} function takes
12490 four arguments:
12491
12492 @enumerate
12493 @item
12494 The first argument is the regular expression that the function searches
12495 for. The regular expression will be a string between quotation marks.
12496
12497 @item
12498 The optional second argument limits how far the function will search; it is a
12499 bound, which is specified as a position in the buffer.
12500
12501 @item
12502 The optional third argument specifies how the function responds to
12503 failure: @code{nil} as the third argument causes the function to
12504 signal an error (and print a message) when the search fails; any other
12505 value causes it to return @code{nil} if the search fails and @code{t}
12506 if the search succeeds.
12507
12508 @item
12509 The optional fourth argument is the repeat count. A negative repeat
12510 count causes @code{re-search-forward} to search backwards.
12511 @end enumerate
12512
12513 @need 800
12514 The template for @code{re-search-forward} looks like this:
12515
12516 @smallexample
12517 @group
12518 (re-search-forward "@var{regular-expression}"
12519 @var{limit-of-search}
12520 @var{what-to-do-if-search-fails}
12521 @var{repeat-count})
12522 @end group
12523 @end smallexample
12524
12525 The second, third, and fourth arguments are optional. However, if you
12526 want to pass a value to either or both of the last two arguments, you
12527 must also pass a value to all the preceding arguments. Otherwise, the
12528 Lisp interpreter will mistake which argument you are passing the value
12529 to.
12530
12531 @need 1200
12532 In the @code{forward-sentence} function, the regular expression will be
12533 the value of the variable @code{sentence-end}. In simple form, that is:
12534
12535 @smallexample
12536 @group
12537 "[.?!][]\"')@}]*\\($\\| \\| \\)[
12538 ]*"
12539 @end group
12540 @end smallexample
12541
12542 @noindent
12543 The limit of the search will be the end of the paragraph (since a
12544 sentence cannot go beyond a paragraph). If the search fails, the
12545 function will return @code{nil}; and the repeat count will be provided
12546 by the argument to the @code{forward-sentence} function.
12547
12548 @node forward-sentence
12549 @section @code{forward-sentence}
12550 @findex forward-sentence
12551
12552 The command to move the cursor forward a sentence is a straightforward
12553 illustration of how to use regular expression searches in Emacs Lisp.
12554 Indeed, the function looks longer and more complicated than it is; this
12555 is because the function is designed to go backwards as well as forwards;
12556 and, optionally, over more than one sentence. The function is usually
12557 bound to the key command @kbd{M-e}.
12558
12559 @menu
12560 * Complete forward-sentence::
12561 * fwd-sentence while loops:: Two @code{while} loops.
12562 * fwd-sentence re-search:: A regular expression search.
12563 @end menu
12564
12565 @ifnottex
12566 @node Complete forward-sentence
12567 @unnumberedsubsec Complete @code{forward-sentence} function definition
12568 @end ifnottex
12569
12570 @need 1250
12571 Here is the code for @code{forward-sentence}:
12572
12573 @c in GNU Emacs 22
12574 @smallexample
12575 @group
12576 (defun forward-sentence (&optional arg)
12577 "Move forward to next `sentence-end'. With argument, repeat.
12578 With negative argument, move backward repeatedly to `sentence-beginning'.
12579
12580 The variable `sentence-end' is a regular expression that matches ends of
12581 sentences. Also, every paragraph boundary terminates sentences as well."
12582 @end group
12583 @group
12584 (interactive "p")
12585 (or arg (setq arg 1))
12586 (let ((opoint (point))
12587 (sentence-end (sentence-end)))
12588 (while (< arg 0)
12589 (let ((pos (point))
12590 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12591 (if (and (re-search-backward sentence-end par-beg t)
12592 (or (< (match-end 0) pos)
12593 (re-search-backward sentence-end par-beg t)))
12594 (goto-char (match-end 0))
12595 (goto-char par-beg)))
12596 (setq arg (1+ arg)))
12597 @end group
12598 @group
12599 (while (> arg 0)
12600 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12601 (if (re-search-forward sentence-end par-end t)
12602 (skip-chars-backward " \t\n")
12603 (goto-char par-end)))
12604 (setq arg (1- arg)))
12605 (constrain-to-field nil opoint t)))
12606 @end group
12607 @end smallexample
12608
12609 @ignore
12610 GNU Emacs 21
12611 @smallexample
12612 @group
12613 (defun forward-sentence (&optional arg)
12614 "Move forward to next sentence-end. With argument, repeat.
12615 With negative argument, move backward repeatedly to sentence-beginning.
12616 Sentence ends are identified by the value of sentence-end
12617 treated as a regular expression. Also, every paragraph boundary
12618 terminates sentences as well."
12619 @end group
12620 @group
12621 (interactive "p")
12622 (or arg (setq arg 1))
12623 (while (< arg 0)
12624 (let ((par-beg
12625 (save-excursion (start-of-paragraph-text) (point))))
12626 (if (re-search-backward
12627 (concat sentence-end "[^ \t\n]") par-beg t)
12628 (goto-char (1- (match-end 0)))
12629 (goto-char par-beg)))
12630 (setq arg (1+ arg)))
12631 (while (> arg 0)
12632 (let ((par-end
12633 (save-excursion (end-of-paragraph-text) (point))))
12634 (if (re-search-forward sentence-end par-end t)
12635 (skip-chars-backward " \t\n")
12636 (goto-char par-end)))
12637 (setq arg (1- arg))))
12638 @end group
12639 @end smallexample
12640 @end ignore
12641
12642 The function looks long at first sight and it is best to look at its
12643 skeleton first, and then its muscle. The way to see the skeleton is to
12644 look at the expressions that start in the left-most columns:
12645
12646 @smallexample
12647 @group
12648 (defun forward-sentence (&optional arg)
12649 "@var{documentation}@dots{}"
12650 (interactive "p")
12651 (or arg (setq arg 1))
12652 (let ((opoint (point)) (sentence-end (sentence-end)))
12653 (while (< arg 0)
12654 (let ((pos (point))
12655 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12656 @var{rest-of-body-of-while-loop-when-going-backwards}
12657 (while (> arg 0)
12658 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12659 @var{rest-of-body-of-while-loop-when-going-forwards}
12660 @var{handle-forms-and-equivalent}
12661 @end group
12662 @end smallexample
12663
12664 This looks much simpler! The function definition consists of
12665 documentation, an @code{interactive} expression, an @code{or}
12666 expression, a @code{let} expression, and @code{while} loops.
12667
12668 Let's look at each of these parts in turn.
12669
12670 We note that the documentation is thorough and understandable.
12671
12672 The function has an @code{interactive "p"} declaration. This means
12673 that the processed prefix argument, if any, is passed to the
12674 function as its argument. (This will be a number.) If the function
12675 is not passed an argument (it is optional) then the argument
12676 @code{arg} will be bound to 1.
12677
12678 When @code{forward-sentence} is called non-interactively without an
12679 argument, @code{arg} is bound to @code{nil}. The @code{or} expression
12680 handles this. What it does is either leave the value of @code{arg} as
12681 it is, but only if @code{arg} is bound to a value; or it sets the
12682 value of @code{arg} to 1, in the case when @code{arg} is bound to
12683 @code{nil}.
12684
12685 Next is a @code{let}. That specifies the values of two local
12686 variables, @code{point} and @code{sentence-end}. The local value of
12687 point, from before the search, is used in the
12688 @code{constrain-to-field} function which handles forms and
12689 equivalents. The @code{sentence-end} variable is set by the
12690 @code{sentence-end} function.
12691
12692 @node fwd-sentence while loops
12693 @unnumberedsubsec The @code{while} loops
12694
12695 Two @code{while} loops follow. The first @code{while} has a
12696 true-or-false-test that tests true if the prefix argument for
12697 @code{forward-sentence} is a negative number. This is for going
12698 backwards. The body of this loop is similar to the body of the second
12699 @code{while} clause, but it is not exactly the same. We will skip
12700 this @code{while} loop and concentrate on the second @code{while}
12701 loop.
12702
12703 @need 1500
12704 The second @code{while} loop is for moving point forward. Its skeleton
12705 looks like this:
12706
12707 @smallexample
12708 @group
12709 (while (> arg 0) ; @r{true-or-false-test}
12710 (let @var{varlist}
12711 (if (@var{true-or-false-test})
12712 @var{then-part}
12713 @var{else-part}
12714 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
12715 @end group
12716 @end smallexample
12717
12718 The @code{while} loop is of the decrementing kind.
12719 (@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
12720 has a true-or-false-test that tests true so long as the counter (in
12721 this case, the variable @code{arg}) is greater than zero; and it has a
12722 decrementer that subtracts 1 from the value of the counter every time
12723 the loop repeats.
12724
12725 If no prefix argument is given to @code{forward-sentence}, which is
12726 the most common way the command is used, this @code{while} loop will
12727 run once, since the value of @code{arg} will be 1.
12728
12729 The body of the @code{while} loop consists of a @code{let} expression,
12730 which creates and binds a local variable, and has, as its body, an
12731 @code{if} expression.
12732
12733 @need 1250
12734 The body of the @code{while} loop looks like this:
12735
12736 @smallexample
12737 @group
12738 (let ((par-end
12739 (save-excursion (end-of-paragraph-text) (point))))
12740 (if (re-search-forward sentence-end par-end t)
12741 (skip-chars-backward " \t\n")
12742 (goto-char par-end)))
12743 @end group
12744 @end smallexample
12745
12746 The @code{let} expression creates and binds the local variable
12747 @code{par-end}. As we shall see, this local variable is designed to
12748 provide a bound or limit to the regular expression search. If the
12749 search fails to find a proper sentence ending in the paragraph, it will
12750 stop on reaching the end of the paragraph.
12751
12752 But first, let us examine how @code{par-end} is bound to the value of
12753 the end of the paragraph. What happens is that the @code{let} sets the
12754 value of @code{par-end} to the value returned when the Lisp interpreter
12755 evaluates the expression
12756
12757 @smallexample
12758 @group
12759 (save-excursion (end-of-paragraph-text) (point))
12760 @end group
12761 @end smallexample
12762
12763 @noindent
12764 In this expression, @code{(end-of-paragraph-text)} moves point to the
12765 end of the paragraph, @code{(point)} returns the value of point, and then
12766 @code{save-excursion} restores point to its original position. Thus,
12767 the @code{let} binds @code{par-end} to the value returned by the
12768 @code{save-excursion} expression, which is the position of the end of
12769 the paragraph. (The @code{end-of-paragraph-text} function uses
12770 @code{forward-paragraph}, which we will discuss shortly.)
12771
12772 @need 1200
12773 Emacs next evaluates the body of the @code{let}, which is an @code{if}
12774 expression that looks like this:
12775
12776 @smallexample
12777 @group
12778 (if (re-search-forward sentence-end par-end t) ; @r{if-part}
12779 (skip-chars-backward " \t\n") ; @r{then-part}
12780 (goto-char par-end))) ; @r{else-part}
12781 @end group
12782 @end smallexample
12783
12784 The @code{if} tests whether its first argument is true and if so,
12785 evaluates its then-part; otherwise, the Emacs Lisp interpreter
12786 evaluates the else-part. The true-or-false-test of the @code{if}
12787 expression is the regular expression search.
12788
12789 It may seem odd to have what looks like the `real work' of
12790 the @code{forward-sentence} function buried here, but this is a common
12791 way this kind of operation is carried out in Lisp.
12792
12793 @node fwd-sentence re-search
12794 @unnumberedsubsec The regular expression search
12795
12796 The @code{re-search-forward} function searches for the end of the
12797 sentence, that is, for the pattern defined by the @code{sentence-end}
12798 regular expression. If the pattern is found---if the end of the sentence is
12799 found---then the @code{re-search-forward} function does two things:
12800
12801 @enumerate
12802 @item
12803 The @code{re-search-forward} function carries out a side effect, which
12804 is to move point to the end of the occurrence found.
12805
12806 @item
12807 The @code{re-search-forward} function returns a value of true. This is
12808 the value received by the @code{if}, and means that the search was
12809 successful.
12810 @end enumerate
12811
12812 @noindent
12813 The side effect, the movement of point, is completed before the
12814 @code{if} function is handed the value returned by the successful
12815 conclusion of the search.
12816
12817 When the @code{if} function receives the value of true from a successful
12818 call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12819 which is the expression @code{(skip-chars-backward " \t\n")}. This
12820 expression moves backwards over any blank spaces, tabs or carriage
12821 returns until a printed character is found and then leaves point after
12822 the character. Since point has already been moved to the end of the
12823 pattern that marks the end of the sentence, this action leaves point
12824 right after the closing printed character of the sentence, which is
12825 usually a period.
12826
12827 On the other hand, if the @code{re-search-forward} function fails to
12828 find a pattern marking the end of the sentence, the function returns
12829 false. The false then causes the @code{if} to evaluate its third
12830 argument, which is @code{(goto-char par-end)}: it moves point to the
12831 end of the paragraph.
12832
12833 (And if the text is in a form or equivalent, and point may not move
12834 fully, then the @code{constrain-to-field} function comes into play.)
12835
12836 Regular expression searches are exceptionally useful and the pattern
12837 illustrated by @code{re-search-forward}, in which the search is the
12838 test of an @code{if} expression, is handy. You will see or write code
12839 incorporating this pattern often.
12840
12841 @node forward-paragraph
12842 @section @code{forward-paragraph}: a Goldmine of Functions
12843 @findex forward-paragraph
12844
12845 @ignore
12846 @c in GNU Emacs 22
12847 (defun forward-paragraph (&optional arg)
12848 "Move forward to end of paragraph.
12849 With argument ARG, do it ARG times;
12850 a negative argument ARG = -N means move backward N paragraphs.
12851
12852 A line which `paragraph-start' matches either separates paragraphs
12853 \(if `paragraph-separate' matches it also) or is the first line of a paragraph.
12854 A paragraph end is the beginning of a line which is not part of the paragraph
12855 to which the end of the previous line belongs, or the end of the buffer.
12856 Returns the count of paragraphs left to move."
12857 (interactive "p")
12858 (or arg (setq arg 1))
12859 (let* ((opoint (point))
12860 (fill-prefix-regexp
12861 (and fill-prefix (not (equal fill-prefix ""))
12862 (not paragraph-ignore-fill-prefix)
12863 (regexp-quote fill-prefix)))
12864 ;; Remove ^ from paragraph-start and paragraph-sep if they are there.
12865 ;; These regexps shouldn't be anchored, because we look for them
12866 ;; starting at the left-margin. This allows paragraph commands to
12867 ;; work normally with indented text.
12868 ;; This hack will not find problem cases like "whatever\\|^something".
12869 (parstart (if (and (not (equal "" paragraph-start))
12870 (equal ?^ (aref paragraph-start 0)))
12871 (substring paragraph-start 1)
12872 paragraph-start))
12873 (parsep (if (and (not (equal "" paragraph-separate))
12874 (equal ?^ (aref paragraph-separate 0)))
12875 (substring paragraph-separate 1)
12876 paragraph-separate))
12877 (parsep
12878 (if fill-prefix-regexp
12879 (concat parsep "\\|"
12880 fill-prefix-regexp "[ \t]*$")
12881 parsep))
12882 ;; This is used for searching.
12883 (sp-parstart (concat "^[ \t]*\\(?:" parstart "\\|" parsep "\\)"))
12884 start found-start)
12885 (while (and (< arg 0) (not (bobp)))
12886 (if (and (not (looking-at parsep))
12887 (re-search-backward "^\n" (max (1- (point)) (point-min)) t)
12888 (looking-at parsep))
12889 (setq arg (1+ arg))
12890 (setq start (point))
12891 ;; Move back over paragraph-separating lines.
12892 (forward-char -1) (beginning-of-line)
12893 (while (and (not (bobp))
12894 (progn (move-to-left-margin)
12895 (looking-at parsep)))
12896 (forward-line -1))
12897 (if (bobp)
12898 nil
12899 (setq arg (1+ arg))
12900 ;; Go to end of the previous (non-separating) line.
12901 (end-of-line)
12902 ;; Search back for line that starts or separates paragraphs.
12903 (if (if fill-prefix-regexp
12904 ;; There is a fill prefix; it overrides parstart.
12905 (let (multiple-lines)
12906 (while (and (progn (beginning-of-line) (not (bobp)))
12907 (progn (move-to-left-margin)
12908 (not (looking-at parsep)))
12909 (looking-at fill-prefix-regexp))
12910 (unless (= (point) start)
12911 (setq multiple-lines t))
12912 (forward-line -1))
12913 (move-to-left-margin)
12914 ;; This deleted code caused a long hanging-indent line
12915 ;; not to be filled together with the following lines.
12916 ;; ;; Don't move back over a line before the paragraph
12917 ;; ;; which doesn't start with fill-prefix
12918 ;; ;; unless that is the only line we've moved over.
12919 ;; (and (not (looking-at fill-prefix-regexp))
12920 ;; multiple-lines
12921 ;; (forward-line 1))
12922 (not (bobp)))
12923 (while (and (re-search-backward sp-parstart nil 1)
12924 (setq found-start t)
12925 ;; Found a candidate, but need to check if it is a
12926 ;; REAL parstart.
12927 (progn (setq start (point))
12928 (move-to-left-margin)
12929 (not (looking-at parsep)))
12930 (not (and (looking-at parstart)
12931 (or (not use-hard-newlines)
12932 (bobp)
12933 (get-text-property
12934 (1- start) 'hard)))))
12935 (setq found-start nil)
12936 (goto-char start))
12937 found-start)
12938 ;; Found one.
12939 (progn
12940 ;; Move forward over paragraph separators.
12941 ;; We know this cannot reach the place we started
12942 ;; because we know we moved back over a non-separator.
12943 (while (and (not (eobp))
12944 (progn (move-to-left-margin)
12945 (looking-at parsep)))
12946 (forward-line 1))
12947 ;; If line before paragraph is just margin, back up to there.
12948 (end-of-line 0)
12949 (if (> (current-column) (current-left-margin))
12950 (forward-char 1)
12951 (skip-chars-backward " \t")
12952 (if (not (bolp))
12953 (forward-line 1))))
12954 ;; No starter or separator line => use buffer beg.
12955 (goto-char (point-min))))))
12956
12957 (while (and (> arg 0) (not (eobp)))
12958 ;; Move forward over separator lines...
12959 (while (and (not (eobp))
12960 (progn (move-to-left-margin) (not (eobp)))
12961 (looking-at parsep))
12962 (forward-line 1))
12963 (unless (eobp) (setq arg (1- arg)))
12964 ;; ... and one more line.
12965 (forward-line 1)
12966 (if fill-prefix-regexp
12967 ;; There is a fill prefix; it overrides parstart.
12968 (while (and (not (eobp))
12969 (progn (move-to-left-margin) (not (eobp)))
12970 (not (looking-at parsep))
12971 (looking-at fill-prefix-regexp))
12972 (forward-line 1))
12973 (while (and (re-search-forward sp-parstart nil 1)
12974 (progn (setq start (match-beginning 0))
12975 (goto-char start)
12976 (not (eobp)))
12977 (progn (move-to-left-margin)
12978 (not (looking-at parsep)))
12979 (or (not (looking-at parstart))
12980 (and use-hard-newlines
12981 (not (get-text-property (1- start) 'hard)))))
12982 (forward-char 1))
12983 (if (< (point) (point-max))
12984 (goto-char start))))
12985 (constrain-to-field nil opoint t)
12986 ;; Return the number of steps that could not be done.
12987 arg))
12988 @end ignore
12989
12990 The @code{forward-paragraph} function moves point forward to the end
12991 of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12992 number of functions that are important in themselves, including
12993 @code{let*}, @code{match-beginning}, and @code{looking-at}.
12994
12995 The function definition for @code{forward-paragraph} is considerably
12996 longer than the function definition for @code{forward-sentence}
12997 because it works with a paragraph, each line of which may begin with a
12998 fill prefix.
12999
13000 A fill prefix consists of a string of characters that are repeated at
13001 the beginning of each line. For example, in Lisp code, it is a
13002 convention to start each line of a paragraph-long comment with
13003 @samp{;;; }. In Text mode, four blank spaces make up another common
13004 fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
13005 emacs, The GNU Emacs Manual}, for more information about fill
13006 prefixes.)
13007
13008 The existence of a fill prefix means that in addition to being able to
13009 find the end of a paragraph whose lines begin on the left-most
13010 column, the @code{forward-paragraph} function must be able to find the
13011 end of a paragraph when all or many of the lines in the buffer begin
13012 with the fill prefix.
13013
13014 Moreover, it is sometimes practical to ignore a fill prefix that
13015 exists, especially when blank lines separate paragraphs.
13016 This is an added complication.
13017
13018 @menu
13019 * forward-paragraph in brief:: Key parts of the function definition.
13020 * fwd-para let:: The @code{let*} expression.
13021 * fwd-para while:: The forward motion @code{while} loop.
13022 @end menu
13023
13024 @ifnottex
13025 @node forward-paragraph in brief
13026 @unnumberedsubsec Shortened @code{forward-paragraph} function definition
13027 @end ifnottex
13028
13029 Rather than print all of the @code{forward-paragraph} function, we
13030 will only print parts of it. Read without preparation, the function
13031 can be daunting!
13032
13033 @need 800
13034 In outline, the function looks like this:
13035
13036 @smallexample
13037 @group
13038 (defun forward-paragraph (&optional arg)
13039 "@var{documentation}@dots{}"
13040 (interactive "p")
13041 (or arg (setq arg 1))
13042 (let*
13043 @var{varlist}
13044 (while (and (< arg 0) (not (bobp))) ; @r{backward-moving-code}
13045 @dots{}
13046 (while (and (> arg 0) (not (eobp))) ; @r{forward-moving-code}
13047 @dots{}
13048 @end group
13049 @end smallexample
13050
13051 The first parts of the function are routine: the function's argument
13052 list consists of one optional argument. Documentation follows.
13053
13054 The lower case @samp{p} in the @code{interactive} declaration means
13055 that the processed prefix argument, if any, is passed to the function.
13056 This will be a number, and is the repeat count of how many paragraphs
13057 point will move. The @code{or} expression in the next line handles
13058 the common case when no argument is passed to the function, which occurs
13059 if the function is called from other code rather than interactively.
13060 This case was described earlier. (@xref{forward-sentence, The
13061 @code{forward-sentence} function}.) Now we reach the end of the
13062 familiar part of this function.
13063
13064 @node fwd-para let
13065 @unnumberedsubsec The @code{let*} expression
13066
13067 The next line of the @code{forward-paragraph} function begins a
13068 @code{let*} expression. This is a different than @code{let}. The
13069 symbol is @code{let*} not @code{let}.
13070
13071 The @code{let*} special form is like @code{let} except that Emacs sets
13072 each variable in sequence, one after another, and variables in the
13073 latter part of the varlist can make use of the values to which Emacs
13074 set variables in the earlier part of the varlist.
13075
13076 @ignore
13077 ( refappend save-excursion, , code save-excursion in code append-to-buffer .)
13078 @end ignore
13079
13080 (@ref{append save-excursion, , @code{save-excursion} in @code{append-to-buffer}}.)
13081
13082 In the @code{let*} expression in this function, Emacs binds a total of
13083 seven variables: @code{opoint}, @code{fill-prefix-regexp},
13084 @code{parstart}, @code{parsep}, @code{sp-parstart}, @code{start}, and
13085 @code{found-start}.
13086
13087 The variable @code{parsep} appears twice, first, to remove instances
13088 of @samp{^}, and second, to handle fill prefixes.
13089
13090 The variable @code{opoint} is just the value of @code{point}. As you
13091 can guess, it is used in a @code{constrain-to-field} expression, just
13092 as in @code{forward-sentence}.
13093
13094 The variable @code{fill-prefix-regexp} is set to the value returned by
13095 evaluating the following list:
13096
13097 @smallexample
13098 @group
13099 (and fill-prefix
13100 (not (equal fill-prefix ""))
13101 (not paragraph-ignore-fill-prefix)
13102 (regexp-quote fill-prefix))
13103 @end group
13104 @end smallexample
13105
13106 @noindent
13107 This is an expression whose first element is the @code{and} special form.
13108
13109 As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
13110 function}), the @code{and} special form evaluates each of its
13111 arguments until one of the arguments returns a value of @code{nil}, in
13112 which case the @code{and} expression returns @code{nil}; however, if
13113 none of the arguments returns a value of @code{nil}, the value
13114 resulting from evaluating the last argument is returned. (Since such
13115 a value is not @code{nil}, it is considered true in Lisp.) In other
13116 words, an @code{and} expression returns a true value only if all its
13117 arguments are true.
13118 @findex and
13119
13120 In this case, the variable @code{fill-prefix-regexp} is bound to a
13121 non-@code{nil} value only if the following four expressions produce a
13122 true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
13123 @code{fill-prefix-regexp} is bound to @code{nil}.
13124
13125 @table @code
13126 @item fill-prefix
13127 When this variable is evaluated, the value of the fill prefix, if any,
13128 is returned. If there is no fill prefix, this variable returns
13129 @code{nil}.
13130
13131 @item (not (equal fill-prefix "")
13132 This expression checks whether an existing fill prefix is an empty
13133 string, that is, a string with no characters in it. An empty string is
13134 not a useful fill prefix.
13135
13136 @item (not paragraph-ignore-fill-prefix)
13137 This expression returns @code{nil} if the variable
13138 @code{paragraph-ignore-fill-prefix} has been turned on by being set to a
13139 true value such as @code{t}.
13140
13141 @item (regexp-quote fill-prefix)
13142 This is the last argument to the @code{and} special form. If all the
13143 arguments to the @code{and} are true, the value resulting from
13144 evaluating this expression will be returned by the @code{and} expression
13145 and bound to the variable @code{fill-prefix-regexp},
13146 @end table
13147
13148 @findex regexp-quote
13149 @noindent
13150 The result of evaluating this @code{and} expression successfully is that
13151 @code{fill-prefix-regexp} will be bound to the value of
13152 @code{fill-prefix} as modified by the @code{regexp-quote} function.
13153 What @code{regexp-quote} does is read a string and return a regular
13154 expression that will exactly match the string and match nothing else.
13155 This means that @code{fill-prefix-regexp} will be set to a value that
13156 will exactly match the fill prefix if the fill prefix exists.
13157 Otherwise, the variable will be set to @code{nil}.
13158
13159 The next two local variables in the @code{let*} expression are
13160 designed to remove instances of @samp{^} from @code{parstart} and
13161 @code{parsep}, the local variables which indicate the paragraph start
13162 and the paragraph separator. The next expression sets @code{parsep}
13163 again. That is to handle fill prefixes.
13164
13165 This is the setting that requires the definition call @code{let*}
13166 rather than @code{let}. The true-or-false-test for the @code{if}
13167 depends on whether the variable @code{fill-prefix-regexp} evaluates to
13168 @code{nil} or some other value.
13169
13170 If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
13171 the else-part of the @code{if} expression and binds @code{parsep} to
13172 its local value. (@code{parsep} is a regular expression that matches
13173 what separates paragraphs.)
13174
13175 But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
13176 the then-part of the @code{if} expression and binds @code{parsep} to a
13177 regular expression that includes the @code{fill-prefix-regexp} as part
13178 of the pattern.
13179
13180 Specifically, @code{parsep} is set to the original value of the
13181 paragraph separate regular expression concatenated with an alternative
13182 expression that consists of the @code{fill-prefix-regexp} followed by
13183 optional whitespace to the end of the line. The whitespace is defined
13184 by @w{@code{"[ \t]*$"}}.) The @samp{\\|} defines this portion of the
13185 regexp as an alternative to @code{parsep}.
13186
13187 According to a comment in the code, the next local variable,
13188 @code{sp-parstart}, is used for searching, and then the final two,
13189 @code{start} and @code{found-start}, are set to @code{nil}.
13190
13191 Now we get into the body of the @code{let*}. The first part of the body
13192 of the @code{let*} deals with the case when the function is given a
13193 negative argument and is therefore moving backwards. We will skip this
13194 section.
13195
13196 @node fwd-para while
13197 @unnumberedsubsec The forward motion @code{while} loop
13198
13199 The second part of the body of the @code{let*} deals with forward
13200 motion. It is a @code{while} loop that repeats itself so long as the
13201 value of @code{arg} is greater than zero. In the most common use of
13202 the function, the value of the argument is 1, so the body of the
13203 @code{while} loop is evaluated exactly once, and the cursor moves
13204 forward one paragraph.
13205
13206 @ignore
13207 (while (and (> arg 0) (not (eobp)))
13208
13209 ;; Move forward over separator lines...
13210 (while (and (not (eobp))
13211 (progn (move-to-left-margin) (not (eobp)))
13212 (looking-at parsep))
13213 (forward-line 1))
13214 (unless (eobp) (setq arg (1- arg)))
13215 ;; ... and one more line.
13216 (forward-line 1)
13217
13218 (if fill-prefix-regexp
13219 ;; There is a fill prefix; it overrides parstart.
13220 (while (and (not (eobp))
13221 (progn (move-to-left-margin) (not (eobp)))
13222 (not (looking-at parsep))
13223 (looking-at fill-prefix-regexp))
13224 (forward-line 1))
13225
13226 (while (and (re-search-forward sp-parstart nil 1)
13227 (progn (setq start (match-beginning 0))
13228 (goto-char start)
13229 (not (eobp)))
13230 (progn (move-to-left-margin)
13231 (not (looking-at parsep)))
13232 (or (not (looking-at parstart))
13233 (and use-hard-newlines
13234 (not (get-text-property (1- start) 'hard)))))
13235 (forward-char 1))
13236
13237 (if (< (point) (point-max))
13238 (goto-char start))))
13239 @end ignore
13240
13241 This part handles three situations: when point is between paragraphs,
13242 when there is a fill prefix and when there is no fill prefix.
13243
13244 @need 800
13245 The @code{while} loop looks like this:
13246
13247 @smallexample
13248 @group
13249 ;; @r{going forwards and not at the end of the buffer}
13250 (while (and (> arg 0) (not (eobp)))
13251
13252 ;; @r{between paragraphs}
13253 ;; Move forward over separator lines...
13254 (while (and (not (eobp))
13255 (progn (move-to-left-margin) (not (eobp)))
13256 (looking-at parsep))
13257 (forward-line 1))
13258 ;; @r{This decrements the loop}
13259 (unless (eobp) (setq arg (1- arg)))
13260 ;; ... and one more line.
13261 (forward-line 1)
13262 @end group
13263
13264 @group
13265 (if fill-prefix-regexp
13266 ;; There is a fill prefix; it overrides parstart;
13267 ;; we go forward line by line
13268 (while (and (not (eobp))
13269 (progn (move-to-left-margin) (not (eobp)))
13270 (not (looking-at parsep))
13271 (looking-at fill-prefix-regexp))
13272 (forward-line 1))
13273 @end group
13274
13275 @group
13276 ;; There is no fill prefix;
13277 ;; we go forward character by character
13278 (while (and (re-search-forward sp-parstart nil 1)
13279 (progn (setq start (match-beginning 0))
13280 (goto-char start)
13281 (not (eobp)))
13282 (progn (move-to-left-margin)
13283 (not (looking-at parsep)))
13284 (or (not (looking-at parstart))
13285 (and use-hard-newlines
13286 (not (get-text-property (1- start) 'hard)))))
13287 (forward-char 1))
13288 @end group
13289
13290 @group
13291 ;; and if there is no fill prefix and if we are not at the end,
13292 ;; go to whatever was found in the regular expression search
13293 ;; for sp-parstart
13294 (if (< (point) (point-max))
13295 (goto-char start))))
13296 @end group
13297 @end smallexample
13298
13299 @findex eobp
13300 We can see that this is a decrementing counter @code{while} loop,
13301 using the expression @code{(setq arg (1- arg))} as the decrementer.
13302 That expression is not far from the @code{while}, but is hidden in
13303 another Lisp macro, an @code{unless} macro. Unless we are at the end
13304 of the buffer---that is what the @code{eobp} function determines; it
13305 is an abbreviation of @samp{End Of Buffer P}---we decrease the value
13306 of @code{arg} by one.
13307
13308 (If we are at the end of the buffer, we cannot go forward any more and
13309 the next loop of the @code{while} expression will test false since the
13310 test is an @code{and} with @code{(not (eobp))}. The @code{not}
13311 function means exactly as you expect; it is another name for
13312 @code{null}, a function that returns true when its argument is false.)
13313
13314 Interestingly, the loop count is not decremented until we leave the
13315 space between paragraphs, unless we come to the end of buffer or stop
13316 seeing the local value of the paragraph separator.
13317
13318 That second @code{while} also has a @code{(move-to-left-margin)}
13319 expression. The function is self-explanatory. It is inside a
13320 @code{progn} expression and not the last element of its body, so it is
13321 only invoked for its side effect, which is to move point to the left
13322 margin of the current line.
13323
13324 @findex looking-at
13325 The @code{looking-at} function is also self-explanatory; it returns
13326 true if the text after point matches the regular expression given as
13327 its argument.
13328
13329 The rest of the body of the loop looks difficult at first, but makes
13330 sense as you come to understand it.
13331
13332 @need 800
13333 First consider what happens if there is a fill prefix:
13334
13335 @smallexample
13336 @group
13337 (if fill-prefix-regexp
13338 ;; There is a fill prefix; it overrides parstart;
13339 ;; we go forward line by line
13340 (while (and (not (eobp))
13341 (progn (move-to-left-margin) (not (eobp)))
13342 (not (looking-at parsep))
13343 (looking-at fill-prefix-regexp))
13344 (forward-line 1))
13345 @end group
13346 @end smallexample
13347
13348 @noindent
13349 This expression moves point forward line by line so long
13350 as four conditions are true:
13351
13352 @enumerate
13353 @item
13354 Point is not at the end of the buffer.
13355
13356 @item
13357 We can move to the left margin of the text and are
13358 not at the end of the buffer.
13359
13360 @item
13361 The text following point does not separate paragraphs.
13362
13363 @item
13364 The pattern following point is the fill prefix regular expression.
13365 @end enumerate
13366
13367 The last condition may be puzzling, until you remember that point was
13368 moved to the beginning of the line early in the @code{forward-paragraph}
13369 function. This means that if the text has a fill prefix, the
13370 @code{looking-at} function will see it.
13371
13372 @need 1250
13373 Consider what happens when there is no fill prefix.
13374
13375 @smallexample
13376 @group
13377 (while (and (re-search-forward sp-parstart nil 1)
13378 (progn (setq start (match-beginning 0))
13379 (goto-char start)
13380 (not (eobp)))
13381 (progn (move-to-left-margin)
13382 (not (looking-at parsep)))
13383 (or (not (looking-at parstart))
13384 (and use-hard-newlines
13385 (not (get-text-property (1- start) 'hard)))))
13386 (forward-char 1))
13387 @end group
13388 @end smallexample
13389
13390 @noindent
13391 This @code{while} loop has us searching forward for
13392 @code{sp-parstart}, which is the combination of possible whitespace
13393 with a the local value of the start of a paragraph or of a paragraph
13394 separator. (The latter two are within an expression starting
13395 @code{\(?:} so that they are not referenced by the
13396 @code{match-beginning} function.)
13397
13398 @need 800
13399 The two expressions,
13400
13401 @smallexample
13402 @group
13403 (setq start (match-beginning 0))
13404 (goto-char start)
13405 @end group
13406 @end smallexample
13407
13408 @noindent
13409 mean go to the start of the text matched by the regular expression
13410 search.
13411
13412 The @code{(match-beginning 0)} expression is new. It returns a number
13413 specifying the location of the start of the text that was matched by
13414 the last search.
13415
13416 The @code{match-beginning} function is used here because of a
13417 characteristic of a forward search: a successful forward search,
13418 regardless of whether it is a plain search or a regular expression
13419 search, moves point to the end of the text that is found. In this
13420 case, a successful search moves point to the end of the pattern for
13421 @code{sp-parstart}.
13422
13423 However, we want to put point at the end of the current paragraph, not
13424 somewhere else. Indeed, since the search possibly includes the
13425 paragraph separator, point may end up at the beginning of the next one
13426 unless we use an expression that includes @code{match-beginning}.
13427
13428 @findex match-beginning
13429 When given an argument of 0, @code{match-beginning} returns the
13430 position that is the start of the text matched by the most recent
13431 search. In this case, the most recent search looks for
13432 @code{sp-parstart}. The @code{(match-beginning 0)} expression returns
13433 the beginning position of that pattern, rather than the end position
13434 of that pattern.
13435
13436 (Incidentally, when passed a positive number as an argument, the
13437 @code{match-beginning} function returns the location of point at that
13438 parenthesized expression in the last search unless that parenthesized
13439 expression begins with @code{\(?:}. I don't know why @code{\(?:}
13440 appears here since the argument is 0.)
13441
13442 @need 1250
13443 The last expression when there is no fill prefix is
13444
13445 @smallexample
13446 @group
13447 (if (< (point) (point-max))
13448 (goto-char start))))
13449 @end group
13450 @end smallexample
13451
13452 @noindent
13453 This says that if there is no fill prefix and if we are not at the
13454 end, point should move to the beginning of whatever was found by the
13455 regular expression search for @code{sp-parstart}.
13456
13457 The full definition for the @code{forward-paragraph} function not only
13458 includes code for going forwards, but also code for going backwards.
13459
13460 If you are reading this inside of GNU Emacs and you want to see the
13461 whole function, you can type @kbd{C-h f} (@code{describe-function})
13462 and the name of the function. This gives you the function
13463 documentation and the name of the library containing the function's
13464 source. Place point over the name of the library and press the RET
13465 key; you will be taken directly to the source. (Be sure to install
13466 your sources! Without them, you are like a person who tries to drive
13467 a car with his eyes shut!)
13468
13469 @node etags
13470 @section Create Your Own @file{TAGS} File
13471 @findex etags
13472 @cindex @file{TAGS} file, create own
13473
13474 Besides @kbd{C-h f} (@code{describe-function}), another way to see the
13475 source of a function is to type @kbd{M-.} (@code{find-tag}) and the
13476 name of the function when prompted for it. This is a good habit to
13477 get into. The @kbd{M-.} (@code{find-tag}) command takes you directly
13478 to the source for a function, variable, or node. The function depends
13479 on tags tables to tell it where to go.
13480
13481 If the @code{find-tag} function first asks you for the name of a
13482 @file{TAGS} table, give it the name of a @file{TAGS} file such as
13483 @file{/usr/local/src/emacs/src/TAGS}. (The exact path to your
13484 @file{TAGS} file depends on how your copy of Emacs was installed. I
13485 just told you the location that provides both my C and my Emacs Lisp
13486 sources.)
13487
13488 You can also create your own @file{TAGS} file for directories that
13489 lack one.
13490
13491 You often need to build and install tags tables yourself. They are
13492 not built automatically. A tags table is called a @file{TAGS} file;
13493 the name is in upper case letters.
13494
13495 You can create a @file{TAGS} file by calling the @code{etags} program
13496 that comes as a part of the Emacs distribution. Usually, @code{etags}
13497 is compiled and installed when Emacs is built. (@code{etags} is not
13498 an Emacs Lisp function or a part of Emacs; it is a C program.)
13499
13500 @need 1250
13501 To create a @file{TAGS} file, first switch to the directory in which
13502 you want to create the file. In Emacs you can do this with the
13503 @kbd{M-x cd} command, or by visiting a file in the directory, or by
13504 listing the directory with @kbd{C-x d} (@code{dired}). Then run the
13505 compile command, with @w{@code{etags *.el}} as the command to execute
13506
13507 @smallexample
13508 M-x compile RET etags *.el RET
13509 @end smallexample
13510
13511 @noindent
13512 to create a @file{TAGS} file for Emacs Lisp.
13513
13514 For example, if you have a large number of files in your
13515 @file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
13516 of which I load 12---you can create a @file{TAGS} file for the Emacs
13517 Lisp files in that directory.
13518
13519 @need 1250
13520 The @code{etags} program takes all the usual shell `wildcards'. For
13521 example, if you have two directories for which you want a single
13522 @file{TAGS} file, type @w{@code{etags *.el ../elisp/*.el}}, where
13523 @file{../elisp/} is the second directory:
13524
13525 @smallexample
13526 M-x compile RET etags *.el ../elisp/*.el RET
13527 @end smallexample
13528
13529 @need 1250
13530 Type
13531
13532 @smallexample
13533 M-x compile RET etags --help RET
13534 @end smallexample
13535
13536 @noindent
13537 to see a list of the options accepted by @code{etags} as well as a
13538 list of supported languages.
13539
13540 The @code{etags} program handles more than 20 languages, including
13541 Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, HTML, Java,
13542 LaTeX, Pascal, Perl, PostScript, Python, TeX, Texinfo, makefiles, and
13543 most assemblers. The program has no switches for specifying the
13544 language; it recognizes the language in an input file according to its
13545 file name and contents.
13546
13547 @file{etags} is very helpful when you are writing code yourself and
13548 want to refer back to functions you have already written. Just run
13549 @code{etags} again at intervals as you write new functions, so they
13550 become part of the @file{TAGS} file.
13551
13552 If you think an appropriate @file{TAGS} file already exists for what
13553 you want, but do not know where it is, you can use the @code{locate}
13554 program to attempt to find it.
13555
13556 Type @w{@kbd{M-x locate @key{RET} TAGS @key{RET}}} and Emacs will list
13557 for you the full path names of all your @file{TAGS} files. On my
13558 system, this command lists 34 @file{TAGS} files. On the other hand, a
13559 `plain vanilla' system I recently installed did not contain any
13560 @file{TAGS} files.
13561
13562 If the tags table you want has been created, you can use the @code{M-x
13563 visit-tags-table} command to specify it. Otherwise, you will need to
13564 create the tag table yourself and then use @code{M-x
13565 visit-tags-table}.
13566
13567 @subsubheading Building Tags in the Emacs sources
13568 @cindex Building Tags in the Emacs sources
13569 @cindex Tags in the Emacs sources
13570 @findex make tags
13571
13572 The GNU Emacs sources come with a @file{Makefile} that contains a
13573 sophisticated @code{etags} command that creates, collects, and merges
13574 tags tables from all over the Emacs sources and puts the information
13575 into one @file{TAGS} file in the @file{src/} directory. (The
13576 @file{src/} directory is below the top level of your Emacs directory.)
13577
13578 @need 1250
13579 To build this @file{TAGS} file, go to the top level of your Emacs
13580 source directory and run the compile command @code{make tags}:
13581
13582 @smallexample
13583 M-x compile RET make tags RET
13584 @end smallexample
13585
13586 @noindent
13587 (The @code{make tags} command works well with the GNU Emacs sources,
13588 as well as with some other source packages.)
13589
13590 For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
13591 Manual}.
13592
13593 @node Regexp Review
13594 @section Review
13595
13596 Here is a brief summary of some recently introduced functions.
13597
13598 @table @code
13599 @item while
13600 Repeatedly evaluate the body of the expression so long as the first
13601 element of the body tests true. Then return @code{nil}. (The
13602 expression is evaluated only for its side effects.)
13603
13604 @need 1250
13605 For example:
13606
13607 @smallexample
13608 @group
13609 (let ((foo 2))
13610 (while (> foo 0)
13611 (insert (format "foo is %d.\n" foo))
13612 (setq foo (1- foo))))
13613
13614 @result{} foo is 2.
13615 foo is 1.
13616 nil
13617 @end group
13618 @end smallexample
13619
13620 @noindent
13621 (The @code{insert} function inserts its arguments at point; the
13622 @code{format} function returns a string formatted from its arguments
13623 the way @code{message} formats its arguments; @code{\n} produces a new
13624 line.)
13625
13626 @item re-search-forward
13627 Search for a pattern, and if the pattern is found, move point to rest
13628 just after it.
13629
13630 @noindent
13631 Takes four arguments, like @code{search-forward}:
13632
13633 @enumerate
13634 @item
13635 A regular expression that specifies the pattern to search for.
13636 (Remember to put quotation marks around this argument!)
13637
13638 @item
13639 Optionally, the limit of the search.
13640
13641 @item
13642 Optionally, what to do if the search fails, return @code{nil} or an
13643 error message.
13644
13645 @item
13646 Optionally, how many times to repeat the search; if negative, the
13647 search goes backwards.
13648 @end enumerate
13649
13650 @item let*
13651 Bind some variables locally to particular values,
13652 and then evaluate the remaining arguments, returning the value of the
13653 last one. While binding the local variables, use the local values of
13654 variables bound earlier, if any.
13655
13656 @need 1250
13657 For example:
13658
13659 @smallexample
13660 @group
13661 (let* ((foo 7)
13662 (bar (* 3 foo)))
13663 (message "`bar' is %d." bar))
13664 @result{} `bar' is 21.
13665 @end group
13666 @end smallexample
13667
13668 @item match-beginning
13669 Return the position of the start of the text found by the last regular
13670 expression search.
13671
13672 @item looking-at
13673 Return @code{t} for true if the text after point matches the argument,
13674 which should be a regular expression.
13675
13676 @item eobp
13677 Return @code{t} for true if point is at the end of the accessible part
13678 of a buffer. The end of the accessible part is the end of the buffer
13679 if the buffer is not narrowed; it is the end of the narrowed part if
13680 the buffer is narrowed.
13681 @end table
13682
13683 @need 1500
13684 @node re-search Exercises
13685 @section Exercises with @code{re-search-forward}
13686
13687 @itemize @bullet
13688 @item
13689 Write a function to search for a regular expression that matches two
13690 or more blank lines in sequence.
13691
13692 @item
13693 Write a function to search for duplicated words, such as `the the'.
13694 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
13695 Manual}, for information on how to write a regexp (a regular
13696 expression) to match a string that is composed of two identical
13697 halves. You can devise several regexps; some are better than others.
13698 The function I use is described in an appendix, along with several
13699 regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
13700 @end itemize
13701
13702 @node Counting Words
13703 @chapter Counting: Repetition and Regexps
13704 @cindex Repetition for word counting
13705 @cindex Regular expressions for word counting
13706
13707 Repetition and regular expression searches are powerful tools that you
13708 often use when you write code in Emacs Lisp. This chapter illustrates
13709 the use of regular expression searches through the construction of
13710 word count commands using @code{while} loops and recursion.
13711
13712 @menu
13713 * Why Count Words::
13714 * @value{COUNT-WORDS}:: Use a regexp, but find a problem.
13715 * recursive-count-words:: Start with case of no words in region.
13716 * Counting Exercise::
13717 @end menu
13718
13719 @ifnottex
13720 @node Why Count Words
13721 @unnumberedsec Counting words
13722 @end ifnottex
13723
13724 The standard Emacs distribution contains functions for counting the
13725 number of lines and words within a region.
13726
13727 Certain types of writing ask you to count words. Thus, if you write
13728 an essay, you may be limited to 800 words; if you write a novel, you
13729 may discipline yourself to write 1000 words a day. It seems odd, but
13730 for a long time, Emacs lacked a word count command. Perhaps people used
13731 Emacs mostly for code or types of documentation that did not require
13732 word counts; or perhaps they restricted themselves to the operating
13733 system word count command, @code{wc}. Alternatively, people may have
13734 followed the publishers' convention and computed a word count by
13735 dividing the number of characters in a document by five.
13736
13737 There are many ways to implement a command to count words. Here are
13738 some examples, which you may wish to compare with the standard Emacs
13739 command, @code{count-words-region}.
13740
13741 @node @value{COUNT-WORDS}
13742 @section The @code{@value{COUNT-WORDS}} Function
13743 @findex @value{COUNT-WORDS}
13744
13745 A word count command could count words in a line, paragraph, region,
13746 or buffer. What should the command cover? You could design the
13747 command to count the number of words in a complete buffer. However,
13748 the Emacs tradition encourages flexibility---you may want to count
13749 words in just a section, rather than all of a buffer. So it makes
13750 more sense to design the command to count the number of words in a
13751 region. Once you have a command to count words in a region, you can,
13752 if you wish, count words in a whole buffer by marking it with
13753 @w{@kbd{C-x h}} (@code{mark-whole-buffer}).
13754
13755 Clearly, counting words is a repetitive act: starting from the
13756 beginning of the region, you count the first word, then the second
13757 word, then the third word, and so on, until you reach the end of the
13758 region. This means that word counting is ideally suited to recursion
13759 or to a @code{while} loop.
13760
13761 @menu
13762 * Design @value{COUNT-WORDS}:: The definition using a @code{while} loop.
13763 * Whitespace Bug:: The Whitespace Bug in @code{@value{COUNT-WORDS}}.
13764 @end menu
13765
13766 @ifnottex
13767 @node Design @value{COUNT-WORDS}
13768 @unnumberedsubsec Designing @code{@value{COUNT-WORDS}}
13769 @end ifnottex
13770
13771 First, we will implement the word count command with a @code{while}
13772 loop, then with recursion. The command will, of course, be
13773 interactive.
13774
13775 @need 800
13776 The template for an interactive function definition is, as always:
13777
13778 @smallexample
13779 @group
13780 (defun @var{name-of-function} (@var{argument-list})
13781 "@var{documentation}@dots{}"
13782 (@var{interactive-expression}@dots{})
13783 @var{body}@dots{})
13784 @end group
13785 @end smallexample
13786
13787 What we need to do is fill in the slots.
13788
13789 The name of the function should be self-explanatory and similar to the
13790 existing @code{count-lines-region} name. This makes the name easier
13791 to remember. @code{count-words-region} is the obvious choice. Since
13792 that name is now used for the standard Emacs command to count words, we
13793 will name our implementation @code{@value{COUNT-WORDS}}.
13794
13795 The function counts words within a region. This means that the
13796 argument list must contain symbols that are bound to the two
13797 positions, the beginning and end of the region. These two positions
13798 can be called @samp{beginning} and @samp{end} respectively. The first
13799 line of the documentation should be a single sentence, since that is
13800 all that is printed as documentation by a command such as
13801 @code{apropos}. The interactive expression will be of the form
13802 @samp{(interactive "r")}, since that will cause Emacs to pass the
13803 beginning and end of the region to the function's argument list. All
13804 this is routine.
13805
13806 The body of the function needs to be written to do three tasks:
13807 first, to set up conditions under which the @code{while} loop can
13808 count words, second, to run the @code{while} loop, and third, to send
13809 a message to the user.
13810
13811 When a user calls @code{@value{COUNT-WORDS}}, point may be at the
13812 beginning or the end of the region. However, the counting process
13813 must start at the beginning of the region. This means we will want
13814 to put point there if it is not already there. Executing
13815 @code{(goto-char beginning)} ensures this. Of course, we will want to
13816 return point to its expected position when the function finishes its
13817 work. For this reason, the body must be enclosed in a
13818 @code{save-excursion} expression.
13819
13820 The central part of the body of the function consists of a
13821 @code{while} loop in which one expression jumps point forward word by
13822 word, and another expression counts those jumps. The true-or-false-test
13823 of the @code{while} loop should test true so long as point should jump
13824 forward, and false when point is at the end of the region.
13825
13826 We could use @code{(forward-word 1)} as the expression for moving point
13827 forward word by word, but it is easier to see what Emacs identifies as a
13828 `word' if we use a regular expression search.
13829
13830 A regular expression search that finds the pattern for which it is
13831 searching leaves point after the last character matched. This means
13832 that a succession of successful word searches will move point forward
13833 word by word.
13834
13835 As a practical matter, we want the regular expression search to jump
13836 over whitespace and punctuation between words as well as over the
13837 words themselves. A regexp that refuses to jump over interword
13838 whitespace would never jump more than one word! This means that
13839 the regexp should include the whitespace and punctuation that follows
13840 a word, if any, as well as the word itself. (A word may end a buffer
13841 and not have any following whitespace or punctuation, so that part of
13842 the regexp must be optional.)
13843
13844 Thus, what we want for the regexp is a pattern defining one or more
13845 word constituent characters followed, optionally, by one or more
13846 characters that are not word constituents. The regular expression for
13847 this is:
13848
13849 @smallexample
13850 \w+\W*
13851 @end smallexample
13852
13853 @noindent
13854 The buffer's syntax table determines which characters are and are not
13855 word constituents. For more information about syntax,
13856 @pxref{Syntax Tables, , Syntax Tables, elisp, The GNU Emacs Lisp
13857 Reference Manual}.
13858
13859 @need 800
13860 The search expression looks like this:
13861
13862 @smallexample
13863 (re-search-forward "\\w+\\W*")
13864 @end smallexample
13865
13866 @noindent
13867 (Note that paired backslashes precede the @samp{w} and @samp{W}. A
13868 single backslash has special meaning to the Emacs Lisp interpreter.
13869 It indicates that the following character is interpreted differently
13870 than usual. For example, the two characters, @samp{\n}, stand for
13871 @samp{newline}, rather than for a backslash followed by @samp{n}. Two
13872 backslashes in a row stand for an ordinary, `unspecial' backslash, so
13873 Emacs Lisp interpreter ends of seeing a single backslash followed by a
13874 letter. So it discovers the letter is special.)
13875
13876 We need a counter to count how many words there are; this variable
13877 must first be set to 0 and then incremented each time Emacs goes
13878 around the @code{while} loop. The incrementing expression is simply:
13879
13880 @smallexample
13881 (setq count (1+ count))
13882 @end smallexample
13883
13884 Finally, we want to tell the user how many words there are in the
13885 region. The @code{message} function is intended for presenting this
13886 kind of information to the user. The message has to be phrased so
13887 that it reads properly regardless of how many words there are in the
13888 region: we don't want to say that ``there are 1 words in the region''.
13889 The conflict between singular and plural is ungrammatical. We can
13890 solve this problem by using a conditional expression that evaluates
13891 different messages depending on the number of words in the region.
13892 There are three possibilities: no words in the region, one word in the
13893 region, and more than one word. This means that the @code{cond}
13894 special form is appropriate.
13895
13896 @need 1500
13897 All this leads to the following function definition:
13898
13899 @smallexample
13900 @group
13901 ;;; @r{First version; has bugs!}
13902 (defun @value{COUNT-WORDS} (beginning end)
13903 "Print number of words in the region.
13904 Words are defined as at least one word-constituent
13905 character followed by at least one character that
13906 is not a word-constituent. The buffer's syntax
13907 table determines which characters these are."
13908 (interactive "r")
13909 (message "Counting words in region ... ")
13910 @end group
13911
13912 @group
13913 ;;; @r{1. Set up appropriate conditions.}
13914 (save-excursion
13915 (goto-char beginning)
13916 (let ((count 0))
13917 @end group
13918
13919 @group
13920 ;;; @r{2. Run the} while @r{loop.}
13921 (while (< (point) end)
13922 (re-search-forward "\\w+\\W*")
13923 (setq count (1+ count)))
13924 @end group
13925
13926 @group
13927 ;;; @r{3. Send a message to the user.}
13928 (cond ((zerop count)
13929 (message
13930 "The region does NOT have any words."))
13931 ((= 1 count)
13932 (message
13933 "The region has 1 word."))
13934 (t
13935 (message
13936 "The region has %d words." count))))))
13937 @end group
13938 @end smallexample
13939
13940 @noindent
13941 As written, the function works, but not in all circumstances.
13942
13943 @node Whitespace Bug
13944 @subsection The Whitespace Bug in @code{@value{COUNT-WORDS}}
13945
13946 The @code{@value{COUNT-WORDS}} command described in the preceding
13947 section has two bugs, or rather, one bug with two manifestations.
13948 First, if you mark a region containing only whitespace in the middle
13949 of some text, the @code{@value{COUNT-WORDS}} command tells you that the
13950 region contains one word! Second, if you mark a region containing
13951 only whitespace at the end of the buffer or the accessible portion of
13952 a narrowed buffer, the command displays an error message that looks
13953 like this:
13954
13955 @smallexample
13956 Search failed: "\\w+\\W*"
13957 @end smallexample
13958
13959 If you are reading this in Info in GNU Emacs, you can test for these
13960 bugs yourself.
13961
13962 First, evaluate the function in the usual manner to install it.
13963 @ifinfo
13964 Here is a copy of the definition. Place your cursor after the closing
13965 parenthesis and type @kbd{C-x C-e} to install it.
13966
13967 @smallexample
13968 @group
13969 ;; @r{First version; has bugs!}
13970 (defun @value{COUNT-WORDS} (beginning end)
13971 "Print number of words in the region.
13972 Words are defined as at least one word-constituent character followed
13973 by at least one character that is not a word-constituent. The buffer's
13974 syntax table determines which characters these are."
13975 @end group
13976 @group
13977 (interactive "r")
13978 (message "Counting words in region ... ")
13979 @end group
13980
13981 @group
13982 ;;; @r{1. Set up appropriate conditions.}
13983 (save-excursion
13984 (goto-char beginning)
13985 (let ((count 0))
13986 @end group
13987
13988 @group
13989 ;;; @r{2. Run the} while @r{loop.}
13990 (while (< (point) end)
13991 (re-search-forward "\\w+\\W*")
13992 (setq count (1+ count)))
13993 @end group
13994
13995 @group
13996 ;;; @r{3. Send a message to the user.}
13997 (cond ((zerop count)
13998 (message "The region does NOT have any words."))
13999 ((= 1 count) (message "The region has 1 word."))
14000 (t (message "The region has %d words." count))))))
14001 @end group
14002 @end smallexample
14003 @end ifinfo
14004
14005 @need 1000
14006 If you wish, you can also install this keybinding by evaluating it:
14007
14008 @smallexample
14009 (global-set-key "\C-c=" '@value{COUNT-WORDS})
14010 @end smallexample
14011
14012 To conduct the first test, set mark and point to the beginning and end
14013 of the following line and then type @kbd{C-c =} (or @kbd{M-x
14014 @value{COUNT-WORDS}} if you have not bound @kbd{C-c =}):
14015
14016 @smallexample
14017 one two three
14018 @end smallexample
14019
14020 @noindent
14021 Emacs will tell you, correctly, that the region has three words.
14022
14023 Repeat the test, but place mark at the beginning of the line and place
14024 point just @emph{before} the word @samp{one}. Again type the command
14025 @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}). Emacs should tell you
14026 that the region has no words, since it is composed only of the
14027 whitespace at the beginning of the line. But instead Emacs tells you
14028 that the region has one word!
14029
14030 For the third test, copy the sample line to the end of the
14031 @file{*scratch*} buffer and then type several spaces at the end of the
14032 line. Place mark right after the word @samp{three} and point at the
14033 end of line. (The end of the line will be the end of the buffer.)
14034 Type @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}) as you did before.
14035 Again, Emacs should tell you that the region has no words, since it is
14036 composed only of the whitespace at the end of the line. Instead,
14037 Emacs displays an error message saying @samp{Search failed}.
14038
14039 The two bugs stem from the same problem.
14040
14041 Consider the first manifestation of the bug, in which the command
14042 tells you that the whitespace at the beginning of the line contains
14043 one word. What happens is this: The @code{M-x @value{COUNT-WORDS}}
14044 command moves point to the beginning of the region. The @code{while}
14045 tests whether the value of point is smaller than the value of
14046 @code{end}, which it is. Consequently, the regular expression search
14047 looks for and finds the first word. It leaves point after the word.
14048 @code{count} is set to one. The @code{while} loop repeats; but this
14049 time the value of point is larger than the value of @code{end}, the
14050 loop is exited; and the function displays a message saying the number
14051 of words in the region is one. In brief, the regular expression
14052 search looks for and finds the word even though it is outside
14053 the marked region.
14054
14055 In the second manifestation of the bug, the region is whitespace at
14056 the end of the buffer. Emacs says @samp{Search failed}. What happens
14057 is that the true-or-false-test in the @code{while} loop tests true, so
14058 the search expression is executed. But since there are no more words
14059 in the buffer, the search fails.
14060
14061 In both manifestations of the bug, the search extends or attempts to
14062 extend outside of the region.
14063
14064 The solution is to limit the search to the region---this is a fairly
14065 simple action, but as you may have come to expect, it is not quite as
14066 simple as you might think.
14067
14068 As we have seen, the @code{re-search-forward} function takes a search
14069 pattern as its first argument. But in addition to this first,
14070 mandatory argument, it accepts three optional arguments. The optional
14071 second argument bounds the search. The optional third argument, if
14072 @code{t}, causes the function to return @code{nil} rather than signal
14073 an error if the search fails. The optional fourth argument is a
14074 repeat count. (In Emacs, you can see a function's documentation by
14075 typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
14076
14077 In the @code{@value{COUNT-WORDS}} definition, the value of the end of
14078 the region is held by the variable @code{end} which is passed as an
14079 argument to the function. Thus, we can add @code{end} as an argument
14080 to the regular expression search expression:
14081
14082 @smallexample
14083 (re-search-forward "\\w+\\W*" end)
14084 @end smallexample
14085
14086 However, if you make only this change to the @code{@value{COUNT-WORDS}}
14087 definition and then test the new version of the definition on a
14088 stretch of whitespace, you will receive an error message saying
14089 @samp{Search failed}.
14090
14091 What happens is this: the search is limited to the region, and fails
14092 as you expect because there are no word-constituent characters in the
14093 region. Since it fails, we receive an error message. But we do not
14094 want to receive an error message in this case; we want to receive the
14095 message that "The region does NOT have any words."
14096
14097 The solution to this problem is to provide @code{re-search-forward}
14098 with a third argument of @code{t}, which causes the function to return
14099 @code{nil} rather than signal an error if the search fails.
14100
14101 However, if you make this change and try it, you will see the message
14102 ``Counting words in region ... '' and @dots{} you will keep on seeing
14103 that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
14104
14105 Here is what happens: the search is limited to the region, as before,
14106 and it fails because there are no word-constituent characters in the
14107 region, as expected. Consequently, the @code{re-search-forward}
14108 expression returns @code{nil}. It does nothing else. In particular,
14109 it does not move point, which it does as a side effect if it finds the
14110 search target. After the @code{re-search-forward} expression returns
14111 @code{nil}, the next expression in the @code{while} loop is evaluated.
14112 This expression increments the count. Then the loop repeats. The
14113 true-or-false-test tests true because the value of point is still less
14114 than the value of end, since the @code{re-search-forward} expression
14115 did not move point. @dots{} and the cycle repeats @dots{}
14116
14117 The @code{@value{COUNT-WORDS}} definition requires yet another
14118 modification, to cause the true-or-false-test of the @code{while} loop
14119 to test false if the search fails. Put another way, there are two
14120 conditions that must be satisfied in the true-or-false-test before the
14121 word count variable is incremented: point must still be within the
14122 region and the search expression must have found a word to count.
14123
14124 Since both the first condition and the second condition must be true
14125 together, the two expressions, the region test and the search
14126 expression, can be joined with an @code{and} special form and embedded in
14127 the @code{while} loop as the true-or-false-test, like this:
14128
14129 @smallexample
14130 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
14131 @end smallexample
14132
14133 @c colon in printed section title causes problem in Info cross reference
14134 @c also trouble with an overfull hbox
14135 @iftex
14136 @noindent
14137 (For information about @code{and}, see
14138 @ref{kill-new function, , The @code{kill-new} function}.)
14139 @end iftex
14140 @ifinfo
14141 @noindent
14142 (@xref{kill-new function, , The @code{kill-new} function}, for
14143 information about @code{and}.)
14144 @end ifinfo
14145
14146 The @code{re-search-forward} expression returns @code{t} if the search
14147 succeeds and as a side effect moves point. Consequently, as words are
14148 found, point is moved through the region. When the search expression
14149 fails to find another word, or when point reaches the end of the
14150 region, the true-or-false-test tests false, the @code{while} loop
14151 exits, and the @code{@value{COUNT-WORDS}} function displays one or
14152 other of its messages.
14153
14154 After incorporating these final changes, the @code{@value{COUNT-WORDS}}
14155 works without bugs (or at least, without bugs that I have found!).
14156 Here is what it looks like:
14157
14158 @smallexample
14159 @group
14160 ;;; @r{Final version:} @code{while}
14161 (defun @value{COUNT-WORDS} (beginning end)
14162 "Print number of words in the region."
14163 (interactive "r")
14164 (message "Counting words in region ... ")
14165 @end group
14166
14167 @group
14168 ;;; @r{1. Set up appropriate conditions.}
14169 (save-excursion
14170 (let ((count 0))
14171 (goto-char beginning)
14172 @end group
14173
14174 @group
14175 ;;; @r{2. Run the} while @r{loop.}
14176 (while (and (< (point) end)
14177 (re-search-forward "\\w+\\W*" end t))
14178 (setq count (1+ count)))
14179 @end group
14180
14181 @group
14182 ;;; @r{3. Send a message to the user.}
14183 (cond ((zerop count)
14184 (message
14185 "The region does NOT have any words."))
14186 ((= 1 count)
14187 (message
14188 "The region has 1 word."))
14189 (t
14190 (message
14191 "The region has %d words." count))))))
14192 @end group
14193 @end smallexample
14194
14195 @node recursive-count-words
14196 @section Count Words Recursively
14197 @cindex Count words recursively
14198 @cindex Recursively counting words
14199 @cindex Words, counted recursively
14200
14201 You can write the function for counting words recursively as well as
14202 with a @code{while} loop. Let's see how this is done.
14203
14204 First, we need to recognize that the @code{@value{COUNT-WORDS}}
14205 function has three jobs: it sets up the appropriate conditions for
14206 counting to occur; it counts the words in the region; and it sends a
14207 message to the user telling how many words there are.
14208
14209 If we write a single recursive function to do everything, we will
14210 receive a message for every recursive call. If the region contains 13
14211 words, we will receive thirteen messages, one right after the other.
14212 We don't want this! Instead, we must write two functions to do the
14213 job, one of which (the recursive function) will be used inside of the
14214 other. One function will set up the conditions and display the
14215 message; the other will return the word count.
14216
14217 Let us start with the function that causes the message to be displayed.
14218 We can continue to call this @code{@value{COUNT-WORDS}}.
14219
14220 This is the function that the user will call. It will be interactive.
14221 Indeed, it will be similar to our previous versions of this
14222 function, except that it will call @code{recursive-count-words} to
14223 determine how many words are in the region.
14224
14225 @need 1250
14226 We can readily construct a template for this function, based on our
14227 previous versions:
14228
14229 @smallexample
14230 @group
14231 ;; @r{Recursive version; uses regular expression search}
14232 (defun @value{COUNT-WORDS} (beginning end)
14233 "@var{documentation}@dots{}"
14234 (@var{interactive-expression}@dots{})
14235 @end group
14236 @group
14237
14238 ;;; @r{1. Set up appropriate conditions.}
14239 (@var{explanatory message})
14240 (@var{set-up functions}@dots{}
14241 @end group
14242 @group
14243
14244 ;;; @r{2. Count the words.}
14245 @var{recursive call}
14246 @end group
14247 @group
14248
14249 ;;; @r{3. Send a message to the user.}
14250 @var{message providing word count}))
14251 @end group
14252 @end smallexample
14253
14254 The definition looks straightforward, except that somehow the count
14255 returned by the recursive call must be passed to the message
14256 displaying the word count. A little thought suggests that this can be
14257 done by making use of a @code{let} expression: we can bind a variable
14258 in the varlist of a @code{let} expression to the number of words in
14259 the region, as returned by the recursive call; and then the
14260 @code{cond} expression, using binding, can display the value to the
14261 user.
14262
14263 Often, one thinks of the binding within a @code{let} expression as
14264 somehow secondary to the `primary' work of a function. But in this
14265 case, what you might consider the `primary' job of the function,
14266 counting words, is done within the @code{let} expression.
14267
14268 @need 1250
14269 Using @code{let}, the function definition looks like this:
14270
14271 @smallexample
14272 @group
14273 (defun @value{COUNT-WORDS} (beginning end)
14274 "Print number of words in the region."
14275 (interactive "r")
14276 @end group
14277
14278 @group
14279 ;;; @r{1. Set up appropriate conditions.}
14280 (message "Counting words in region ... ")
14281 (save-excursion
14282 (goto-char beginning)
14283 @end group
14284
14285 @group
14286 ;;; @r{2. Count the words.}
14287 (let ((count (recursive-count-words end)))
14288 @end group
14289
14290 @group
14291 ;;; @r{3. Send a message to the user.}
14292 (cond ((zerop count)
14293 (message
14294 "The region does NOT have any words."))
14295 ((= 1 count)
14296 (message
14297 "The region has 1 word."))
14298 (t
14299 (message
14300 "The region has %d words." count))))))
14301 @end group
14302 @end smallexample
14303
14304 Next, we need to write the recursive counting function.
14305
14306 A recursive function has at least three parts: the `do-again-test', the
14307 `next-step-expression', and the recursive call.
14308
14309 The do-again-test determines whether the function will or will not be
14310 called again. Since we are counting words in a region and can use a
14311 function that moves point forward for every word, the do-again-test
14312 can check whether point is still within the region. The do-again-test
14313 should find the value of point and determine whether point is before,
14314 at, or after the value of the end of the region. We can use the
14315 @code{point} function to locate point. Clearly, we must pass the
14316 value of the end of the region to the recursive counting function as an
14317 argument.
14318
14319 In addition, the do-again-test should also test whether the search finds a
14320 word. If it does not, the function should not call itself again.
14321
14322 The next-step-expression changes a value so that when the recursive
14323 function is supposed to stop calling itself, it stops. More
14324 precisely, the next-step-expression changes a value so that at the
14325 right time, the do-again-test stops the recursive function from
14326 calling itself again. In this case, the next-step-expression can be
14327 the expression that moves point forward, word by word.
14328
14329 The third part of a recursive function is the recursive call.
14330
14331 Somewhere, also, we also need a part that does the `work' of the
14332 function, a part that does the counting. A vital part!
14333
14334 @need 1250
14335 But already, we have an outline of the recursive counting function:
14336
14337 @smallexample
14338 @group
14339 (defun recursive-count-words (region-end)
14340 "@var{documentation}@dots{}"
14341 @var{do-again-test}
14342 @var{next-step-expression}
14343 @var{recursive call})
14344 @end group
14345 @end smallexample
14346
14347 Now we need to fill in the slots. Let's start with the simplest cases
14348 first: if point is at or beyond the end of the region, there cannot
14349 be any words in the region, so the function should return zero.
14350 Likewise, if the search fails, there are no words to count, so the
14351 function should return zero.
14352
14353 On the other hand, if point is within the region and the search
14354 succeeds, the function should call itself again.
14355
14356 @need 800
14357 Thus, the do-again-test should look like this:
14358
14359 @smallexample
14360 @group
14361 (and (< (point) region-end)
14362 (re-search-forward "\\w+\\W*" region-end t))
14363 @end group
14364 @end smallexample
14365
14366 Note that the search expression is part of the do-again-test---the
14367 function returns @code{t} if its search succeeds and @code{nil} if it
14368 fails. (@xref{Whitespace Bug, , The Whitespace Bug in
14369 @code{@value{COUNT-WORDS}}}, for an explanation of how
14370 @code{re-search-forward} works.)
14371
14372 The do-again-test is the true-or-false test of an @code{if} clause.
14373 Clearly, if the do-again-test succeeds, the then-part of the @code{if}
14374 clause should call the function again; but if it fails, the else-part
14375 should return zero since either point is outside the region or the
14376 search failed because there were no words to find.
14377
14378 But before considering the recursive call, we need to consider the
14379 next-step-expression. What is it? Interestingly, it is the search
14380 part of the do-again-test.
14381
14382 In addition to returning @code{t} or @code{nil} for the
14383 do-again-test, @code{re-search-forward} moves point forward as a side
14384 effect of a successful search. This is the action that changes the
14385 value of point so that the recursive function stops calling itself
14386 when point completes its movement through the region. Consequently,
14387 the @code{re-search-forward} expression is the next-step-expression.
14388
14389 @need 1200
14390 In outline, then, the body of the @code{recursive-count-words}
14391 function looks like this:
14392
14393 @smallexample
14394 @group
14395 (if @var{do-again-test-and-next-step-combined}
14396 ;; @r{then}
14397 @var{recursive-call-returning-count}
14398 ;; @r{else}
14399 @var{return-zero})
14400 @end group
14401 @end smallexample
14402
14403 How to incorporate the mechanism that counts?
14404
14405 If you are not used to writing recursive functions, a question like
14406 this can be troublesome. But it can and should be approached
14407 systematically.
14408
14409 We know that the counting mechanism should be associated in some way
14410 with the recursive call. Indeed, since the next-step-expression moves
14411 point forward by one word, and since a recursive call is made for
14412 each word, the counting mechanism must be an expression that adds one
14413 to the value returned by a call to @code{recursive-count-words}.
14414
14415 @need 800
14416 Consider several cases:
14417
14418 @itemize @bullet
14419 @item
14420 If there are two words in the region, the function should return
14421 a value resulting from adding one to the value returned when it counts
14422 the first word, plus the number returned when it counts the remaining
14423 words in the region, which in this case is one.
14424
14425 @item
14426 If there is one word in the region, the function should return
14427 a value resulting from adding one to the value returned when it counts
14428 that word, plus the number returned when it counts the remaining
14429 words in the region, which in this case is zero.
14430
14431 @item
14432 If there are no words in the region, the function should return zero.
14433 @end itemize
14434
14435 From the sketch we can see that the else-part of the @code{if} returns
14436 zero for the case of no words. This means that the then-part of the
14437 @code{if} must return a value resulting from adding one to the value
14438 returned from a count of the remaining words.
14439
14440 @need 1200
14441 The expression will look like this, where @code{1+} is a function that
14442 adds one to its argument.
14443
14444 @smallexample
14445 (1+ (recursive-count-words region-end))
14446 @end smallexample
14447
14448 @need 1200
14449 The whole @code{recursive-count-words} function will then look like
14450 this:
14451
14452 @smallexample
14453 @group
14454 (defun recursive-count-words (region-end)
14455 "@var{documentation}@dots{}"
14456
14457 ;;; @r{1. do-again-test}
14458 (if (and (< (point) region-end)
14459 (re-search-forward "\\w+\\W*" region-end t))
14460 @end group
14461
14462 @group
14463 ;;; @r{2. then-part: the recursive call}
14464 (1+ (recursive-count-words region-end))
14465
14466 ;;; @r{3. else-part}
14467 0))
14468 @end group
14469 @end smallexample
14470
14471 @need 1250
14472 Let's examine how this works:
14473
14474 If there are no words in the region, the else part of the @code{if}
14475 expression is evaluated and consequently the function returns zero.
14476
14477 If there is one word in the region, the value of point is less than
14478 the value of @code{region-end} and the search succeeds. In this case,
14479 the true-or-false-test of the @code{if} expression tests true, and the
14480 then-part of the @code{if} expression is evaluated. The counting
14481 expression is evaluated. This expression returns a value (which will
14482 be the value returned by the whole function) that is the sum of one
14483 added to the value returned by a recursive call.
14484
14485 Meanwhile, the next-step-expression has caused point to jump over the
14486 first (and in this case only) word in the region. This means that
14487 when @code{(recursive-count-words region-end)} is evaluated a second
14488 time, as a result of the recursive call, the value of point will be
14489 equal to or greater than the value of region end. So this time,
14490 @code{recursive-count-words} will return zero. The zero will be added
14491 to one, and the original evaluation of @code{recursive-count-words}
14492 will return one plus zero, which is one, which is the correct amount.
14493
14494 Clearly, if there are two words in the region, the first call to
14495 @code{recursive-count-words} returns one added to the value returned
14496 by calling @code{recursive-count-words} on a region containing the
14497 remaining word---that is, it adds one to one, producing two, which is
14498 the correct amount.
14499
14500 Similarly, if there are three words in the region, the first call to
14501 @code{recursive-count-words} returns one added to the value returned
14502 by calling @code{recursive-count-words} on a region containing the
14503 remaining two words---and so on and so on.
14504
14505 @need 1250
14506 @noindent
14507 With full documentation the two functions look like this:
14508
14509 @need 1250
14510 @noindent
14511 The recursive function:
14512
14513 @findex recursive-count-words
14514 @smallexample
14515 @group
14516 (defun recursive-count-words (region-end)
14517 "Number of words between point and REGION-END."
14518 @end group
14519
14520 @group
14521 ;;; @r{1. do-again-test}
14522 (if (and (< (point) region-end)
14523 (re-search-forward "\\w+\\W*" region-end t))
14524 @end group
14525
14526 @group
14527 ;;; @r{2. then-part: the recursive call}
14528 (1+ (recursive-count-words region-end))
14529
14530 ;;; @r{3. else-part}
14531 0))
14532 @end group
14533 @end smallexample
14534
14535 @need 800
14536 @noindent
14537 The wrapper:
14538
14539 @smallexample
14540 @group
14541 ;;; @r{Recursive version}
14542 (defun @value{COUNT-WORDS} (beginning end)
14543 "Print number of words in the region.
14544 @end group
14545
14546 @group
14547 Words are defined as at least one word-constituent
14548 character followed by at least one character that is
14549 not a word-constituent. The buffer's syntax table
14550 determines which characters these are."
14551 @end group
14552 @group
14553 (interactive "r")
14554 (message "Counting words in region ... ")
14555 (save-excursion
14556 (goto-char beginning)
14557 (let ((count (recursive-count-words end)))
14558 @end group
14559 @group
14560 (cond ((zerop count)
14561 (message
14562 "The region does NOT have any words."))
14563 @end group
14564 @group
14565 ((= 1 count)
14566 (message "The region has 1 word."))
14567 (t
14568 (message
14569 "The region has %d words." count))))))
14570 @end group
14571 @end smallexample
14572
14573 @node Counting Exercise
14574 @section Exercise: Counting Punctuation
14575
14576 Using a @code{while} loop, write a function to count the number of
14577 punctuation marks in a region---period, comma, semicolon, colon,
14578 exclamation mark, and question mark. Do the same using recursion.
14579
14580 @node Words in a defun
14581 @chapter Counting Words in a @code{defun}
14582 @cindex Counting words in a @code{defun}
14583 @cindex Word counting in a @code{defun}
14584
14585 Our next project is to count the number of words in a function
14586 definition. Clearly, this can be done using some variant of
14587 @code{@value{COUNT-WORDS}}. @xref{Counting Words, , Counting Words:
14588 Repetition and Regexps}. If we are just going to count the words in
14589 one definition, it is easy enough to mark the definition with the
14590 @kbd{C-M-h} (@code{mark-defun}) command, and then call
14591 @code{@value{COUNT-WORDS}}.
14592
14593 However, I am more ambitious: I want to count the words and symbols in
14594 every definition in the Emacs sources and then print a graph that
14595 shows how many functions there are of each length: how many contain 40
14596 to 49 words or symbols, how many contain 50 to 59 words or symbols,
14597 and so on. I have often been curious how long a typical function is,
14598 and this will tell.
14599
14600 @menu
14601 * Divide and Conquer::
14602 * Words and Symbols:: What to count?
14603 * Syntax:: What constitutes a word or symbol?
14604 * count-words-in-defun:: Very like @code{@value{COUNT-WORDS}}.
14605 * Several defuns:: Counting several defuns in a file.
14606 * Find a File:: Do you want to look at a file?
14607 * lengths-list-file:: A list of the lengths of many definitions.
14608 * Several files:: Counting in definitions in different files.
14609 * Several files recursively:: Recursively counting in different files.
14610 * Prepare the data:: Prepare the data for display in a graph.
14611 @end menu
14612
14613 @ifnottex
14614 @node Divide and Conquer
14615 @unnumberedsec Divide and Conquer
14616 @end ifnottex
14617
14618 Described in one phrase, the histogram project is daunting; but
14619 divided into numerous small steps, each of which we can take one at a
14620 time, the project becomes less fearsome. Let us consider what the
14621 steps must be:
14622
14623 @itemize @bullet
14624 @item
14625 First, write a function to count the words in one definition. This
14626 includes the problem of handling symbols as well as words.
14627
14628 @item
14629 Second, write a function to list the numbers of words in each function
14630 in a file. This function can use the @code{count-words-in-defun}
14631 function.
14632
14633 @item
14634 Third, write a function to list the numbers of words in each function
14635 in each of several files. This entails automatically finding the
14636 various files, switching to them, and counting the words in the
14637 definitions within them.
14638
14639 @item
14640 Fourth, write a function to convert the list of numbers that we
14641 created in step three to a form that will be suitable for printing as
14642 a graph.
14643
14644 @item
14645 Fifth, write a function to print the results as a graph.
14646 @end itemize
14647
14648 This is quite a project! But if we take each step slowly, it will not
14649 be difficult.
14650
14651 @node Words and Symbols
14652 @section What to Count?
14653 @cindex Words and symbols in defun
14654
14655 When we first start thinking about how to count the words in a
14656 function definition, the first question is (or ought to be) what are
14657 we going to count? When we speak of `words' with respect to a Lisp
14658 function definition, we are actually speaking, in large part, of
14659 `symbols'. For example, the following @code{multiply-by-seven}
14660 function contains the five symbols @code{defun},
14661 @code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
14662 addition, in the documentation string, it contains the four words
14663 @samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
14664 symbol @samp{number} is repeated, so the definition contains a total
14665 of ten words and symbols.
14666
14667 @smallexample
14668 @group
14669 (defun multiply-by-seven (number)
14670 "Multiply NUMBER by seven."
14671 (* 7 number))
14672 @end group
14673 @end smallexample
14674
14675 @noindent
14676 However, if we mark the @code{multiply-by-seven} definition with
14677 @kbd{C-M-h} (@code{mark-defun}), and then call
14678 @code{@value{COUNT-WORDS}} on it, we will find that
14679 @code{@value{COUNT-WORDS}} claims the definition has eleven words, not
14680 ten! Something is wrong!
14681
14682 The problem is twofold: @code{@value{COUNT-WORDS}} does not count the
14683 @samp{*} as a word, and it counts the single symbol,
14684 @code{multiply-by-seven}, as containing three words. The hyphens are
14685 treated as if they were interword spaces rather than intraword
14686 connectors: @samp{multiply-by-seven} is counted as if it were written
14687 @samp{multiply by seven}.
14688
14689 The cause of this confusion is the regular expression search within
14690 the @code{@value{COUNT-WORDS}} definition that moves point forward word
14691 by word. In the canonical version of @code{@value{COUNT-WORDS}}, the
14692 regexp is:
14693
14694 @smallexample
14695 "\\w+\\W*"
14696 @end smallexample
14697
14698 @noindent
14699 This regular expression is a pattern defining one or more word
14700 constituent characters possibly followed by one or more characters
14701 that are not word constituents. What is meant by `word constituent
14702 characters' brings us to the issue of syntax, which is worth a section
14703 of its own.
14704
14705 @node Syntax
14706 @section What Constitutes a Word or Symbol?
14707 @cindex Syntax categories and tables
14708
14709 Emacs treats different characters as belonging to different
14710 @dfn{syntax categories}. For example, the regular expression,
14711 @samp{\\w+}, is a pattern specifying one or more @emph{word
14712 constituent} characters. Word constituent characters are members of
14713 one syntax category. Other syntax categories include the class of
14714 punctuation characters, such as the period and the comma, and the
14715 class of whitespace characters, such as the blank space and the tab
14716 character. (For more information, @pxref{Syntax Tables, , Syntax
14717 Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
14718
14719 Syntax tables specify which characters belong to which categories.
14720 Usually, a hyphen is not specified as a `word constituent character'.
14721 Instead, it is specified as being in the `class of characters that are
14722 part of symbol names but not words.' This means that the
14723 @code{@value{COUNT-WORDS}} function treats it in the same way it treats
14724 an interword white space, which is why @code{@value{COUNT-WORDS}}
14725 counts @samp{multiply-by-seven} as three words.
14726
14727 There are two ways to cause Emacs to count @samp{multiply-by-seven} as
14728 one symbol: modify the syntax table or modify the regular expression.
14729
14730 We could redefine a hyphen as a word constituent character by
14731 modifying the syntax table that Emacs keeps for each mode. This
14732 action would serve our purpose, except that a hyphen is merely the
14733 most common character within symbols that is not typically a word
14734 constituent character; there are others, too.
14735
14736 Alternatively, we can redefine the regexp used in the
14737 @code{@value{COUNT-WORDS}} definition so as to include symbols. This
14738 procedure has the merit of clarity, but the task is a little tricky.
14739
14740 @need 1200
14741 The first part is simple enough: the pattern must match ``at least one
14742 character that is a word or symbol constituent''. Thus:
14743
14744 @smallexample
14745 "\\(\\w\\|\\s_\\)+"
14746 @end smallexample
14747
14748 @noindent
14749 The @samp{\\(} is the first part of the grouping construct that
14750 includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
14751 by the @samp{\\|}. The @samp{\\w} matches any word-constituent
14752 character and the @samp{\\s_} matches any character that is part of a
14753 symbol name but not a word-constituent character. The @samp{+}
14754 following the group indicates that the word or symbol constituent
14755 characters must be matched at least once.
14756
14757 However, the second part of the regexp is more difficult to design.
14758 What we want is to follow the first part with ``optionally one or more
14759 characters that are not constituents of a word or symbol''. At first,
14760 I thought I could define this with the following:
14761
14762 @smallexample
14763 "\\(\\W\\|\\S_\\)*"
14764 @end smallexample
14765
14766 @noindent
14767 The upper case @samp{W} and @samp{S} match characters that are
14768 @emph{not} word or symbol constituents. Unfortunately, this
14769 expression matches any character that is either not a word constituent
14770 or not a symbol constituent. This matches any character!
14771
14772 I then noticed that every word or symbol in my test region was
14773 followed by white space (blank space, tab, or newline). So I tried
14774 placing a pattern to match one or more blank spaces after the pattern
14775 for one or more word or symbol constituents. This failed, too. Words
14776 and symbols are often separated by whitespace, but in actual code
14777 parentheses may follow symbols and punctuation may follow words. So
14778 finally, I designed a pattern in which the word or symbol constituents
14779 are followed optionally by characters that are not white space and
14780 then followed optionally by white space.
14781
14782 @need 800
14783 Here is the full regular expression:
14784
14785 @smallexample
14786 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14787 @end smallexample
14788
14789 @node count-words-in-defun
14790 @section The @code{count-words-in-defun} Function
14791 @cindex Counting words in a @code{defun}
14792
14793 We have seen that there are several ways to write a
14794 @code{count-words-region} function. To write a
14795 @code{count-words-in-defun}, we need merely adapt one of these
14796 versions.
14797
14798 The version that uses a @code{while} loop is easy to understand, so I
14799 am going to adapt that. Because @code{count-words-in-defun} will be
14800 part of a more complex program, it need not be interactive and it need
14801 not display a message but just return the count. These considerations
14802 simplify the definition a little.
14803
14804 On the other hand, @code{count-words-in-defun} will be used within a
14805 buffer that contains function definitions. Consequently, it is
14806 reasonable to ask that the function determine whether it is called
14807 when point is within a function definition, and if it is, to return
14808 the count for that definition. This adds complexity to the
14809 definition, but saves us from needing to pass arguments to the
14810 function.
14811
14812 @need 1250
14813 These considerations lead us to prepare the following template:
14814
14815 @smallexample
14816 @group
14817 (defun count-words-in-defun ()
14818 "@var{documentation}@dots{}"
14819 (@var{set up}@dots{}
14820 (@var{while loop}@dots{})
14821 @var{return count})
14822 @end group
14823 @end smallexample
14824
14825 @noindent
14826 As usual, our job is to fill in the slots.
14827
14828 First, the set up.
14829
14830 We are presuming that this function will be called within a buffer
14831 containing function definitions. Point will either be within a
14832 function definition or not. For @code{count-words-in-defun} to work,
14833 point must move to the beginning of the definition, a counter must
14834 start at zero, and the counting loop must stop when point reaches the
14835 end of the definition.
14836
14837 The @code{beginning-of-defun} function searches backwards for an
14838 opening delimiter such as a @samp{(} at the beginning of a line, and
14839 moves point to that position, or else to the limit of the search. In
14840 practice, this means that @code{beginning-of-defun} moves point to the
14841 beginning of an enclosing or preceding function definition, or else to
14842 the beginning of the buffer. We can use @code{beginning-of-defun} to
14843 place point where we wish to start.
14844
14845 The @code{while} loop requires a counter to keep track of the words or
14846 symbols being counted. A @code{let} expression can be used to create
14847 a local variable for this purpose, and bind it to an initial value of zero.
14848
14849 The @code{end-of-defun} function works like @code{beginning-of-defun}
14850 except that it moves point to the end of the definition.
14851 @code{end-of-defun} can be used as part of an expression that
14852 determines the position of the end of the definition.
14853
14854 The set up for @code{count-words-in-defun} takes shape rapidly: first
14855 we move point to the beginning of the definition, then we create a
14856 local variable to hold the count, and finally, we record the position
14857 of the end of the definition so the @code{while} loop will know when to stop
14858 looping.
14859
14860 @need 1250
14861 The code looks like this:
14862
14863 @smallexample
14864 @group
14865 (beginning-of-defun)
14866 (let ((count 0)
14867 (end (save-excursion (end-of-defun) (point))))
14868 @end group
14869 @end smallexample
14870
14871 @noindent
14872 The code is simple. The only slight complication is likely to concern
14873 @code{end}: it is bound to the position of the end of the definition
14874 by a @code{save-excursion} expression that returns the value of point
14875 after @code{end-of-defun} temporarily moves it to the end of the
14876 definition.
14877
14878 The second part of the @code{count-words-in-defun}, after the set up,
14879 is the @code{while} loop.
14880
14881 The loop must contain an expression that jumps point forward word by
14882 word and symbol by symbol, and another expression that counts the
14883 jumps. The true-or-false-test for the @code{while} loop should test
14884 true so long as point should jump forward, and false when point is at
14885 the end of the definition. We have already redefined the regular
14886 expression for this, so the loop is straightforward:
14887
14888 @smallexample
14889 @group
14890 (while (and (< (point) end)
14891 (re-search-forward
14892 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t))
14893 (setq count (1+ count)))
14894 @end group
14895 @end smallexample
14896
14897 The third part of the function definition returns the count of words
14898 and symbols. This part is the last expression within the body of the
14899 @code{let} expression, and can be, very simply, the local variable
14900 @code{count}, which when evaluated returns the count.
14901
14902 @need 1250
14903 Put together, the @code{count-words-in-defun} definition looks like this:
14904
14905 @findex count-words-in-defun
14906 @smallexample
14907 @group
14908 (defun count-words-in-defun ()
14909 "Return the number of words and symbols in a defun."
14910 (beginning-of-defun)
14911 (let ((count 0)
14912 (end (save-excursion (end-of-defun) (point))))
14913 @end group
14914 @group
14915 (while
14916 (and (< (point) end)
14917 (re-search-forward
14918 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14919 end t))
14920 (setq count (1+ count)))
14921 count))
14922 @end group
14923 @end smallexample
14924
14925 How to test this? The function is not interactive, but it is easy to
14926 put a wrapper around the function to make it interactive; we can use
14927 almost the same code as for the recursive version of
14928 @code{@value{COUNT-WORDS}}:
14929
14930 @smallexample
14931 @group
14932 ;;; @r{Interactive version.}
14933 (defun count-words-defun ()
14934 "Number of words and symbols in a function definition."
14935 (interactive)
14936 (message
14937 "Counting words and symbols in function definition ... ")
14938 @end group
14939 @group
14940 (let ((count (count-words-in-defun)))
14941 (cond
14942 ((zerop count)
14943 (message
14944 "The definition does NOT have any words or symbols."))
14945 @end group
14946 @group
14947 ((= 1 count)
14948 (message
14949 "The definition has 1 word or symbol."))
14950 (t
14951 (message
14952 "The definition has %d words or symbols." count)))))
14953 @end group
14954 @end smallexample
14955
14956 @need 800
14957 @noindent
14958 Let's re-use @kbd{C-c =} as a convenient keybinding:
14959
14960 @smallexample
14961 (global-set-key "\C-c=" 'count-words-defun)
14962 @end smallexample
14963
14964 Now we can try out @code{count-words-defun}: install both
14965 @code{count-words-in-defun} and @code{count-words-defun}, and set the
14966 keybinding, and then place the cursor within the following definition:
14967
14968 @smallexample
14969 @group
14970 (defun multiply-by-seven (number)
14971 "Multiply NUMBER by seven."
14972 (* 7 number))
14973 @result{} 10
14974 @end group
14975 @end smallexample
14976
14977 @noindent
14978 Success! The definition has 10 words and symbols.
14979
14980 The next problem is to count the numbers of words and symbols in
14981 several definitions within a single file.
14982
14983 @node Several defuns
14984 @section Count Several @code{defuns} Within a File
14985
14986 A file such as @file{simple.el} may have a hundred or more function
14987 definitions within it. Our long term goal is to collect statistics on
14988 many files, but as a first step, our immediate goal is to collect
14989 statistics on one file.
14990
14991 The information will be a series of numbers, each number being the
14992 length of a function definition. We can store the numbers in a list.
14993
14994 We know that we will want to incorporate the information regarding one
14995 file with information about many other files; this means that the
14996 function for counting definition lengths within one file need only
14997 return the list of lengths. It need not and should not display any
14998 messages.
14999
15000 The word count commands contain one expression to jump point forward
15001 word by word and another expression to count the jumps. The function
15002 to return the lengths of definitions can be designed to work the same
15003 way, with one expression to jump point forward definition by
15004 definition and another expression to construct the lengths' list.
15005
15006 This statement of the problem makes it elementary to write the
15007 function definition. Clearly, we will start the count at the
15008 beginning of the file, so the first command will be @code{(goto-char
15009 (point-min))}. Next, we start the @code{while} loop; and the
15010 true-or-false test of the loop can be a regular expression search for
15011 the next function definition---so long as the search succeeds, point
15012 is moved forward and then the body of the loop is evaluated. The body
15013 needs an expression that constructs the lengths' list. @code{cons},
15014 the list construction command, can be used to create the list. That
15015 is almost all there is to it.
15016
15017 @need 800
15018 Here is what this fragment of code looks like:
15019
15020 @smallexample
15021 @group
15022 (goto-char (point-min))
15023 (while (re-search-forward "^(defun" nil t)
15024 (setq lengths-list
15025 (cons (count-words-in-defun) lengths-list)))
15026 @end group
15027 @end smallexample
15028
15029 What we have left out is the mechanism for finding the file that
15030 contains the function definitions.
15031
15032 In previous examples, we either used this, the Info file, or we
15033 switched back and forth to some other buffer, such as the
15034 @file{*scratch*} buffer.
15035
15036 Finding a file is a new process that we have not yet discussed.
15037
15038 @node Find a File
15039 @section Find a File
15040 @cindex Find a File
15041
15042 To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
15043 command. This command is almost, but not quite right for the lengths
15044 problem.
15045
15046 @need 1200
15047 Let's look at the source for @code{find-file}:
15048
15049 @smallexample
15050 @group
15051 (defun find-file (filename)
15052 "Edit file FILENAME.
15053 Switch to a buffer visiting file FILENAME,
15054 creating one if none already exists."
15055 (interactive "FFind file: ")
15056 (switch-to-buffer (find-file-noselect filename)))
15057 @end group
15058 @end smallexample
15059
15060 @noindent
15061 (The most recent version of the @code{find-file} function definition
15062 permits you to specify optional wildcards to visit multiple files; that
15063 makes the definition more complex and we will not discuss it here,
15064 since it is not relevant. You can see its source using either
15065 @kbd{M-.} (@code{find-tag}) or @kbd{C-h f} (@code{describe-function}).)
15066
15067 @ignore
15068 In Emacs 22
15069 (defun find-file (filename &optional wildcards)
15070 "Edit file FILENAME.
15071 Switch to a buffer visiting file FILENAME,
15072 creating one if none already exists.
15073 Interactively, the default if you just type RET is the current directory,
15074 but the visited file name is available through the minibuffer history:
15075 type M-n to pull it into the minibuffer.
15076
15077 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
15078 expand wildcards (if any) and visit multiple files. You can
15079 suppress wildcard expansion by setting `find-file-wildcards' to nil.
15080
15081 To visit a file without any kind of conversion and without
15082 automatically choosing a major mode, use \\[find-file-literally]."
15083 (interactive (find-file-read-args "Find file: " nil))
15084 (let ((value (find-file-noselect filename nil nil wildcards)))
15085 (if (listp value)
15086 (mapcar 'switch-to-buffer (nreverse value))
15087 (switch-to-buffer value))))
15088 @end ignore
15089
15090 The definition I am showing possesses short but complete documentation
15091 and an interactive specification that prompts you for a file name when
15092 you use the command interactively. The body of the definition
15093 contains two functions, @code{find-file-noselect} and
15094 @code{switch-to-buffer}.
15095
15096 According to its documentation as shown by @kbd{C-h f} (the
15097 @code{describe-function} command), the @code{find-file-noselect}
15098 function reads the named file into a buffer and returns the buffer.
15099 (Its most recent version includes an optional wildcards argument,
15100 too, as well as another to read a file literally and an other you
15101 suppress warning messages. These optional arguments are irrelevant.)
15102
15103 However, the @code{find-file-noselect} function does not select the
15104 buffer in which it puts the file. Emacs does not switch its attention
15105 (or yours if you are using @code{find-file-noselect}) to the selected
15106 buffer. That is what @code{switch-to-buffer} does: it switches the
15107 buffer to which Emacs attention is directed; and it switches the
15108 buffer displayed in the window to the new buffer. We have discussed
15109 buffer switching elsewhere. (@xref{Switching Buffers}.)
15110
15111 In this histogram project, we do not need to display each file on the
15112 screen as the program determines the length of each definition within
15113 it. Instead of employing @code{switch-to-buffer}, we can work with
15114 @code{set-buffer}, which redirects the attention of the computer
15115 program to a different buffer but does not redisplay it on the screen.
15116 So instead of calling on @code{find-file} to do the job, we must write
15117 our own expression.
15118
15119 The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
15120
15121 @node lengths-list-file
15122 @section @code{lengths-list-file} in Detail
15123
15124 The core of the @code{lengths-list-file} function is a @code{while}
15125 loop containing a function to move point forward `defun by defun' and
15126 a function to count the number of words and symbols in each defun.
15127 This core must be surrounded by functions that do various other tasks,
15128 including finding the file, and ensuring that point starts out at the
15129 beginning of the file. The function definition looks like this:
15130 @findex lengths-list-file
15131
15132 @smallexample
15133 @group
15134 (defun lengths-list-file (filename)
15135 "Return list of definitions' lengths within FILE.
15136 The returned list is a list of numbers.
15137 Each number is the number of words or
15138 symbols in one function definition."
15139 @end group
15140 @group
15141 (message "Working on `%s' ... " filename)
15142 (save-excursion
15143 (let ((buffer (find-file-noselect filename))
15144 (lengths-list))
15145 (set-buffer buffer)
15146 (setq buffer-read-only t)
15147 (widen)
15148 (goto-char (point-min))
15149 (while (re-search-forward "^(defun" nil t)
15150 (setq lengths-list
15151 (cons (count-words-in-defun) lengths-list)))
15152 (kill-buffer buffer)
15153 lengths-list)))
15154 @end group
15155 @end smallexample
15156
15157 @noindent
15158 The function is passed one argument, the name of the file on which it
15159 will work. It has four lines of documentation, but no interactive
15160 specification. Since people worry that a computer is broken if they
15161 don't see anything going on, the first line of the body is a
15162 message.
15163
15164 The next line contains a @code{save-excursion} that returns Emacs's
15165 attention to the current buffer when the function completes. This is
15166 useful in case you embed this function in another function that
15167 presumes point is restored to the original buffer.
15168
15169 In the varlist of the @code{let} expression, Emacs finds the file and
15170 binds the local variable @code{buffer} to the buffer containing the
15171 file. At the same time, Emacs creates @code{lengths-list} as a local
15172 variable.
15173
15174 Next, Emacs switches its attention to the buffer.
15175
15176 In the following line, Emacs makes the buffer read-only. Ideally,
15177 this line is not necessary. None of the functions for counting words
15178 and symbols in a function definition should change the buffer.
15179 Besides, the buffer is not going to be saved, even if it were changed.
15180 This line is entirely the consequence of great, perhaps excessive,
15181 caution. The reason for the caution is that this function and those
15182 it calls work on the sources for Emacs and it is inconvenient if they
15183 are inadvertently modified. It goes without saying that I did not
15184 realize a need for this line until an experiment went awry and started
15185 to modify my Emacs source files @dots{}
15186
15187 Next comes a call to widen the buffer if it is narrowed. This
15188 function is usually not needed---Emacs creates a fresh buffer if none
15189 already exists; but if a buffer visiting the file already exists Emacs
15190 returns that one. In this case, the buffer may be narrowed and must
15191 be widened. If we wanted to be fully `user-friendly', we would
15192 arrange to save the restriction and the location of point, but we
15193 won't.
15194
15195 The @code{(goto-char (point-min))} expression moves point to the
15196 beginning of the buffer.
15197
15198 Then comes a @code{while} loop in which the `work' of the function is
15199 carried out. In the loop, Emacs determines the length of each
15200 definition and constructs a lengths' list containing the information.
15201
15202 Emacs kills the buffer after working through it. This is to save
15203 space inside of Emacs. My version of GNU Emacs 19 contained over 300
15204 source files of interest; GNU Emacs 22 contains over a thousand source
15205 files. Another function will apply @code{lengths-list-file} to each
15206 of the files.
15207
15208 Finally, the last expression within the @code{let} expression is the
15209 @code{lengths-list} variable; its value is returned as the value of
15210 the whole function.
15211
15212 You can try this function by installing it in the usual fashion. Then
15213 place your cursor after the following expression and type @kbd{C-x
15214 C-e} (@code{eval-last-sexp}).
15215
15216 @c !!! 22.1.1 lisp sources location here
15217 @smallexample
15218 (lengths-list-file
15219 "/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el")
15220 @end smallexample
15221
15222 @noindent
15223 (You may need to change the pathname of the file; the one here is for
15224 GNU Emacs version 22.1.1. To change the expression, copy it to
15225 the @file{*scratch*} buffer and edit it.
15226
15227 @need 1200
15228 @noindent
15229 (Also, to see the full length of the list, rather than a truncated
15230 version, you may have to evaluate the following:
15231
15232 @smallexample
15233 (custom-set-variables '(eval-expression-print-length nil))
15234 @end smallexample
15235
15236 @noindent
15237 (@xref{defcustom, , Specifying Variables using @code{defcustom}}.
15238 Then evaluate the @code{lengths-list-file} expression.)
15239
15240 @need 1200
15241 The lengths' list for @file{debug.el} takes less than a second to
15242 produce and looks like this in GNU Emacs 22:
15243
15244 @smallexample
15245 (83 113 105 144 289 22 30 97 48 89 25 52 52 88 28 29 77 49 43 290 232 587)
15246 @end smallexample
15247
15248 @need 1500
15249 (Using my old machine, the version 19 lengths' list for @file{debug.el}
15250 took seven seconds to produce and looked like this:
15251
15252 @smallexample
15253 (75 41 80 62 20 45 44 68 45 12 34 235)
15254 @end smallexample
15255
15256 (The newer version of @file{debug.el} contains more defuns than the
15257 earlier one; and my new machine is much faster than the old one.)
15258
15259 Note that the length of the last definition in the file is first in
15260 the list.
15261
15262 @node Several files
15263 @section Count Words in @code{defuns} in Different Files
15264
15265 In the previous section, we created a function that returns a list of
15266 the lengths of each definition in a file. Now, we want to define a
15267 function to return a master list of the lengths of the definitions in
15268 a list of files.
15269
15270 Working on each of a list of files is a repetitious act, so we can use
15271 either a @code{while} loop or recursion.
15272
15273 @menu
15274 * lengths-list-many-files:: Return a list of the lengths of defuns.
15275 * append:: Attach one list to another.
15276 @end menu
15277
15278 @ifnottex
15279 @node lengths-list-many-files
15280 @unnumberedsubsec Determine the lengths of @code{defuns}
15281 @end ifnottex
15282
15283 The design using a @code{while} loop is routine. The argument passed
15284 the function is a list of files. As we saw earlier (@pxref{Loop
15285 Example}), you can write a @code{while} loop so that the body of the
15286 loop is evaluated if such a list contains elements, but to exit the
15287 loop if the list is empty. For this design to work, the body of the
15288 loop must contain an expression that shortens the list each time the
15289 body is evaluated, so that eventually the list is empty. The usual
15290 technique is to set the value of the list to the value of the @sc{cdr}
15291 of the list each time the body is evaluated.
15292
15293 @need 800
15294 The template looks like this:
15295
15296 @smallexample
15297 @group
15298 (while @var{test-whether-list-is-empty}
15299 @var{body}@dots{}
15300 @var{set-list-to-cdr-of-list})
15301 @end group
15302 @end smallexample
15303
15304 Also, we remember that a @code{while} loop returns @code{nil} (the
15305 result of evaluating the true-or-false-test), not the result of any
15306 evaluation within its body. (The evaluations within the body of the
15307 loop are done for their side effects.) However, the expression that
15308 sets the lengths' list is part of the body---and that is the value
15309 that we want returned by the function as a whole. To do this, we
15310 enclose the @code{while} loop within a @code{let} expression, and
15311 arrange that the last element of the @code{let} expression contains
15312 the value of the lengths' list. (@xref{Incrementing Example, , Loop
15313 Example with an Incrementing Counter}.)
15314
15315 @findex lengths-list-many-files
15316 @need 1250
15317 These considerations lead us directly to the function itself:
15318
15319 @smallexample
15320 @group
15321 ;;; @r{Use @code{while} loop.}
15322 (defun lengths-list-many-files (list-of-files)
15323 "Return list of lengths of defuns in LIST-OF-FILES."
15324 @end group
15325 @group
15326 (let (lengths-list)
15327
15328 ;;; @r{true-or-false-test}
15329 (while list-of-files
15330 (setq lengths-list
15331 (append
15332 lengths-list
15333
15334 ;;; @r{Generate a lengths' list.}
15335 (lengths-list-file
15336 (expand-file-name (car list-of-files)))))
15337 @end group
15338
15339 @group
15340 ;;; @r{Make files' list shorter.}
15341 (setq list-of-files (cdr list-of-files)))
15342
15343 ;;; @r{Return final value of lengths' list.}
15344 lengths-list))
15345 @end group
15346 @end smallexample
15347
15348 @code{expand-file-name} is a built-in function that converts a file
15349 name to the absolute, long, path name form. The function employs the
15350 name of the directory in which the function is called.
15351
15352 @c !!! 22.1.1 lisp sources location here
15353 @need 1500
15354 Thus, if @code{expand-file-name} is called on @code{debug.el} when
15355 Emacs is visiting the
15356 @file{/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/} directory,
15357
15358 @smallexample
15359 debug.el
15360 @end smallexample
15361
15362 @need 800
15363 @noindent
15364 becomes
15365
15366 @c !!! 22.1.1 lisp sources location here
15367 @smallexample
15368 /usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el
15369 @end smallexample
15370
15371 The only other new element of this function definition is the as yet
15372 unstudied function @code{append}, which merits a short section for
15373 itself.
15374
15375 @node append
15376 @subsection The @code{append} Function
15377
15378 @need 800
15379 The @code{append} function attaches one list to another. Thus,
15380
15381 @smallexample
15382 (append '(1 2 3 4) '(5 6 7 8))
15383 @end smallexample
15384
15385 @need 800
15386 @noindent
15387 produces the list
15388
15389 @smallexample
15390 (1 2 3 4 5 6 7 8)
15391 @end smallexample
15392
15393 This is exactly how we want to attach two lengths' lists produced by
15394 @code{lengths-list-file} to each other. The results contrast with
15395 @code{cons},
15396
15397 @smallexample
15398 (cons '(1 2 3 4) '(5 6 7 8))
15399 @end smallexample
15400
15401 @need 1250
15402 @noindent
15403 which constructs a new list in which the first argument to @code{cons}
15404 becomes the first element of the new list:
15405
15406 @smallexample
15407 ((1 2 3 4) 5 6 7 8)
15408 @end smallexample
15409
15410 @node Several files recursively
15411 @section Recursively Count Words in Different Files
15412
15413 Besides a @code{while} loop, you can work on each of a list of files
15414 with recursion. A recursive version of @code{lengths-list-many-files}
15415 is short and simple.
15416
15417 The recursive function has the usual parts: the `do-again-test', the
15418 `next-step-expression', and the recursive call. The `do-again-test'
15419 determines whether the function should call itself again, which it
15420 will do if the @code{list-of-files} contains any remaining elements;
15421 the `next-step-expression' resets the @code{list-of-files} to the
15422 @sc{cdr} of itself, so eventually the list will be empty; and the
15423 recursive call calls itself on the shorter list. The complete
15424 function is shorter than this description!
15425 @findex recursive-lengths-list-many-files
15426
15427 @smallexample
15428 @group
15429 (defun recursive-lengths-list-many-files (list-of-files)
15430 "Return list of lengths of each defun in LIST-OF-FILES."
15431 (if list-of-files ; @r{do-again-test}
15432 (append
15433 (lengths-list-file
15434 (expand-file-name (car list-of-files)))
15435 (recursive-lengths-list-many-files
15436 (cdr list-of-files)))))
15437 @end group
15438 @end smallexample
15439
15440 @noindent
15441 In a sentence, the function returns the lengths' list for the first of
15442 the @code{list-of-files} appended to the result of calling itself on
15443 the rest of the @code{list-of-files}.
15444
15445 Here is a test of @code{recursive-lengths-list-many-files}, along with
15446 the results of running @code{lengths-list-file} on each of the files
15447 individually.
15448
15449 Install @code{recursive-lengths-list-many-files} and
15450 @code{lengths-list-file}, if necessary, and then evaluate the
15451 following expressions. You may need to change the files' pathnames;
15452 those here work when this Info file and the Emacs sources are located
15453 in their customary places. To change the expressions, copy them to
15454 the @file{*scratch*} buffer, edit them, and then evaluate them.
15455
15456 The results are shown after the @samp{@result{}}. (These results are
15457 for files from Emacs version 22.1.1; files from other versions of
15458 Emacs may produce different results.)
15459
15460 @c !!! 22.1.1 lisp sources location here
15461 @smallexample
15462 @group
15463 (cd "/usr/local/share/emacs/22.1.1/")
15464
15465 (lengths-list-file "./lisp/macros.el")
15466 @result{} (283 263 480 90)
15467 @end group
15468
15469 @group
15470 (lengths-list-file "./lisp/mail/mailalias.el")
15471 @result{} (38 32 29 95 178 180 321 218 324)
15472 @end group
15473
15474 @group
15475 (lengths-list-file "./lisp/makesum.el")
15476 @result{} (85 181)
15477 @end group
15478
15479 @group
15480 (recursive-lengths-list-many-files
15481 '("./lisp/macros.el"
15482 "./lisp/mail/mailalias.el"
15483 "./lisp/makesum.el"))
15484 @result{} (283 263 480 90 38 32 29 95 178 180 321 218 324 85 181)
15485 @end group
15486 @end smallexample
15487
15488 The @code{recursive-lengths-list-many-files} function produces the
15489 output we want.
15490
15491 The next step is to prepare the data in the list for display in a graph.
15492
15493 @node Prepare the data
15494 @section Prepare the Data for Display in a Graph
15495
15496 The @code{recursive-lengths-list-many-files} function returns a list
15497 of numbers. Each number records the length of a function definition.
15498 What we need to do now is transform this data into a list of numbers
15499 suitable for generating a graph. The new list will tell how many
15500 functions definitions contain less than 10 words and
15501 symbols, how many contain between 10 and 19 words and symbols, how
15502 many contain between 20 and 29 words and symbols, and so on.
15503
15504 In brief, we need to go through the lengths' list produced by the
15505 @code{recursive-lengths-list-many-files} function and count the number
15506 of defuns within each range of lengths, and produce a list of those
15507 numbers.
15508
15509 @menu
15510 * Data for Display in Detail::
15511 * Sorting:: Sorting lists.
15512 * Files List:: Making a list of files.
15513 * Counting function definitions::
15514 @end menu
15515
15516 @ifnottex
15517 @node Data for Display in Detail
15518 @unnumberedsubsec The Data for Display in Detail
15519 @end ifnottex
15520
15521 Based on what we have done before, we can readily foresee that it
15522 should not be too hard to write a function that `@sc{cdr}s' down the
15523 lengths' list, looks at each element, determines which length range it
15524 is in, and increments a counter for that range.
15525
15526 However, before beginning to write such a function, we should consider
15527 the advantages of sorting the lengths' list first, so the numbers are
15528 ordered from smallest to largest. First, sorting will make it easier
15529 to count the numbers in each range, since two adjacent numbers will
15530 either be in the same length range or in adjacent ranges. Second, by
15531 inspecting a sorted list, we can discover the highest and lowest
15532 number, and thereby determine the largest and smallest length range
15533 that we will need.
15534
15535 @node Sorting
15536 @subsection Sorting Lists
15537 @findex sort
15538
15539 Emacs contains a function to sort lists, called (as you might guess)
15540 @code{sort}. The @code{sort} function takes two arguments, the list
15541 to be sorted, and a predicate that determines whether the first of
15542 two list elements is ``less'' than the second.
15543
15544 As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
15545 Type Object as an Argument}), a predicate is a function that
15546 determines whether some property is true or false. The @code{sort}
15547 function will reorder a list according to whatever property the
15548 predicate uses; this means that @code{sort} can be used to sort
15549 non-numeric lists by non-numeric criteria---it can, for example,
15550 alphabetize a list.
15551
15552 @need 1250
15553 The @code{<} function is used when sorting a numeric list. For example,
15554
15555 @smallexample
15556 (sort '(4 8 21 17 33 7 21 7) '<)
15557 @end smallexample
15558
15559 @need 800
15560 @noindent
15561 produces this:
15562
15563 @smallexample
15564 (4 7 7 8 17 21 21 33)
15565 @end smallexample
15566
15567 @noindent
15568 (Note that in this example, both the arguments are quoted so that the
15569 symbols are not evaluated before being passed to @code{sort} as
15570 arguments.)
15571
15572 Sorting the list returned by the
15573 @code{recursive-lengths-list-many-files} function is straightforward;
15574 it uses the @code{<} function:
15575
15576 @ignore
15577 2006 Oct 29
15578 In GNU Emacs 22, eval
15579 (progn
15580 (cd "/usr/local/share/emacs/22.0.50/")
15581 (sort
15582 (recursive-lengths-list-many-files
15583 '("./lisp/macros.el"
15584 "./lisp/mail/mailalias.el"
15585 "./lisp/makesum.el"))
15586 '<))
15587
15588 @end ignore
15589
15590 @smallexample
15591 @group
15592 (sort
15593 (recursive-lengths-list-many-files
15594 '("./lisp/macros.el"
15595 "./lisp/mailalias.el"
15596 "./lisp/makesum.el"))
15597 '<)
15598 @end group
15599 @end smallexample
15600
15601 @need 800
15602 @noindent
15603 which produces:
15604
15605 @smallexample
15606 (29 32 38 85 90 95 178 180 181 218 263 283 321 324 480)
15607 @end smallexample
15608
15609 @noindent
15610 (Note that in this example, the first argument to @code{sort} is not
15611 quoted, since the expression must be evaluated so as to produce the
15612 list that is passed to @code{sort}.)
15613
15614 @node Files List
15615 @subsection Making a List of Files
15616
15617 The @code{recursive-lengths-list-many-files} function requires a list
15618 of files as its argument. For our test examples, we constructed such
15619 a list by hand; but the Emacs Lisp source directory is too large for
15620 us to do for that. Instead, we will write a function to do the job
15621 for us. In this function, we will use both a @code{while} loop and a
15622 recursive call.
15623
15624 @findex directory-files
15625 We did not have to write a function like this for older versions of
15626 GNU Emacs, since they placed all the @samp{.el} files in one
15627 directory. Instead, we were able to use the @code{directory-files}
15628 function, which lists the names of files that match a specified
15629 pattern within a single directory.
15630
15631 However, recent versions of Emacs place Emacs Lisp files in
15632 sub-directories of the top level @file{lisp} directory. This
15633 re-arrangement eases navigation. For example, all the mail related
15634 files are in a @file{lisp} sub-directory called @file{mail}. But at
15635 the same time, this arrangement forces us to create a file listing
15636 function that descends into the sub-directories.
15637
15638 @findex files-in-below-directory
15639 We can create this function, called @code{files-in-below-directory},
15640 using familiar functions such as @code{car}, @code{nthcdr}, and
15641 @code{substring} in conjunction with an existing function called
15642 @code{directory-files-and-attributes}. This latter function not only
15643 lists all the filenames in a directory, including the names
15644 of sub-directories, but also their attributes.
15645
15646 To restate our goal: to create a function that will enable us
15647 to feed filenames to @code{recursive-lengths-list-many-files}
15648 as a list that looks like this (but with more elements):
15649
15650 @smallexample
15651 @group
15652 ("./lisp/macros.el"
15653 "./lisp/mail/rmail.el"
15654 "./lisp/makesum.el")
15655 @end group
15656 @end smallexample
15657
15658 The @code{directory-files-and-attributes} function returns a list of
15659 lists. Each of the lists within the main list consists of 13
15660 elements. The first element is a string that contains the name of the
15661 file---which, in GNU/Linux, may be a `directory file', that is to
15662 say, a file with the special attributes of a directory. The second
15663 element of the list is @code{t} for a directory, a string
15664 for symbolic link (the string is the name linked to), or @code{nil}.
15665
15666 For example, the first @samp{.el} file in the @file{lisp/} directory
15667 is @file{abbrev.el}. Its name is
15668 @file{/usr/local/share/emacs/22.1.1/lisp/abbrev.el} and it is not a
15669 directory or a symbolic link.
15670
15671 @need 1000
15672 This is how @code{directory-files-and-attributes} lists that file and
15673 its attributes:
15674
15675 @smallexample
15676 @group
15677 ("abbrev.el"
15678 nil
15679 1
15680 1000
15681 100
15682 @end group
15683 @group
15684 (20615 27034 579989 697000)
15685 (17905 55681 0 0)
15686 (20615 26327 734791 805000)
15687 13188
15688 "-rw-r--r--"
15689 @end group
15690 @group
15691 t
15692 2971624
15693 773)
15694 @end group
15695 @end smallexample
15696
15697 @need 1200
15698 On the other hand, @file{mail/} is a directory within the @file{lisp/}
15699 directory. The beginning of its listing looks like this:
15700
15701 @smallexample
15702 @group
15703 ("mail"
15704 t
15705 @dots{}
15706 )
15707 @end group
15708 @end smallexample
15709
15710 (To learn about the different attributes, look at the documentation of
15711 @code{file-attributes}. Bear in mind that the @code{file-attributes}
15712 function does not list the filename, so its first element is
15713 @code{directory-files-and-attributes}'s second element.)
15714
15715 We will want our new function, @code{files-in-below-directory}, to
15716 list the @samp{.el} files in the directory it is told to check, and in
15717 any directories below that directory.
15718
15719 This gives us a hint on how to construct
15720 @code{files-in-below-directory}: within a directory, the function
15721 should add @samp{.el} filenames to a list; and if, within a directory,
15722 the function comes upon a sub-directory, it should go into that
15723 sub-directory and repeat its actions.
15724
15725 However, we should note that every directory contains a name that
15726 refers to itself, called @file{.}, (``dot'') and a name that refers to
15727 its parent directory, called @file{..} (``double dot''). (In
15728 @file{/}, the root directory, @file{..} refers to itself, since
15729 @file{/} has no parent.) Clearly, we do not want our
15730 @code{files-in-below-directory} function to enter those directories,
15731 since they always lead us, directly or indirectly, to the current
15732 directory.
15733
15734 Consequently, our @code{files-in-below-directory} function must do
15735 several tasks:
15736
15737 @itemize @bullet
15738 @item
15739 Check to see whether it is looking at a filename that ends in
15740 @samp{.el}; and if so, add its name to a list.
15741
15742 @item
15743 Check to see whether it is looking at a filename that is the name of a
15744 directory; and if so,
15745
15746 @itemize @minus
15747 @item
15748 Check to see whether it is looking at @file{.} or @file{..}; and if
15749 so skip it.
15750
15751 @item
15752 Or else, go into that directory and repeat the process.
15753 @end itemize
15754 @end itemize
15755
15756 Let's write a function definition to do these tasks. We will use a
15757 @code{while} loop to move from one filename to another within a
15758 directory, checking what needs to be done; and we will use a recursive
15759 call to repeat the actions on each sub-directory. The recursive
15760 pattern is `accumulate'
15761 (@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
15762 using @code{append} as the combiner.
15763
15764 @ignore
15765 (directory-files "/usr/local/src/emacs/lisp/" t "\\.el$")
15766 (shell-command "find /usr/local/src/emacs/lisp/ -name '*.el'")
15767
15768 (directory-files "/usr/local/share/emacs/22.1.1/lisp/" t "\\.el$")
15769 (shell-command "find /usr/local/share/emacs/22.1.1/lisp/ -name '*.el'")
15770 @end ignore
15771
15772 @c /usr/local/share/emacs/22.1.1/lisp/
15773
15774 @need 800
15775 Here is the function:
15776
15777 @smallexample
15778 @group
15779 (defun files-in-below-directory (directory)
15780 "List the .el files in DIRECTORY and in its sub-directories."
15781 ;; Although the function will be used non-interactively,
15782 ;; it will be easier to test if we make it interactive.
15783 ;; The directory will have a name such as
15784 ;; "/usr/local/share/emacs/22.1.1/lisp/"
15785 (interactive "DDirectory name: ")
15786 @end group
15787 @group
15788 (let (el-files-list
15789 (current-directory-list
15790 (directory-files-and-attributes directory t)))
15791 ;; while we are in the current directory
15792 (while current-directory-list
15793 @end group
15794 @group
15795 (cond
15796 ;; check to see whether filename ends in `.el'
15797 ;; and if so, append its name to a list.
15798 ((equal ".el" (substring (car (car current-directory-list)) -3))
15799 (setq el-files-list
15800 (cons (car (car current-directory-list)) el-files-list)))
15801 @end group
15802 @group
15803 ;; check whether filename is that of a directory
15804 ((eq t (car (cdr (car current-directory-list))))
15805 ;; decide whether to skip or recurse
15806 (if
15807 (equal "."
15808 (substring (car (car current-directory-list)) -1))
15809 ;; then do nothing since filename is that of
15810 ;; current directory or parent, "." or ".."
15811 ()
15812 @end group
15813 @group
15814 ;; else descend into the directory and repeat the process
15815 (setq el-files-list
15816 (append
15817 (files-in-below-directory
15818 (car (car current-directory-list)))
15819 el-files-list)))))
15820 ;; move to the next filename in the list; this also
15821 ;; shortens the list so the while loop eventually comes to an end
15822 (setq current-directory-list (cdr current-directory-list)))
15823 ;; return the filenames
15824 el-files-list))
15825 @end group
15826 @end smallexample
15827
15828 @c (files-in-below-directory "/usr/local/src/emacs/lisp/")
15829 @c (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15830
15831 The @code{files-in-below-directory} @code{directory-files} function
15832 takes one argument, the name of a directory.
15833
15834 @need 1250
15835 Thus, on my system,
15836
15837 @c (length (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15838
15839 @c !!! 22.1.1 lisp sources location here
15840 @smallexample
15841 @group
15842 (length
15843 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/"))
15844 @end group
15845 @end smallexample
15846
15847 @noindent
15848 tells me that in and below my Lisp sources directory are 1031
15849 @samp{.el} files.
15850
15851 @code{files-in-below-directory} returns a list in reverse alphabetical
15852 order. An expression to sort the list in alphabetical order looks
15853 like this:
15854
15855 @smallexample
15856 @group
15857 (sort
15858 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15859 'string-lessp)
15860 @end group
15861 @end smallexample
15862
15863 @ignore
15864 (defun test ()
15865 "Test how long it takes to find lengths of all sorted elisp defuns."
15866 (insert "\n" (current-time-string) "\n")
15867 (sit-for 0)
15868 (sort
15869 (recursive-lengths-list-many-files
15870 (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15871 '<)
15872 (insert (format "%s" (current-time-string))))
15873 @end ignore
15874
15875 @node Counting function definitions
15876 @subsection Counting function definitions
15877
15878 Our immediate goal is to generate a list that tells us how many
15879 function definitions contain fewer than 10 words and symbols, how many
15880 contain between 10 and 19 words and symbols, how many contain between
15881 20 and 29 words and symbols, and so on.
15882
15883 With a sorted list of numbers, this is easy: count how many elements
15884 of the list are smaller than 10, then, after moving past the numbers
15885 just counted, count how many are smaller than 20, then, after moving
15886 past the numbers just counted, count how many are smaller than 30, and
15887 so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
15888 larger than the top of that range. We can call the list of such
15889 numbers the @code{top-of-ranges} list.
15890
15891 @need 1200
15892 If we wished, we could generate this list automatically, but it is
15893 simpler to write a list manually. Here it is:
15894 @vindex top-of-ranges
15895
15896 @smallexample
15897 @group
15898 (defvar top-of-ranges
15899 '(10 20 30 40 50
15900 60 70 80 90 100
15901 110 120 130 140 150
15902 160 170 180 190 200
15903 210 220 230 240 250
15904 260 270 280 290 300)
15905 "List specifying ranges for `defuns-per-range'.")
15906 @end group
15907 @end smallexample
15908
15909 To change the ranges, we edit this list.
15910
15911 Next, we need to write the function that creates the list of the
15912 number of definitions within each range. Clearly, this function must
15913 take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15914 as arguments.
15915
15916 The @code{defuns-per-range} function must do two things again and
15917 again: it must count the number of definitions within a range
15918 specified by the current top-of-range value; and it must shift to the
15919 next higher value in the @code{top-of-ranges} list after counting the
15920 number of definitions in the current range. Since each of these
15921 actions is repetitive, we can use @code{while} loops for the job.
15922 One loop counts the number of definitions in the range defined by the
15923 current top-of-range value, and the other loop selects each of the
15924 top-of-range values in turn.
15925
15926 Several entries of the @code{sorted-lengths} list are counted for each
15927 range; this means that the loop for the @code{sorted-lengths} list
15928 will be inside the loop for the @code{top-of-ranges} list, like a
15929 small gear inside a big gear.
15930
15931 The inner loop counts the number of definitions within the range. It
15932 is a simple counting loop of the type we have seen before.
15933 (@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15934 The true-or-false test of the loop tests whether the value from the
15935 @code{sorted-lengths} list is smaller than the current value of the
15936 top of the range. If it is, the function increments the counter and
15937 tests the next value from the @code{sorted-lengths} list.
15938
15939 @need 1250
15940 The inner loop looks like this:
15941
15942 @smallexample
15943 @group
15944 (while @var{length-element-smaller-than-top-of-range}
15945 (setq number-within-range (1+ number-within-range))
15946 (setq sorted-lengths (cdr sorted-lengths)))
15947 @end group
15948 @end smallexample
15949
15950 The outer loop must start with the lowest value of the
15951 @code{top-of-ranges} list, and then be set to each of the succeeding
15952 higher values in turn. This can be done with a loop like this:
15953
15954 @smallexample
15955 @group
15956 (while top-of-ranges
15957 @var{body-of-loop}@dots{}
15958 (setq top-of-ranges (cdr top-of-ranges)))
15959 @end group
15960 @end smallexample
15961
15962 @need 1200
15963 Put together, the two loops look like this:
15964
15965 @smallexample
15966 @group
15967 (while top-of-ranges
15968
15969 ;; @r{Count the number of elements within the current range.}
15970 (while @var{length-element-smaller-than-top-of-range}
15971 (setq number-within-range (1+ number-within-range))
15972 (setq sorted-lengths (cdr sorted-lengths)))
15973
15974 ;; @r{Move to next range.}
15975 (setq top-of-ranges (cdr top-of-ranges)))
15976 @end group
15977 @end smallexample
15978
15979 In addition, in each circuit of the outer loop, Emacs should record
15980 the number of definitions within that range (the value of
15981 @code{number-within-range}) in a list. We can use @code{cons} for
15982 this purpose. (@xref{cons, , @code{cons}}.)
15983
15984 The @code{cons} function works fine, except that the list it
15985 constructs will contain the number of definitions for the highest
15986 range at its beginning and the number of definitions for the lowest
15987 range at its end. This is because @code{cons} attaches new elements
15988 of the list to the beginning of the list, and since the two loops are
15989 working their way through the lengths' list from the lower end first,
15990 the @code{defuns-per-range-list} will end up largest number first.
15991 But we will want to print our graph with smallest values first and the
15992 larger later. The solution is to reverse the order of the
15993 @code{defuns-per-range-list}. We can do this using the
15994 @code{nreverse} function, which reverses the order of a list.
15995 @findex nreverse
15996
15997 @need 800
15998 For example,
15999
16000 @smallexample
16001 (nreverse '(1 2 3 4))
16002 @end smallexample
16003
16004 @need 800
16005 @noindent
16006 produces:
16007
16008 @smallexample
16009 (4 3 2 1)
16010 @end smallexample
16011
16012 Note that the @code{nreverse} function is ``destructive''---that is,
16013 it changes the list to which it is applied; this contrasts with the
16014 @code{car} and @code{cdr} functions, which are non-destructive. In
16015 this case, we do not want the original @code{defuns-per-range-list},
16016 so it does not matter that it is destroyed. (The @code{reverse}
16017 function provides a reversed copy of a list, leaving the original list
16018 as is.)
16019 @findex reverse
16020
16021 @need 1250
16022 Put all together, the @code{defuns-per-range} looks like this:
16023
16024 @smallexample
16025 @group
16026 (defun defuns-per-range (sorted-lengths top-of-ranges)
16027 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
16028 (let ((top-of-range (car top-of-ranges))
16029 (number-within-range 0)
16030 defuns-per-range-list)
16031 @end group
16032
16033 @group
16034 ;; @r{Outer loop.}
16035 (while top-of-ranges
16036 @end group
16037
16038 @group
16039 ;; @r{Inner loop.}
16040 (while (and
16041 ;; @r{Need number for numeric test.}
16042 (car sorted-lengths)
16043 (< (car sorted-lengths) top-of-range))
16044 @end group
16045
16046 @group
16047 ;; @r{Count number of definitions within current range.}
16048 (setq number-within-range (1+ number-within-range))
16049 (setq sorted-lengths (cdr sorted-lengths)))
16050
16051 ;; @r{Exit inner loop but remain within outer loop.}
16052 @end group
16053
16054 @group
16055 (setq defuns-per-range-list
16056 (cons number-within-range defuns-per-range-list))
16057 (setq number-within-range 0) ; @r{Reset count to zero.}
16058 @end group
16059
16060 @group
16061 ;; @r{Move to next range.}
16062 (setq top-of-ranges (cdr top-of-ranges))
16063 ;; @r{Specify next top of range value.}
16064 (setq top-of-range (car top-of-ranges)))
16065 @end group
16066
16067 @group
16068 ;; @r{Exit outer loop and count the number of defuns larger than}
16069 ;; @r{ the largest top-of-range value.}
16070 (setq defuns-per-range-list
16071 (cons
16072 (length sorted-lengths)
16073 defuns-per-range-list))
16074 @end group
16075
16076 @group
16077 ;; @r{Return a list of the number of definitions within each range,}
16078 ;; @r{ smallest to largest.}
16079 (nreverse defuns-per-range-list)))
16080 @end group
16081 @end smallexample
16082
16083 @need 1200
16084 @noindent
16085 The function is straightforward except for one subtle feature. The
16086 true-or-false test of the inner loop looks like this:
16087
16088 @smallexample
16089 @group
16090 (and (car sorted-lengths)
16091 (< (car sorted-lengths) top-of-range))
16092 @end group
16093 @end smallexample
16094
16095 @need 800
16096 @noindent
16097 instead of like this:
16098
16099 @smallexample
16100 (< (car sorted-lengths) top-of-range)
16101 @end smallexample
16102
16103 The purpose of the test is to determine whether the first item in the
16104 @code{sorted-lengths} list is less than the value of the top of the
16105 range.
16106
16107 The simple version of the test works fine unless the
16108 @code{sorted-lengths} list has a @code{nil} value. In that case, the
16109 @code{(car sorted-lengths)} expression function returns
16110 @code{nil}. The @code{<} function cannot compare a number to
16111 @code{nil}, which is an empty list, so Emacs signals an error and
16112 stops the function from attempting to continue to execute.
16113
16114 The @code{sorted-lengths} list always becomes @code{nil} when the
16115 counter reaches the end of the list. This means that any attempt to
16116 use the @code{defuns-per-range} function with the simple version of
16117 the test will fail.
16118
16119 We solve the problem by using the @code{(car sorted-lengths)}
16120 expression in conjunction with the @code{and} expression. The
16121 @code{(car sorted-lengths)} expression returns a non-@code{nil}
16122 value so long as the list has at least one number within it, but
16123 returns @code{nil} if the list is empty. The @code{and} expression
16124 first evaluates the @code{(car sorted-lengths)} expression, and
16125 if it is @code{nil}, returns false @emph{without} evaluating the
16126 @code{<} expression. But if the @code{(car sorted-lengths)}
16127 expression returns a non-@code{nil} value, the @code{and} expression
16128 evaluates the @code{<} expression, and returns that value as the value
16129 of the @code{and} expression.
16130
16131 @c colon in printed section title causes problem in Info cross reference
16132 This way, we avoid an error.
16133 @iftex
16134 @noindent
16135 (For information about @code{and}, see
16136 @ref{kill-new function, , The @code{kill-new} function}.)
16137 @end iftex
16138 @ifinfo
16139 @noindent
16140 (@xref{kill-new function, , The @code{kill-new} function}, for
16141 information about @code{and}.)
16142 @end ifinfo
16143
16144 Here is a short test of the @code{defuns-per-range} function. First,
16145 evaluate the expression that binds (a shortened)
16146 @code{top-of-ranges} list to the list of values, then evaluate the
16147 expression for binding the @code{sorted-lengths} list, and then
16148 evaluate the @code{defuns-per-range} function.
16149
16150 @smallexample
16151 @group
16152 ;; @r{(Shorter list than we will use later.)}
16153 (setq top-of-ranges
16154 '(110 120 130 140 150
16155 160 170 180 190 200))
16156
16157 (setq sorted-lengths
16158 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
16159
16160 (defuns-per-range sorted-lengths top-of-ranges)
16161 @end group
16162 @end smallexample
16163
16164 @need 800
16165 @noindent
16166 The list returned looks like this:
16167
16168 @smallexample
16169 (2 2 2 0 0 1 0 2 0 0 4)
16170 @end smallexample
16171
16172 @noindent
16173 Indeed, there are two elements of the @code{sorted-lengths} list
16174 smaller than 110, two elements between 110 and 119, two elements
16175 between 120 and 129, and so on. There are four elements with a value
16176 of 200 or larger.
16177
16178 @c The next step is to turn this numbers' list into a graph.
16179 @node Readying a Graph
16180 @chapter Readying a Graph
16181 @cindex Readying a graph
16182 @cindex Graph prototype
16183 @cindex Prototype graph
16184 @cindex Body of graph
16185
16186 Our goal is to construct a graph showing the numbers of function
16187 definitions of various lengths in the Emacs lisp sources.
16188
16189 As a practical matter, if you were creating a graph, you would
16190 probably use a program such as @code{gnuplot} to do the job.
16191 (@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
16192 however, we create one from scratch, and in the process we will
16193 re-acquaint ourselves with some of what we learned before and learn
16194 more.
16195
16196 In this chapter, we will first write a simple graph printing function.
16197 This first definition will be a @dfn{prototype}, a rapidly written
16198 function that enables us to reconnoiter this unknown graph-making
16199 territory. We will discover dragons, or find that they are myth.
16200 After scouting the terrain, we will feel more confident and enhance
16201 the function to label the axes automatically.
16202
16203 @menu
16204 * Columns of a graph::
16205 * graph-body-print:: How to print the body of a graph.
16206 * recursive-graph-body-print::
16207 * Printed Axes::
16208 * Line Graph Exercise::
16209 @end menu
16210
16211 @ifnottex
16212 @node Columns of a graph
16213 @unnumberedsec Printing the Columns of a Graph
16214 @end ifnottex
16215
16216 Since Emacs is designed to be flexible and work with all kinds of
16217 terminals, including character-only terminals, the graph will need to
16218 be made from one of the `typewriter' symbols. An asterisk will do; as
16219 we enhance the graph-printing function, we can make the choice of
16220 symbol a user option.
16221
16222 We can call this function @code{graph-body-print}; it will take a
16223 @code{numbers-list} as its only argument. At this stage, we will not
16224 label the graph, but only print its body.
16225
16226 The @code{graph-body-print} function inserts a vertical column of
16227 asterisks for each element in the @code{numbers-list}. The height of
16228 each line is determined by the value of that element of the
16229 @code{numbers-list}.
16230
16231 Inserting columns is a repetitive act; that means that this function can
16232 be written either with a @code{while} loop or recursively.
16233
16234 Our first challenge is to discover how to print a column of asterisks.
16235 Usually, in Emacs, we print characters onto a screen horizontally,
16236 line by line, by typing. We have two routes we can follow: write our
16237 own column-insertion function or discover whether one exists in Emacs.
16238
16239 To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
16240 command. This command is like the @kbd{C-h a} (@code{command-apropos})
16241 command, except that the latter finds only those functions that are
16242 commands. The @kbd{M-x apropos} command lists all symbols that match
16243 a regular expression, including functions that are not interactive.
16244 @findex apropos
16245
16246 What we want to look for is some command that prints or inserts
16247 columns. Very likely, the name of the function will contain either
16248 the word `print' or the word `insert' or the word `column'.
16249 Therefore, we can simply type @kbd{M-x apropos RET
16250 print\|insert\|column RET} and look at the result. On my system, this
16251 command once too takes quite some time, and then produced a list of 79
16252 functions and variables. Now it does not take much time at all and
16253 produces a list of 211 functions and variables. Scanning down the
16254 list, the only function that looks as if it might do the job is
16255 @code{insert-rectangle}.
16256
16257 @need 1200
16258 Indeed, this is the function we want; its documentation says:
16259
16260 @smallexample
16261 @group
16262 insert-rectangle:
16263 Insert text of RECTANGLE with upper left corner at point.
16264 RECTANGLE's first line is inserted at point,
16265 its second line is inserted at a point vertically under point, etc.
16266 RECTANGLE should be a list of strings.
16267 After this command, the mark is at the upper left corner
16268 and point is at the lower right corner.
16269 @end group
16270 @end smallexample
16271
16272 We can run a quick test, to make sure it does what we expect of it.
16273
16274 Here is the result of placing the cursor after the
16275 @code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
16276 (@code{eval-last-sexp}). The function inserts the strings
16277 @samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
16278 point. Also the function returns @code{nil}.
16279
16280 @smallexample
16281 @group
16282 (insert-rectangle '("first" "second" "third"))first
16283 second
16284 thirdnil
16285 @end group
16286 @end smallexample
16287
16288 @noindent
16289 Of course, we won't be inserting the text of the
16290 @code{insert-rectangle} expression itself into the buffer in which we
16291 are making the graph, but will call the function from our program. We
16292 shall, however, have to make sure that point is in the buffer at the
16293 place where the @code{insert-rectangle} function will insert its
16294 column of strings.
16295
16296 If you are reading this in Info, you can see how this works by
16297 switching to another buffer, such as the @file{*scratch*} buffer,
16298 placing point somewhere in the buffer, typing @kbd{M-:}, typing the
16299 @code{insert-rectangle} expression into the minibuffer at the prompt,
16300 and then typing @key{RET}. This causes Emacs to evaluate the
16301 expression in the minibuffer, but to use as the value of point the
16302 position of point in the @file{*scratch*} buffer. (@kbd{M-:} is the
16303 keybinding for @code{eval-expression}. Also, @code{nil} does not
16304 appear in the @file{*scratch*} buffer since the expression is
16305 evaluated in the minibuffer.)
16306
16307 We find when we do this that point ends up at the end of the last
16308 inserted line---that is to say, this function moves point as a
16309 side-effect. If we were to repeat the command, with point at this
16310 position, the next insertion would be below and to the right of the
16311 previous insertion. We don't want this! If we are going to make a
16312 bar graph, the columns need to be beside each other.
16313
16314 So we discover that each cycle of the column-inserting @code{while}
16315 loop must reposition point to the place we want it, and that place
16316 will be at the top, not the bottom, of the column. Moreover, we
16317 remember that when we print a graph, we do not expect all the columns
16318 to be the same height. This means that the top of each column may be
16319 at a different height from the previous one. We cannot simply
16320 reposition point to the same line each time, but moved over to the
16321 right---or perhaps we can@dots{}
16322
16323 We are planning to make the columns of the bar graph out of asterisks.
16324 The number of asterisks in the column is the number specified by the
16325 current element of the @code{numbers-list}. We need to construct a
16326 list of asterisks of the right length for each call to
16327 @code{insert-rectangle}. If this list consists solely of the requisite
16328 number of asterisks, then we will have position point the right number
16329 of lines above the base for the graph to print correctly. This could
16330 be difficult.
16331
16332 Alternatively, if we can figure out some way to pass
16333 @code{insert-rectangle} a list of the same length each time, then we
16334 can place point on the same line each time, but move it over one
16335 column to the right for each new column. If we do this, however, some
16336 of the entries in the list passed to @code{insert-rectangle} must be
16337 blanks rather than asterisks. For example, if the maximum height of
16338 the graph is 5, but the height of the column is 3, then
16339 @code{insert-rectangle} requires an argument that looks like this:
16340
16341 @smallexample
16342 (" " " " "*" "*" "*")
16343 @end smallexample
16344
16345 This last proposal is not so difficult, so long as we can determine
16346 the column height. There are two ways for us to specify the column
16347 height: we can arbitrarily state what it will be, which would work
16348 fine for graphs of that height; or we can search through the list of
16349 numbers and use the maximum height of the list as the maximum height
16350 of the graph. If the latter operation were difficult, then the former
16351 procedure would be easiest, but there is a function built into Emacs
16352 that determines the maximum of its arguments. We can use that
16353 function. The function is called @code{max} and it returns the
16354 largest of all its arguments, which must be numbers. Thus, for
16355 example,
16356
16357 @smallexample
16358 (max 3 4 6 5 7 3)
16359 @end smallexample
16360
16361 @noindent
16362 returns 7. (A corresponding function called @code{min} returns the
16363 smallest of all its arguments.)
16364 @findex max
16365 @findex min
16366
16367 However, we cannot simply call @code{max} on the @code{numbers-list};
16368 the @code{max} function expects numbers as its argument, not a list of
16369 numbers. Thus, the following expression,
16370
16371 @smallexample
16372 (max '(3 4 6 5 7 3))
16373 @end smallexample
16374
16375 @need 800
16376 @noindent
16377 produces the following error message;
16378
16379 @smallexample
16380 Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
16381 @end smallexample
16382
16383 @findex apply
16384 We need a function that passes a list of arguments to a function.
16385 This function is @code{apply}. This function `applies' its first
16386 argument (a function) to its remaining arguments, the last of which
16387 may be a list.
16388
16389 @need 1250
16390 For example,
16391
16392 @smallexample
16393 (apply 'max 3 4 7 3 '(4 8 5))
16394 @end smallexample
16395
16396 @noindent
16397 returns 8.
16398
16399 (Incidentally, I don't know how you would learn of this function
16400 without a book such as this. It is possible to discover other
16401 functions, like @code{search-forward} or @code{insert-rectangle}, by
16402 guessing at a part of their names and then using @code{apropos}. Even
16403 though its base in metaphor is clear---`apply' its first argument to
16404 the rest---I doubt a novice would come up with that particular word
16405 when using @code{apropos} or other aid. Of course, I could be wrong;
16406 after all, the function was first named by someone who had to invent
16407 it.)
16408
16409 The second and subsequent arguments to @code{apply} are optional, so
16410 we can use @code{apply} to call a function and pass the elements of a
16411 list to it, like this, which also returns 8:
16412
16413 @smallexample
16414 (apply 'max '(4 8 5))
16415 @end smallexample
16416
16417 This latter way is how we will use @code{apply}. The
16418 @code{recursive-lengths-list-many-files} function returns a numbers'
16419 list to which we can apply @code{max} (we could also apply @code{max} to
16420 the sorted numbers' list; it does not matter whether the list is
16421 sorted or not.)
16422
16423 @need 800
16424 Hence, the operation for finding the maximum height of the graph is this:
16425
16426 @smallexample
16427 (setq max-graph-height (apply 'max numbers-list))
16428 @end smallexample
16429
16430 Now we can return to the question of how to create a list of strings
16431 for a column of the graph. Told the maximum height of the graph
16432 and the number of asterisks that should appear in the column, the
16433 function should return a list of strings for the
16434 @code{insert-rectangle} command to insert.
16435
16436 Each column is made up of asterisks or blanks. Since the function is
16437 passed the value of the height of the column and the number of
16438 asterisks in the column, the number of blanks can be found by
16439 subtracting the number of asterisks from the height of the column.
16440 Given the number of blanks and the number of asterisks, two
16441 @code{while} loops can be used to construct the list:
16442
16443 @smallexample
16444 @group
16445 ;;; @r{First version.}
16446 (defun column-of-graph (max-graph-height actual-height)
16447 "Return list of strings that is one column of a graph."
16448 (let ((insert-list nil)
16449 (number-of-top-blanks
16450 (- max-graph-height actual-height)))
16451 @end group
16452
16453 @group
16454 ;; @r{Fill in asterisks.}
16455 (while (> actual-height 0)
16456 (setq insert-list (cons "*" insert-list))
16457 (setq actual-height (1- actual-height)))
16458 @end group
16459
16460 @group
16461 ;; @r{Fill in blanks.}
16462 (while (> number-of-top-blanks 0)
16463 (setq insert-list (cons " " insert-list))
16464 (setq number-of-top-blanks
16465 (1- number-of-top-blanks)))
16466 @end group
16467
16468 @group
16469 ;; @r{Return whole list.}
16470 insert-list))
16471 @end group
16472 @end smallexample
16473
16474 If you install this function and then evaluate the following
16475 expression you will see that it returns the list as desired:
16476
16477 @smallexample
16478 (column-of-graph 5 3)
16479 @end smallexample
16480
16481 @need 800
16482 @noindent
16483 returns
16484
16485 @smallexample
16486 (" " " " "*" "*" "*")
16487 @end smallexample
16488
16489 As written, @code{column-of-graph} contains a major flaw: the symbols
16490 used for the blank and for the marked entries in the column are
16491 `hard-coded' as a space and asterisk. This is fine for a prototype,
16492 but you, or another user, may wish to use other symbols. For example,
16493 in testing the graph function, you many want to use a period in place
16494 of the space, to make sure the point is being repositioned properly
16495 each time the @code{insert-rectangle} function is called; or you might
16496 want to substitute a @samp{+} sign or other symbol for the asterisk.
16497 You might even want to make a graph-column that is more than one
16498 display column wide. The program should be more flexible. The way to
16499 do that is to replace the blank and the asterisk with two variables
16500 that we can call @code{graph-blank} and @code{graph-symbol} and define
16501 those variables separately.
16502
16503 Also, the documentation is not well written. These considerations
16504 lead us to the second version of the function:
16505
16506 @smallexample
16507 @group
16508 (defvar graph-symbol "*"
16509 "String used as symbol in graph, usually an asterisk.")
16510 @end group
16511
16512 @group
16513 (defvar graph-blank " "
16514 "String used as blank in graph, usually a blank space.
16515 graph-blank must be the same number of columns wide
16516 as graph-symbol.")
16517 @end group
16518 @end smallexample
16519
16520 @noindent
16521 (For an explanation of @code{defvar}, see
16522 @ref{defvar, , Initializing a Variable with @code{defvar}}.)
16523
16524 @smallexample
16525 @group
16526 ;;; @r{Second version.}
16527 (defun column-of-graph (max-graph-height actual-height)
16528 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
16529
16530 @end group
16531 @group
16532 The graph-symbols are contiguous entries at the end
16533 of the list.
16534 The list will be inserted as one column of a graph.
16535 The strings are either graph-blank or graph-symbol."
16536 @end group
16537
16538 @group
16539 (let ((insert-list nil)
16540 (number-of-top-blanks
16541 (- max-graph-height actual-height)))
16542 @end group
16543
16544 @group
16545 ;; @r{Fill in @code{graph-symbols}.}
16546 (while (> actual-height 0)
16547 (setq insert-list (cons graph-symbol insert-list))
16548 (setq actual-height (1- actual-height)))
16549 @end group
16550
16551 @group
16552 ;; @r{Fill in @code{graph-blanks}.}
16553 (while (> number-of-top-blanks 0)
16554 (setq insert-list (cons graph-blank insert-list))
16555 (setq number-of-top-blanks
16556 (1- number-of-top-blanks)))
16557
16558 ;; @r{Return whole list.}
16559 insert-list))
16560 @end group
16561 @end smallexample
16562
16563 If we wished, we could rewrite @code{column-of-graph} a third time to
16564 provide optionally for a line graph as well as for a bar graph. This
16565 would not be hard to do. One way to think of a line graph is that it
16566 is no more than a bar graph in which the part of each bar that is
16567 below the top is blank. To construct a column for a line graph, the
16568 function first constructs a list of blanks that is one shorter than
16569 the value, then it uses @code{cons} to attach a graph symbol to the
16570 list; then it uses @code{cons} again to attach the `top blanks' to
16571 the list.
16572
16573 It is easy to see how to write such a function, but since we don't
16574 need it, we will not do it. But the job could be done, and if it were
16575 done, it would be done with @code{column-of-graph}. Even more
16576 important, it is worth noting that few changes would have to be made
16577 anywhere else. The enhancement, if we ever wish to make it, is
16578 simple.
16579
16580 Now, finally, we come to our first actual graph printing function.
16581 This prints the body of a graph, not the labels for the vertical and
16582 horizontal axes, so we can call this @code{graph-body-print}.
16583
16584 @node graph-body-print
16585 @section The @code{graph-body-print} Function
16586 @findex graph-body-print
16587
16588 After our preparation in the preceding section, the
16589 @code{graph-body-print} function is straightforward. The function
16590 will print column after column of asterisks and blanks, using the
16591 elements of a numbers' list to specify the number of asterisks in each
16592 column. This is a repetitive act, which means we can use a
16593 decrementing @code{while} loop or recursive function for the job. In
16594 this section, we will write the definition using a @code{while} loop.
16595
16596 The @code{column-of-graph} function requires the height of the graph
16597 as an argument, so we should determine and record that as a local variable.
16598
16599 This leads us to the following template for the @code{while} loop
16600 version of this function:
16601
16602 @smallexample
16603 @group
16604 (defun graph-body-print (numbers-list)
16605 "@var{documentation}@dots{}"
16606 (let ((height @dots{}
16607 @dots{}))
16608 @end group
16609
16610 @group
16611 (while numbers-list
16612 @var{insert-columns-and-reposition-point}
16613 (setq numbers-list (cdr numbers-list)))))
16614 @end group
16615 @end smallexample
16616
16617 @noindent
16618 We need to fill in the slots of the template.
16619
16620 Clearly, we can use the @code{(apply 'max numbers-list)} expression to
16621 determine the height of the graph.
16622
16623 The @code{while} loop will cycle through the @code{numbers-list} one
16624 element at a time. As it is shortened by the @code{(setq numbers-list
16625 (cdr numbers-list))} expression, the @sc{car} of each instance of the
16626 list is the value of the argument for @code{column-of-graph}.
16627
16628 At each cycle of the @code{while} loop, the @code{insert-rectangle}
16629 function inserts the list returned by @code{column-of-graph}. Since
16630 the @code{insert-rectangle} function moves point to the lower right of
16631 the inserted rectangle, we need to save the location of point at the
16632 time the rectangle is inserted, move back to that position after the
16633 rectangle is inserted, and then move horizontally to the next place
16634 from which @code{insert-rectangle} is called.
16635
16636 If the inserted columns are one character wide, as they will be if
16637 single blanks and asterisks are used, the repositioning command is
16638 simply @code{(forward-char 1)}; however, the width of a column may be
16639 greater than one. This means that the repositioning command should be
16640 written @code{(forward-char symbol-width)}. The @code{symbol-width}
16641 itself is the length of a @code{graph-blank} and can be found using
16642 the expression @code{(length graph-blank)}. The best place to bind
16643 the @code{symbol-width} variable to the value of the width of graph
16644 column is in the varlist of the @code{let} expression.
16645
16646 @need 1250
16647 These considerations lead to the following function definition:
16648
16649 @smallexample
16650 @group
16651 (defun graph-body-print (numbers-list)
16652 "Print a bar graph of the NUMBERS-LIST.
16653 The numbers-list consists of the Y-axis values."
16654
16655 (let ((height (apply 'max numbers-list))
16656 (symbol-width (length graph-blank))
16657 from-position)
16658 @end group
16659
16660 @group
16661 (while numbers-list
16662 (setq from-position (point))
16663 (insert-rectangle
16664 (column-of-graph height (car numbers-list)))
16665 (goto-char from-position)
16666 (forward-char symbol-width)
16667 @end group
16668 @group
16669 ;; @r{Draw graph column by column.}
16670 (sit-for 0)
16671 (setq numbers-list (cdr numbers-list)))
16672 @end group
16673 @group
16674 ;; @r{Place point for X axis labels.}
16675 (forward-line height)
16676 (insert "\n")
16677 ))
16678 @end group
16679 @end smallexample
16680
16681 @noindent
16682 The one unexpected expression in this function is the
16683 @w{@code{(sit-for 0)}} expression in the @code{while} loop. This
16684 expression makes the graph printing operation more interesting to
16685 watch than it would be otherwise. The expression causes Emacs to
16686 `sit' or do nothing for a zero length of time and then redraw the
16687 screen. Placed here, it causes Emacs to redraw the screen column by
16688 column. Without it, Emacs would not redraw the screen until the
16689 function exits.
16690
16691 We can test @code{graph-body-print} with a short list of numbers.
16692
16693 @enumerate
16694 @item
16695 Install @code{graph-symbol}, @code{graph-blank},
16696 @code{column-of-graph}, which are in
16697 @iftex
16698 @ref{Readying a Graph, , Readying a Graph},
16699 @end iftex
16700 @ifinfo
16701 @ref{Columns of a graph},
16702 @end ifinfo
16703 and @code{graph-body-print}.
16704
16705 @need 800
16706 @item
16707 Copy the following expression:
16708
16709 @smallexample
16710 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
16711 @end smallexample
16712
16713 @item
16714 Switch to the @file{*scratch*} buffer and place the cursor where you
16715 want the graph to start.
16716
16717 @item
16718 Type @kbd{M-:} (@code{eval-expression}).
16719
16720 @item
16721 Yank the @code{graph-body-print} expression into the minibuffer
16722 with @kbd{C-y} (@code{yank)}.
16723
16724 @item
16725 Press @key{RET} to evaluate the @code{graph-body-print} expression.
16726 @end enumerate
16727
16728 @need 800
16729 Emacs will print a graph like this:
16730
16731 @smallexample
16732 @group
16733 *
16734 * **
16735 * ****
16736 *** ****
16737 ********* *
16738 ************
16739 *************
16740 @end group
16741 @end smallexample
16742
16743 @node recursive-graph-body-print
16744 @section The @code{recursive-graph-body-print} Function
16745 @findex recursive-graph-body-print
16746
16747 The @code{graph-body-print} function may also be written recursively.
16748 The recursive solution is divided into two parts: an outside `wrapper'
16749 that uses a @code{let} expression to determine the values of several
16750 variables that need only be found once, such as the maximum height of
16751 the graph, and an inside function that is called recursively to print
16752 the graph.
16753
16754 @need 1250
16755 The `wrapper' is uncomplicated:
16756
16757 @smallexample
16758 @group
16759 (defun recursive-graph-body-print (numbers-list)
16760 "Print a bar graph of the NUMBERS-LIST.
16761 The numbers-list consists of the Y-axis values."
16762 (let ((height (apply 'max numbers-list))
16763 (symbol-width (length graph-blank))
16764 from-position)
16765 (recursive-graph-body-print-internal
16766 numbers-list
16767 height
16768 symbol-width)))
16769 @end group
16770 @end smallexample
16771
16772 The recursive function is a little more difficult. It has four parts:
16773 the `do-again-test', the printing code, the recursive call, and the
16774 `next-step-expression'. The `do-again-test' is a @code{when}
16775 expression that determines whether the @code{numbers-list} contains
16776 any remaining elements; if it does, the function prints one column of
16777 the graph using the printing code and calls itself again. The
16778 function calls itself again according to the value produced by the
16779 `next-step-expression' which causes the call to act on a shorter
16780 version of the @code{numbers-list}.
16781
16782 @smallexample
16783 @group
16784 (defun recursive-graph-body-print-internal
16785 (numbers-list height symbol-width)
16786 "Print a bar graph.
16787 Used within recursive-graph-body-print function."
16788 @end group
16789
16790 @group
16791 (when numbers-list
16792 (setq from-position (point))
16793 (insert-rectangle
16794 (column-of-graph height (car numbers-list)))
16795 @end group
16796 @group
16797 (goto-char from-position)
16798 (forward-char symbol-width)
16799 (sit-for 0) ; @r{Draw graph column by column.}
16800 (recursive-graph-body-print-internal
16801 (cdr numbers-list) height symbol-width)))
16802 @end group
16803 @end smallexample
16804
16805 @need 1250
16806 After installation, this expression can be tested; here is a sample:
16807
16808 @smallexample
16809 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
16810 @end smallexample
16811
16812 @need 800
16813 Here is what @code{recursive-graph-body-print} produces:
16814
16815 @smallexample
16816 @group
16817 *
16818 ** *
16819 **** *
16820 **** ***
16821 * *********
16822 ************
16823 *************
16824 @end group
16825 @end smallexample
16826
16827 Either of these two functions, @code{graph-body-print} or
16828 @code{recursive-graph-body-print}, create the body of a graph.
16829
16830 @node Printed Axes
16831 @section Need for Printed Axes
16832
16833 A graph needs printed axes, so you can orient yourself. For a do-once
16834 project, it may be reasonable to draw the axes by hand using Emacs's
16835 Picture mode; but a graph drawing function may be used more than once.
16836
16837 For this reason, I have written enhancements to the basic
16838 @code{print-graph-body} function that automatically print labels for
16839 the horizontal and vertical axes. Since the label printing functions
16840 do not contain much new material, I have placed their description in
16841 an appendix. @xref{Full Graph, , A Graph with Labeled Axes}.
16842
16843 @node Line Graph Exercise
16844 @section Exercise
16845
16846 Write a line graph version of the graph printing functions.
16847
16848 @node Emacs Initialization
16849 @chapter Your @file{.emacs} File
16850 @cindex @file{.emacs} file
16851 @cindex Customizing your @file{.emacs} file
16852 @cindex Initialization file
16853
16854 ``You don't have to like Emacs to like it''---this seemingly
16855 paradoxical statement is the secret of GNU Emacs. The plain, `out of
16856 the box' Emacs is a generic tool. Most people who use it, customize
16857 it to suit themselves.
16858
16859 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
16860 expressions in Emacs Lisp you can change or extend Emacs.
16861
16862 @menu
16863 * Default Configuration::
16864 * Site-wide Init:: You can write site-wide init files.
16865 * defcustom:: Emacs will write code for you.
16866 * Beginning a .emacs File:: How to write a @code{.emacs file}.
16867 * Text and Auto-fill:: Automatically wrap lines.
16868 * Mail Aliases:: Use abbreviations for email addresses.
16869 * Indent Tabs Mode:: Don't use tabs with @TeX{}
16870 * Keybindings:: Create some personal keybindings.
16871 * Keymaps:: More about key binding.
16872 * Loading Files:: Load (i.e., evaluate) files automatically.
16873 * Autoload:: Make functions available.
16874 * Simple Extension:: Define a function; bind it to a key.
16875 * X11 Colors:: Colors in X.
16876 * Miscellaneous::
16877 * Mode Line:: How to customize your mode line.
16878 @end menu
16879
16880 @ifnottex
16881 @node Default Configuration
16882 @unnumberedsec Emacs's Default Configuration
16883 @end ifnottex
16884
16885 There are those who appreciate Emacs's default configuration. After
16886 all, Emacs starts you in C mode when you edit a C file, starts you in
16887 Fortran mode when you edit a Fortran file, and starts you in
16888 Fundamental mode when you edit an unadorned file. This all makes
16889 sense, if you do not know who is going to use Emacs. Who knows what a
16890 person hopes to do with an unadorned file? Fundamental mode is the
16891 right default for such a file, just as C mode is the right default for
16892 editing C code. (Enough programming languages have syntaxes
16893 that enable them to share or nearly share features, so C mode is
16894 now provided by CC mode, the `C Collection'.)
16895
16896 But when you do know who is going to use Emacs---you,
16897 yourself---then it makes sense to customize Emacs.
16898
16899 For example, I seldom want Fundamental mode when I edit an
16900 otherwise undistinguished file; I want Text mode. This is why I
16901 customize Emacs: so it suits me.
16902
16903 You can customize and extend Emacs by writing or adapting a
16904 @file{~/.emacs} file. This is your personal initialization file; its
16905 contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16906 may also add @file{.el} to @file{~/.emacs} and call it a
16907 @file{~/.emacs.el} file. In the past, you were forbidden to type the
16908 extra keystrokes that the name @file{~/.emacs.el} requires, but now
16909 you may. The new format is consistent with the Emacs Lisp file
16910 naming conventions; the old format saves typing.}
16911
16912 A @file{~/.emacs} file contains Emacs Lisp code. You can write this
16913 code yourself; or you can use Emacs's @code{customize} feature to write
16914 the code for you. You can combine your own expressions and
16915 auto-written Customize expressions in your @file{.emacs} file.
16916
16917 (I myself prefer to write my own expressions, except for those,
16918 particularly fonts, that I find easier to manipulate using the
16919 @code{customize} command. I combine the two methods.)
16920
16921 Most of this chapter is about writing expressions yourself. It
16922 describes a simple @file{.emacs} file; for more information, see
16923 @ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16924 @ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16925 Manual}.
16926
16927 @node Site-wide Init
16928 @section Site-wide Initialization Files
16929
16930 @cindex @file{default.el} init file
16931 @cindex @file{site-init.el} init file
16932 @cindex @file{site-load.el} init file
16933 In addition to your personal initialization file, Emacs automatically
16934 loads various site-wide initialization files, if they exist. These
16935 have the same form as your @file{.emacs} file, but are loaded by
16936 everyone.
16937
16938 Two site-wide initialization files, @file{site-load.el} and
16939 @file{site-init.el}, are loaded into Emacs and then `dumped' if a
16940 `dumped' version of Emacs is created, as is most common. (Dumped
16941 copies of Emacs load more quickly. However, once a file is loaded and
16942 dumped, a change to it does not lead to a change in Emacs unless you
16943 load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16944 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16945 @file{INSTALL} file.)
16946
16947 Three other site-wide initialization files are loaded automatically
16948 each time you start Emacs, if they exist. These are
16949 @file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16950 file, and @file{default.el}, and the terminal type file, which are both
16951 loaded @emph{after} your @file{.emacs} file.
16952
16953 Settings and definitions in your @file{.emacs} file will overwrite
16954 conflicting settings and definitions in a @file{site-start.el} file,
16955 if it exists; but the settings and definitions in a @file{default.el}
16956 or terminal type file will overwrite those in your @file{.emacs} file.
16957 (You can prevent interference from a terminal type file by setting
16958 @code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16959 Simple Extension}.)
16960
16961 @c Rewritten to avoid overfull hbox.
16962 The @file{INSTALL} file that comes in the distribution contains
16963 descriptions of the @file{site-init.el} and @file{site-load.el} files.
16964
16965 The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16966 control loading. These files are in the @file{lisp} directory of the
16967 Emacs distribution and are worth perusing.
16968
16969 The @file{loaddefs.el} file contains a good many suggestions as to
16970 what to put into your own @file{.emacs} file, or into a site-wide
16971 initialization file.
16972
16973 @node defcustom
16974 @section Specifying Variables using @code{defcustom}
16975 @findex defcustom
16976
16977 You can specify variables using @code{defcustom} so that you and
16978 others can then use Emacs's @code{customize} feature to set their
16979 values. (You cannot use @code{customize} to write function
16980 definitions; but you can write @code{defuns} in your @file{.emacs}
16981 file. Indeed, you can write any Lisp expression in your @file{.emacs}
16982 file.)
16983
16984 The @code{customize} feature depends on the @code{defcustom} special
16985 form. Although you can use @code{defvar} or @code{setq} for variables
16986 that users set, the @code{defcustom} special form is designed for the
16987 job.
16988
16989 You can use your knowledge of @code{defvar} for writing the
16990 first three arguments for @code{defcustom}. The first argument to
16991 @code{defcustom} is the name of the variable. The second argument is
16992 the variable's initial value, if any; and this value is set only if
16993 the value has not already been set. The third argument is the
16994 documentation.
16995
16996 The fourth and subsequent arguments to @code{defcustom} specify types
16997 and options; these are not featured in @code{defvar}. (These
16998 arguments are optional.)
16999
17000 Each of these arguments consists of a keyword followed by a value.
17001 Each keyword starts with the colon character @samp{:}.
17002
17003 @need 1250
17004 For example, the customizable user option variable
17005 @code{text-mode-hook} looks like this:
17006
17007 @smallexample
17008 @group
17009 (defcustom text-mode-hook nil
17010 "Normal hook run when entering Text mode and many related modes."
17011 :type 'hook
17012 :options '(turn-on-auto-fill flyspell-mode)
17013 :group 'data)
17014 @end group
17015 @end smallexample
17016
17017 @noindent
17018 The name of the variable is @code{text-mode-hook}; it has no default
17019 value; and its documentation string tells you what it does.
17020
17021 The @code{:type} keyword tells Emacs the kind of data to which
17022 @code{text-mode-hook} should be set and how to display the value in a
17023 Customization buffer.
17024
17025 The @code{:options} keyword specifies a suggested list of values for
17026 the variable. Usually, @code{:options} applies to a hook.
17027 The list is only a suggestion; it is not exclusive; a person who sets
17028 the variable may set it to other values; the list shown following the
17029 @code{:options} keyword is intended to offer convenient choices to a
17030 user.
17031
17032 Finally, the @code{:group} keyword tells the Emacs Customization
17033 command in which group the variable is located. This tells where to
17034 find it.
17035
17036 The @code{defcustom} function recognizes more than a dozen keywords.
17037 For more information, see @ref{Customization, , Writing Customization
17038 Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
17039
17040 Consider @code{text-mode-hook} as an example.
17041
17042 There are two ways to customize this variable. You can use the
17043 customization command or write the appropriate expressions yourself.
17044
17045 @need 800
17046 Using the customization command, you can type:
17047
17048 @smallexample
17049 M-x customize
17050 @end smallexample
17051
17052 @noindent
17053 and find that the group for editing files of data is called `data'.
17054 Enter that group. Text Mode Hook is the first member. You can click
17055 on its various options, such as @code{turn-on-auto-fill}, to set the
17056 values. After you click on the button to
17057
17058 @smallexample
17059 Save for Future Sessions
17060 @end smallexample
17061
17062 @noindent
17063 Emacs will write an expression into your @file{.emacs} file.
17064 It will look like this:
17065
17066 @smallexample
17067 @group
17068 (custom-set-variables
17069 ;; custom-set-variables was added by Custom.
17070 ;; If you edit it by hand, you could mess it up, so be careful.
17071 ;; Your init file should contain only one such instance.
17072 ;; If there is more than one, they won't work right.
17073 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
17074 @end group
17075 @end smallexample
17076
17077 @noindent
17078 (The @code{text-mode-hook-identify} function tells
17079 @code{toggle-text-mode-auto-fill} which buffers are in Text mode.
17080 It comes on automatically.)
17081
17082 The @code{custom-set-variables} function works somewhat differently
17083 than a @code{setq}. While I have never learned the differences, I
17084 modify the @code{custom-set-variables} expressions in my @file{.emacs}
17085 file by hand: I make the changes in what appears to me to be a
17086 reasonable manner and have not had any problems. Others prefer to use
17087 the Customization command and let Emacs do the work for them.
17088
17089 Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
17090 This function sets the various font faces. Over time, I have set a
17091 considerable number of faces. Some of the time, I re-set them using
17092 @code{customize}; other times, I simply edit the
17093 @code{custom-set-faces} expression in my @file{.emacs} file itself.
17094
17095 The second way to customize your @code{text-mode-hook} is to set it
17096 yourself in your @file{.emacs} file using code that has nothing to do
17097 with the @code{custom-set-@dots{}} functions.
17098
17099 @need 800
17100 When you do this, and later use @code{customize}, you will see a
17101 message that says
17102
17103 @smallexample
17104 CHANGED outside Customize; operating on it here may be unreliable.
17105 @end smallexample
17106
17107 @need 800
17108 This message is only a warning. If you click on the button to
17109
17110 @smallexample
17111 Save for Future Sessions
17112 @end smallexample
17113
17114 @noindent
17115 Emacs will write a @code{custom-set-@dots{}} expression near the end
17116 of your @file{.emacs} file that will be evaluated after your
17117 hand-written expression. It will, therefore, overrule your
17118 hand-written expression. No harm will be done. When you do this,
17119 however, be careful to remember which expression is active; if you
17120 forget, you may confuse yourself.
17121
17122 So long as you remember where the values are set, you will have no
17123 trouble. In any event, the values are always set in your
17124 initialization file, which is usually called @file{.emacs}.
17125
17126 I myself use @code{customize} for hardly anything. Mostly, I write
17127 expressions myself.
17128
17129 @findex defsubst
17130 @findex defconst
17131 Incidentally, to be more complete concerning defines: @code{defsubst}
17132 defines an inline function. The syntax is just like that of
17133 @code{defun}. @code{defconst} defines a symbol as a constant. The
17134 intent is that neither programs nor users should ever change a value
17135 set by @code{defconst}. (You can change it; the value set is a
17136 variable; but please do not.)
17137
17138 @node Beginning a .emacs File
17139 @section Beginning a @file{.emacs} File
17140 @cindex @file{.emacs} file, beginning of
17141
17142 When you start Emacs, it loads your @file{.emacs} file unless you tell
17143 it not to by specifying @samp{-q} on the command line. (The
17144 @code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
17145
17146 A @file{.emacs} file contains Lisp expressions. Often, these are no
17147 more than expressions to set values; sometimes they are function
17148 definitions.
17149
17150 @xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
17151 Manual}, for a short description of initialization files.
17152
17153 This chapter goes over some of the same ground, but is a walk among
17154 extracts from a complete, long-used @file{.emacs} file---my own.
17155
17156 The first part of the file consists of comments: reminders to myself.
17157 By now, of course, I remember these things, but when I started, I did
17158 not.
17159
17160 @need 1200
17161 @smallexample
17162 @group
17163 ;;;; Bob's .emacs file
17164 ; Robert J. Chassell
17165 ; 26 September 1985
17166 @end group
17167 @end smallexample
17168
17169 @noindent
17170 Look at that date! I started this file a long time ago. I have been
17171 adding to it ever since.
17172
17173 @smallexample
17174 @group
17175 ; Each section in this file is introduced by a
17176 ; line beginning with four semicolons; and each
17177 ; entry is introduced by a line beginning with
17178 ; three semicolons.
17179 @end group
17180 @end smallexample
17181
17182 @noindent
17183 This describes the usual conventions for comments in Emacs Lisp.
17184 Everything on a line that follows a semicolon is a comment. Two,
17185 three, and four semicolons are used as subsection and section markers.
17186 (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference Manual}, for
17187 more about comments.)
17188
17189 @smallexample
17190 @group
17191 ;;;; The Help Key
17192 ; Control-h is the help key;
17193 ; after typing control-h, type a letter to
17194 ; indicate the subject about which you want help.
17195 ; For an explanation of the help facility,
17196 ; type control-h two times in a row.
17197 @end group
17198 @end smallexample
17199
17200 @noindent
17201 Just remember: type @kbd{C-h} two times for help.
17202
17203 @smallexample
17204 @group
17205 ; To find out about any mode, type control-h m
17206 ; while in that mode. For example, to find out
17207 ; about mail mode, enter mail mode and then type
17208 ; control-h m.
17209 @end group
17210 @end smallexample
17211
17212 @noindent
17213 `Mode help', as I call this, is very helpful. Usually, it tells you
17214 all you need to know.
17215
17216 Of course, you don't need to include comments like these in your
17217 @file{.emacs} file. I included them in mine because I kept forgetting
17218 about Mode help or the conventions for comments---but I was able to
17219 remember to look here to remind myself.
17220
17221 @node Text and Auto-fill
17222 @section Text and Auto Fill Mode
17223
17224 Now we come to the part that `turns on' Text mode and
17225 Auto Fill mode.
17226
17227 @smallexample
17228 @group
17229 ;;; Text mode and Auto Fill mode
17230 ;; The next two lines put Emacs into Text mode
17231 ;; and Auto Fill mode, and are for writers who
17232 ;; want to start writing prose rather than code.
17233 (setq-default major-mode 'text-mode)
17234 (add-hook 'text-mode-hook 'turn-on-auto-fill)
17235 @end group
17236 @end smallexample
17237
17238 Here is the first part of this @file{.emacs} file that does something
17239 besides remind a forgetful human!
17240
17241 The first of the two lines in parentheses tells Emacs to turn on Text
17242 mode when you find a file, @emph{unless} that file should go into some
17243 other mode, such as C mode.
17244
17245 @cindex Per-buffer, local variables list
17246 @cindex Local variables list, per-buffer,
17247 @cindex Automatic mode selection
17248 @cindex Mode selection, automatic
17249 When Emacs reads a file, it looks at the extension to the file name,
17250 if any. (The extension is the part that comes after a @samp{.}.) If
17251 the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
17252 on C mode. Also, Emacs looks at first nonblank line of the file; if
17253 the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
17254 possesses a list of extensions and specifications that it uses
17255 automatically. In addition, Emacs looks near the last page for a
17256 per-buffer, ``local variables list'', if any.
17257
17258 @ifinfo
17259 @xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
17260 Emacs Manual}.
17261
17262 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17263 Manual}.
17264 @end ifinfo
17265 @iftex
17266 See sections ``How Major Modes are Chosen'' and ``Local Variables in
17267 Files'' in @cite{The GNU Emacs Manual}.
17268 @end iftex
17269
17270 Now, back to the @file{.emacs} file.
17271
17272 @need 800
17273 Here is the line again; how does it work?
17274
17275 @cindex Text Mode turned on
17276 @smallexample
17277 (setq major-mode 'text-mode)
17278 @end smallexample
17279
17280 @noindent
17281 This line is a short, but complete Emacs Lisp expression.
17282
17283 We are already familiar with @code{setq}. It sets the following variable,
17284 @code{major-mode}, to the subsequent value, which is @code{text-mode}.
17285 The single quote mark before @code{text-mode} tells Emacs to deal directly
17286 with the @code{text-mode} symbol, not with whatever it might stand for.
17287 @xref{set & setq, , Setting the Value of a Variable},
17288 for a reminder of how @code{setq} works.
17289 The main point is that there is no difference between the procedure you
17290 use to set a value in your @file{.emacs} file and the procedure you use
17291 anywhere else in Emacs.
17292
17293 @need 800
17294 Here is the next line:
17295
17296 @cindex Auto Fill mode turned on
17297 @findex add-hook
17298 @smallexample
17299 (add-hook 'text-mode-hook 'turn-on-auto-fill)
17300 @end smallexample
17301
17302 @noindent
17303 In this line, the @code{add-hook} command adds
17304 @code{turn-on-auto-fill} to the variable.
17305
17306 @code{turn-on-auto-fill} is the name of a program, that, you guessed
17307 it!, turns on Auto Fill mode.
17308
17309 Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
17310 onto Text mode. So every time Emacs turns on Text mode, Emacs also
17311 turns on Auto Fill mode.
17312
17313 In brief, the first line causes Emacs to enter Text mode when you edit a
17314 file, unless the file name extension, a first non-blank line, or local
17315 variables to tell Emacs otherwise.
17316
17317 Text mode among other actions, sets the syntax table to work
17318 conveniently for writers. In Text mode, Emacs considers an apostrophe
17319 as part of a word like a letter; but Emacs does not consider a period
17320 or a space as part of a word. Thus, @kbd{M-f} moves you over
17321 @samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
17322 the @samp{t} of @samp{it's}.
17323
17324 The second line causes Emacs to turn on Auto Fill mode when it turns
17325 on Text mode. In Auto Fill mode, Emacs automatically breaks a line
17326 that is too wide and brings the excessively wide part of the line down
17327 to the next line. Emacs breaks lines between words, not within them.
17328
17329 When Auto Fill mode is turned off, lines continue to the right as you
17330 type them. Depending on how you set the value of
17331 @code{truncate-lines}, the words you type either disappear off the
17332 right side of the screen, or else are shown, in a rather ugly and
17333 unreadable manner, as a continuation line on the screen.
17334
17335 @need 1250
17336 In addition, in this part of my @file{.emacs} file, I tell the Emacs
17337 fill commands to insert two spaces after a colon:
17338
17339 @smallexample
17340 (setq colon-double-space t)
17341 @end smallexample
17342
17343 @node Mail Aliases
17344 @section Mail Aliases
17345
17346 Here is a @code{setq} that `turns on' mail aliases, along with more
17347 reminders.
17348
17349 @smallexample
17350 @group
17351 ;;; Mail mode
17352 ; To enter mail mode, type `C-x m'
17353 ; To enter RMAIL (for reading mail),
17354 ; type `M-x rmail'
17355 (setq mail-aliases t)
17356 @end group
17357 @end smallexample
17358
17359 @cindex Mail aliases
17360 @noindent
17361 This @code{setq} command sets the value of the variable
17362 @code{mail-aliases} to @code{t}. Since @code{t} means true, the line
17363 says, in effect, ``Yes, use mail aliases.''
17364
17365 Mail aliases are convenient short names for long email addresses or
17366 for lists of email addresses. The file where you keep your `aliases'
17367 is @file{~/.mailrc}. You write an alias like this:
17368
17369 @smallexample
17370 alias geo george@@foobar.wiz.edu
17371 @end smallexample
17372
17373 @noindent
17374 When you write a message to George, address it to @samp{geo}; the
17375 mailer will automatically expand @samp{geo} to the full address.
17376
17377 @node Indent Tabs Mode
17378 @section Indent Tabs Mode
17379 @cindex Tabs, preventing
17380 @findex indent-tabs-mode
17381
17382 By default, Emacs inserts tabs in place of multiple spaces when it
17383 formats a region. (For example, you might indent many lines of text
17384 all at once with the @code{indent-region} command.) Tabs look fine on
17385 a terminal or with ordinary printing, but they produce badly indented
17386 output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
17387
17388 @need 1250
17389 The following turns off Indent Tabs mode:
17390
17391 @smallexample
17392 @group
17393 ;;; Prevent Extraneous Tabs
17394 (setq-default indent-tabs-mode nil)
17395 @end group
17396 @end smallexample
17397
17398 Note that this line uses @code{setq-default} rather than the
17399 @code{setq} command that we have seen before. The @code{setq-default}
17400 command sets values only in buffers that do not have their own local
17401 values for the variable.
17402
17403 @ifinfo
17404 @xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
17405
17406 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17407 Manual}.
17408 @end ifinfo
17409 @iftex
17410 See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
17411 Files'' in @cite{The GNU Emacs Manual}.
17412 @end iftex
17413
17414 @need 1700
17415 @node Keybindings
17416 @section Some Keybindings
17417
17418 Now for some personal keybindings:
17419
17420 @smallexample
17421 @group
17422 ;;; Compare windows
17423 (global-set-key "\C-cw" 'compare-windows)
17424 @end group
17425 @end smallexample
17426
17427 @findex compare-windows
17428 @code{compare-windows} is a nifty command that compares the text in
17429 your current window with text in the next window. It makes the
17430 comparison by starting at point in each window, moving over text in
17431 each window as far as they match. I use this command all the time.
17432
17433 This also shows how to set a key globally, for all modes.
17434
17435 @cindex Setting a key globally
17436 @cindex Global set key
17437 @cindex Key setting globally
17438 @findex global-set-key
17439 The command is @code{global-set-key}. It is followed by the
17440 keybinding. In a @file{.emacs} file, the keybinding is written as
17441 shown: @code{\C-c} stands for `control-c', which means `press the
17442 control key and the @key{c} key at the same time'. The @code{w} means
17443 `press the @key{w} key'. The keybinding is surrounded by double
17444 quotation marks. In documentation, you would write this as
17445 @w{@kbd{C-c w}}. (If you were binding a @key{META} key, such as
17446 @kbd{M-c}, rather than a @key{CTRL} key, you would write
17447 @w{@code{\M-c}} in your @file{.emacs} file. @xref{Init Rebinding, ,
17448 Rebinding Keys in Your Init File, emacs, The GNU Emacs Manual}, for
17449 details.)
17450
17451 The command invoked by the keys is @code{compare-windows}. Note that
17452 @code{compare-windows} is preceded by a single quote; otherwise, Emacs
17453 would first try to evaluate the symbol to determine its value.
17454
17455 These three things, the double quotation marks, the backslash before
17456 the @samp{C}, and the single quote mark are necessary parts of
17457 keybinding that I tend to forget. Fortunately, I have come to
17458 remember that I should look at my existing @file{.emacs} file, and
17459 adapt what is there.
17460
17461 As for the keybinding itself: @kbd{C-c w}. This combines the prefix
17462 key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
17463 set of keys, @kbd{C-c} followed by a single character, is strictly
17464 reserved for individuals' own use. (I call these `own' keys, since
17465 these are for my own use.) You should always be able to create such a
17466 keybinding for your own use without stomping on someone else's
17467 keybinding. If you ever write an extension to Emacs, please avoid
17468 taking any of these keys for public use. Create a key like @kbd{C-c
17469 C-w} instead. Otherwise, we will run out of `own' keys.
17470
17471 @need 1250
17472 Here is another keybinding, with a comment:
17473
17474 @smallexample
17475 @group
17476 ;;; Keybinding for `occur'
17477 ; I use occur a lot, so let's bind it to a key:
17478 (global-set-key "\C-co" 'occur)
17479 @end group
17480 @end smallexample
17481
17482 @findex occur
17483 The @code{occur} command shows all the lines in the current buffer
17484 that contain a match for a regular expression. Matching lines are
17485 shown in a buffer called @file{*Occur*}. That buffer serves as a menu
17486 to jump to occurrences.
17487
17488 @findex global-unset-key
17489 @cindex Unbinding key
17490 @cindex Key unbinding
17491 @need 1250
17492 Here is how to unbind a key, so it does not
17493 work:
17494
17495 @smallexample
17496 @group
17497 ;;; Unbind `C-x f'
17498 (global-unset-key "\C-xf")
17499 @end group
17500 @end smallexample
17501
17502 There is a reason for this unbinding: I found I inadvertently typed
17503 @w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
17504 file, as I intended, I accidentally set the width for filled text,
17505 almost always to a width I did not want. Since I hardly ever reset my
17506 default width, I simply unbound the key.
17507
17508 @findex list-buffers, @r{rebound}
17509 @findex buffer-menu, @r{bound to key}
17510 @need 1250
17511 The following rebinds an existing key:
17512
17513 @smallexample
17514 @group
17515 ;;; Rebind `C-x C-b' for `buffer-menu'
17516 (global-set-key "\C-x\C-b" 'buffer-menu)
17517 @end group
17518 @end smallexample
17519
17520 By default, @kbd{C-x C-b} runs the
17521 @code{list-buffers} command. This command lists
17522 your buffers in @emph{another} window. Since I
17523 almost always want to do something in that
17524 window, I prefer the @code{buffer-menu}
17525 command, which not only lists the buffers,
17526 but moves point into that window.
17527
17528 @node Keymaps
17529 @section Keymaps
17530 @cindex Keymaps
17531 @cindex Rebinding keys
17532
17533 Emacs uses @dfn{keymaps} to record which keys call which commands.
17534 When you use @code{global-set-key} to set the keybinding for a single
17535 command in all parts of Emacs, you are specifying the keybinding in
17536 @code{current-global-map}.
17537
17538 Specific modes, such as C mode or Text mode, have their own keymaps;
17539 the mode-specific keymaps override the global map that is shared by
17540 all buffers.
17541
17542 The @code{global-set-key} function binds, or rebinds, the global
17543 keymap. For example, the following binds the key @kbd{C-x C-b} to the
17544 function @code{buffer-menu}:
17545
17546 @smallexample
17547 (global-set-key "\C-x\C-b" 'buffer-menu)
17548 @end smallexample
17549
17550 Mode-specific keymaps are bound using the @code{define-key} function,
17551 which takes a specific keymap as an argument, as well as the key and
17552 the command. For example, my @file{.emacs} file contains the
17553 following expression to bind the @code{texinfo-insert-@@group} command
17554 to @kbd{C-c C-c g}:
17555
17556 @smallexample
17557 @group
17558 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
17559 @end group
17560 @end smallexample
17561
17562 @noindent
17563 The @code{texinfo-insert-@@group} function itself is a little extension
17564 to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
17565 use this command all the time and prefer to type the three strokes
17566 @kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
17567 (@samp{@@group} and its matching @samp{@@end group} are commands that
17568 keep all enclosed text together on one page; many multi-line examples
17569 in this book are surrounded by @samp{@@group @dots{} @@end group}.)
17570
17571 @need 1250
17572 Here is the @code{texinfo-insert-@@group} function definition:
17573
17574 @smallexample
17575 @group
17576 (defun texinfo-insert-@@group ()
17577 "Insert the string @@group in a Texinfo buffer."
17578 (interactive)
17579 (beginning-of-line)
17580 (insert "@@group\n"))
17581 @end group
17582 @end smallexample
17583
17584 (Of course, I could have used Abbrev mode to save typing, rather than
17585 write a function to insert a word; but I prefer key strokes consistent
17586 with other Texinfo mode key bindings.)
17587
17588 You will see numerous @code{define-key} expressions in
17589 @file{loaddefs.el} as well as in the various mode libraries, such as
17590 @file{cc-mode.el} and @file{lisp-mode.el}.
17591
17592 @xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
17593 Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
17594 Reference Manual}, for more information about keymaps.
17595
17596 @node Loading Files
17597 @section Loading Files
17598 @cindex Loading files
17599 @c findex load
17600
17601 Many people in the GNU Emacs community have written extensions to
17602 Emacs. As time goes by, these extensions are often included in new
17603 releases. For example, the Calendar and Diary packages are now part
17604 of the standard GNU Emacs, as is Calc.
17605
17606 You can use a @code{load} command to evaluate a complete file and
17607 thereby install all the functions and variables in the file into Emacs.
17608 For example:
17609
17610 @c (auto-compression-mode t)
17611
17612 @smallexample
17613 (load "~/emacs/slowsplit")
17614 @end smallexample
17615
17616 This evaluates, i.e., loads, the @file{slowsplit.el} file or if it
17617 exists, the faster, byte compiled @file{slowsplit.elc} file from the
17618 @file{emacs} sub-directory of your home directory. The file contains
17619 the function @code{split-window-quietly}, which John Robinson wrote in
17620 1989.
17621
17622 The @code{split-window-quietly} function splits a window with the
17623 minimum of redisplay. I installed it in 1989 because it worked well
17624 with the slow 1200 baud terminals I was then using. Nowadays, I only
17625 occasionally come across such a slow connection, but I continue to use
17626 the function because I like the way it leaves the bottom half of a
17627 buffer in the lower of the new windows and the top half in the upper
17628 window.
17629
17630 @need 1250
17631 To replace the key binding for the default
17632 @code{split-window-vertically}, you must also unset that key and bind
17633 the keys to @code{split-window-quietly}, like this:
17634
17635 @smallexample
17636 @group
17637 (global-unset-key "\C-x2")
17638 (global-set-key "\C-x2" 'split-window-quietly)
17639 @end group
17640 @end smallexample
17641
17642 @vindex load-path
17643 If you load many extensions, as I do, then instead of specifying the
17644 exact location of the extension file, as shown above, you can specify
17645 that directory as part of Emacs's @code{load-path}. Then, when Emacs
17646 loads a file, it will search that directory as well as its default
17647 list of directories. (The default list is specified in @file{paths.h}
17648 when Emacs is built.)
17649
17650 @need 1250
17651 The following command adds your @file{~/emacs} directory to the
17652 existing load path:
17653
17654 @smallexample
17655 @group
17656 ;;; Emacs Load Path
17657 (setq load-path (cons "~/emacs" load-path))
17658 @end group
17659 @end smallexample
17660
17661 Incidentally, @code{load-library} is an interactive interface to the
17662 @code{load} function. The complete function looks like this:
17663
17664 @findex load-library
17665 @smallexample
17666 @group
17667 (defun load-library (library)
17668 "Load the library named LIBRARY.
17669 This is an interface to the function `load'."
17670 (interactive
17671 (list (completing-read "Load library: "
17672 (apply-partially 'locate-file-completion-table
17673 load-path
17674 (get-load-suffixes)))))
17675 (load library))
17676 @end group
17677 @end smallexample
17678
17679 The name of the function, @code{load-library}, comes from the use of
17680 `library' as a conventional synonym for `file'. The source for the
17681 @code{load-library} command is in the @file{files.el} library.
17682
17683 Another interactive command that does a slightly different job is
17684 @code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
17685 Emacs, emacs, The GNU Emacs Manual}, for information on the
17686 distinction between @code{load-library} and this command.
17687
17688 @node Autoload
17689 @section Autoloading
17690 @findex autoload
17691
17692 Instead of installing a function by loading the file that contains it,
17693 or by evaluating the function definition, you can make the function
17694 available but not actually install it until it is first called. This
17695 is called @dfn{autoloading}.
17696
17697 When you execute an autoloaded function, Emacs automatically evaluates
17698 the file that contains the definition, and then calls the function.
17699
17700 Emacs starts quicker with autoloaded functions, since their libraries
17701 are not loaded right away; but you need to wait a moment when you
17702 first use such a function, while its containing file is evaluated.
17703
17704 Rarely used functions are frequently autoloaded. The
17705 @file{loaddefs.el} library contains hundreds of autoloaded functions,
17706 from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
17707 come to use a `rare' function frequently. When you do, you should
17708 load that function's file with a @code{load} expression in your
17709 @file{.emacs} file.
17710
17711 In my @file{.emacs} file, I load 14 libraries that contain functions
17712 that would otherwise be autoloaded. (Actually, it would have been
17713 better to include these files in my `dumped' Emacs, but I forgot.
17714 @xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17715 Reference Manual}, and the @file{INSTALL} file for more about
17716 dumping.)
17717
17718 You may also want to include autoloaded expressions in your @file{.emacs}
17719 file. @code{autoload} is a built-in function that takes up to five
17720 arguments, the final three of which are optional. The first argument
17721 is the name of the function to be autoloaded; the second is the name
17722 of the file to be loaded. The third argument is documentation for the
17723 function, and the fourth tells whether the function can be called
17724 interactively. The fifth argument tells what type of
17725 object---@code{autoload} can handle a keymap or macro as well as a
17726 function (the default is a function).
17727
17728 @need 800
17729 Here is a typical example:
17730
17731 @smallexample
17732 @group
17733 (autoload 'html-helper-mode
17734 "html-helper-mode" "Edit HTML documents" t)
17735 @end group
17736 @end smallexample
17737
17738 @noindent
17739 (@code{html-helper-mode} is an older alternative to @code{html-mode},
17740 which is a standard part of the distribution.)
17741
17742 @noindent
17743 This expression autoloads the @code{html-helper-mode} function. It
17744 takes it from the @file{html-helper-mode.el} file (or from the byte
17745 compiled version @file{html-helper-mode.elc}, if that exists.) The
17746 file must be located in a directory specified by @code{load-path}.
17747 The documentation says that this is a mode to help you edit documents
17748 written in the HyperText Markup Language. You can call this mode
17749 interactively by typing @kbd{M-x html-helper-mode}. (You need to
17750 duplicate the function's regular documentation in the autoload
17751 expression because the regular function is not yet loaded, so its
17752 documentation is not available.)
17753
17754 @xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
17755 Manual}, for more information.
17756
17757 @node Simple Extension
17758 @section A Simple Extension: @code{line-to-top-of-window}
17759 @findex line-to-top-of-window
17760 @cindex Simple extension in @file{.emacs} file
17761
17762 Here is a simple extension to Emacs that moves the line point is on to
17763 the top of the window. I use this all the time, to make text easier
17764 to read.
17765
17766 You can put the following code into a separate file and then load it
17767 from your @file{.emacs} file, or you can include it within your
17768 @file{.emacs} file.
17769
17770 @need 1250
17771 Here is the definition:
17772
17773 @smallexample
17774 @group
17775 ;;; Line to top of window;
17776 ;;; replace three keystroke sequence C-u 0 C-l
17777 (defun line-to-top-of-window ()
17778 "Move the line point is on to top of window."
17779 (interactive)
17780 (recenter 0))
17781 @end group
17782 @end smallexample
17783
17784 @need 1250
17785 Now for the keybinding.
17786
17787 Nowadays, function keys as well as mouse button events and
17788 non-@sc{ascii} characters are written within square brackets, without
17789 quotation marks. (In Emacs version 18 and before, you had to write
17790 different function key bindings for each different make of terminal.)
17791
17792 I bind @code{line-to-top-of-window} to my @key{F6} function key like
17793 this:
17794
17795 @smallexample
17796 (global-set-key [f6] 'line-to-top-of-window)
17797 @end smallexample
17798
17799 For more information, see @ref{Init Rebinding, , Rebinding Keys in
17800 Your Init File, emacs, The GNU Emacs Manual}.
17801
17802 @cindex Conditional 'twixt two versions of Emacs
17803 @cindex Version of Emacs, choosing
17804 @cindex Emacs version, choosing
17805 If you run two versions of GNU Emacs, such as versions 22 and 23, and
17806 use one @file{.emacs} file, you can select which code to evaluate with
17807 the following conditional:
17808
17809 @smallexample
17810 @group
17811 (cond
17812 ((= 22 emacs-major-version)
17813 ;; evaluate version 22 code
17814 ( @dots{} ))
17815 ((= 23 emacs-major-version)
17816 ;; evaluate version 23 code
17817 ( @dots{} )))
17818 @end group
17819 @end smallexample
17820
17821 For example, recent versions blink
17822 their cursors by default. I hate such blinking, as well as other
17823 features, so I placed the following in my @file{.emacs}
17824 file@footnote{When I start instances of Emacs that do not load my
17825 @file{.emacs} file or any site file, I also turn off blinking:
17826
17827 @smallexample
17828 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
17829
17830 @exdent Or nowadays, using an even more sophisticated set of options,
17831
17832 emacs -Q - D
17833 @end smallexample
17834 }:
17835
17836 @smallexample
17837 @group
17838 (when (>= emacs-major-version 21)
17839 (blink-cursor-mode 0)
17840 ;; Insert newline when you press `C-n' (next-line)
17841 ;; at the end of the buffer
17842 (setq next-line-add-newlines t)
17843 @end group
17844 @group
17845 ;; Turn on image viewing
17846 (auto-image-file-mode t)
17847 @end group
17848 @group
17849 ;; Turn on menu bar (this bar has text)
17850 ;; (Use numeric argument to turn on)
17851 (menu-bar-mode 1)
17852 @end group
17853 @group
17854 ;; Turn off tool bar (this bar has icons)
17855 ;; (Use numeric argument to turn on)
17856 (tool-bar-mode nil)
17857 @end group
17858 @group
17859 ;; Turn off tooltip mode for tool bar
17860 ;; (This mode causes icon explanations to pop up)
17861 ;; (Use numeric argument to turn on)
17862 (tooltip-mode nil)
17863 ;; If tooltips turned on, make tips appear promptly
17864 (setq tooltip-delay 0.1) ; default is 0.7 second
17865 )
17866 @end group
17867 @end smallexample
17868
17869 @node X11 Colors
17870 @section X11 Colors
17871
17872 You can specify colors when you use Emacs with the MIT X Windowing
17873 system.
17874
17875 I dislike the default colors and specify my own.
17876
17877 @need 1250
17878 Here are the expressions in my @file{.emacs}
17879 file that set values:
17880
17881 @smallexample
17882 @group
17883 ;; Set cursor color
17884 (set-cursor-color "white")
17885
17886 ;; Set mouse color
17887 (set-mouse-color "white")
17888
17889 ;; Set foreground and background
17890 (set-foreground-color "white")
17891 (set-background-color "darkblue")
17892 @end group
17893
17894 @group
17895 ;;; Set highlighting colors for isearch and drag
17896 (set-face-foreground 'highlight "white")
17897 (set-face-background 'highlight "blue")
17898 @end group
17899
17900 @group
17901 (set-face-foreground 'region "cyan")
17902 (set-face-background 'region "blue")
17903 @end group
17904
17905 @group
17906 (set-face-foreground 'secondary-selection "skyblue")
17907 (set-face-background 'secondary-selection "darkblue")
17908 @end group
17909
17910 @group
17911 ;; Set calendar highlighting colors
17912 (setq calendar-load-hook
17913 (lambda ()
17914 (set-face-foreground 'diary-face "skyblue")
17915 (set-face-background 'holiday-face "slate blue")
17916 (set-face-foreground 'holiday-face "white")))
17917 @end group
17918 @end smallexample
17919
17920 The various shades of blue soothe my eye and prevent me from seeing
17921 the screen flicker.
17922
17923 Alternatively, I could have set my specifications in various X
17924 initialization files. For example, I could set the foreground,
17925 background, cursor, and pointer (i.e., mouse) colors in my
17926 @file{~/.Xresources} file like this:
17927
17928 @smallexample
17929 @group
17930 Emacs*foreground: white
17931 Emacs*background: darkblue
17932 Emacs*cursorColor: white
17933 Emacs*pointerColor: white
17934 @end group
17935 @end smallexample
17936
17937 In any event, since it is not part of Emacs, I set the root color of
17938 my X window in my @file{~/.xinitrc} file, like this@footnote{I also
17939 run more modern window managers, such as Enlightenment, Gnome, or KDE;
17940 in those cases, I often specify an image rather than a plain color.}:
17941
17942 @smallexample
17943 xsetroot -solid Navy -fg white &
17944 @end smallexample
17945
17946 @need 1700
17947 @node Miscellaneous
17948 @section Miscellaneous Settings for a @file{.emacs} File
17949
17950 @need 1250
17951 Here are a few miscellaneous settings:
17952 @sp 1
17953
17954 @itemize @minus
17955 @item
17956 Set the shape and color of the mouse cursor:
17957
17958 @smallexample
17959 @group
17960 ; Cursor shapes are defined in
17961 ; `/usr/include/X11/cursorfont.h';
17962 ; for example, the `target' cursor is number 128;
17963 ; the `top_left_arrow' cursor is number 132.
17964 @end group
17965
17966 @group
17967 (let ((mpointer (x-get-resource "*mpointer"
17968 "*emacs*mpointer")))
17969 ;; If you have not set your mouse pointer
17970 ;; then set it, otherwise leave as is:
17971 (if (eq mpointer nil)
17972 (setq mpointer "132")) ; top_left_arrow
17973 @end group
17974 @group
17975 (setq x-pointer-shape (string-to-int mpointer))
17976 (set-mouse-color "white"))
17977 @end group
17978 @end smallexample
17979
17980 @item
17981 Or you can set the values of a variety of features in an alist, like
17982 this:
17983
17984 @smallexample
17985 @group
17986 (setq-default
17987 default-frame-alist
17988 '((cursor-color . "white")
17989 (mouse-color . "white")
17990 (foreground-color . "white")
17991 (background-color . "DodgerBlue4")
17992 ;; (cursor-type . bar)
17993 (cursor-type . box)
17994 @end group
17995 @group
17996 (tool-bar-lines . 0)
17997 (menu-bar-lines . 1)
17998 (width . 80)
17999 (height . 58)
18000 (font .
18001 "-Misc-Fixed-Medium-R-Normal--20-200-75-75-C-100-ISO8859-1")
18002 ))
18003 @end group
18004 @end smallexample
18005
18006 @item
18007 Convert @kbd{@key{CTRL}-h} into @key{DEL} and @key{DEL}
18008 into @kbd{@key{CTRL}-h}.@*
18009 (Some older keyboards needed this, although I have not seen the
18010 problem recently.)
18011
18012 @smallexample
18013 @group
18014 ;; Translate `C-h' to <DEL>.
18015 ; (keyboard-translate ?\C-h ?\C-?)
18016
18017 ;; Translate <DEL> to `C-h'.
18018 (keyboard-translate ?\C-? ?\C-h)
18019 @end group
18020 @end smallexample
18021
18022 @item Turn off a blinking cursor!
18023
18024 @smallexample
18025 @group
18026 (if (fboundp 'blink-cursor-mode)
18027 (blink-cursor-mode -1))
18028 @end group
18029 @end smallexample
18030
18031 @noindent
18032 or start GNU Emacs with the command @code{emacs -nbc}.
18033
18034 @need 1250
18035 @item When using `grep'@*
18036 @samp{-i}@w{ } Ignore case distinctions@*
18037 @samp{-n}@w{ } Prefix each line of output with line number@*
18038 @samp{-H}@w{ } Print the filename for each match.@*
18039 @samp{-e}@w{ } Protect patterns beginning with a hyphen character, @samp{-}
18040
18041 @smallexample
18042 (setq grep-command "grep -i -nH -e ")
18043 @end smallexample
18044
18045 @ignore
18046 @c Evidently, no longer needed in GNU Emacs 22
18047
18048 item Automatically uncompress compressed files when visiting them
18049
18050 smallexample
18051 (load "uncompress")
18052 end smallexample
18053
18054 @end ignore
18055
18056 @item Find an existing buffer, even if it has a different name@*
18057 This avoids problems with symbolic links.
18058
18059 @smallexample
18060 (setq find-file-existing-other-name t)
18061 @end smallexample
18062
18063 @item Set your language environment and default input method
18064
18065 @smallexample
18066 @group
18067 (set-language-environment "latin-1")
18068 ;; Remember you can enable or disable multilingual text input
18069 ;; with the @code{toggle-input-method'} (@kbd{C-\}) command
18070 (setq default-input-method "latin-1-prefix")
18071 @end group
18072 @end smallexample
18073
18074 If you want to write with Chinese `GB' characters, set this instead:
18075
18076 @smallexample
18077 @group
18078 (set-language-environment "Chinese-GB")
18079 (setq default-input-method "chinese-tonepy")
18080 @end group
18081 @end smallexample
18082 @end itemize
18083
18084 @subsubheading Fixing Unpleasant Key Bindings
18085 @cindex Key bindings, fixing
18086 @cindex Bindings, key, fixing unpleasant
18087
18088 Some systems bind keys unpleasantly. Sometimes, for example, the
18089 @key{CTRL} key appears in an awkward spot rather than at the far left
18090 of the home row.
18091
18092 Usually, when people fix these sorts of keybindings, they do not
18093 change their @file{~/.emacs} file. Instead, they bind the proper keys
18094 on their consoles with the @code{loadkeys} or @code{install-keymap}
18095 commands in their boot script and then include @code{xmodmap} commands
18096 in their @file{.xinitrc} or @file{.Xsession} file for X Windows.
18097
18098 @need 1250
18099 @noindent
18100 For a boot script:
18101
18102 @smallexample
18103 @group
18104 loadkeys /usr/share/keymaps/i386/qwerty/emacs2.kmap.gz
18105 @exdent or
18106 install-keymap emacs2
18107 @end group
18108 @end smallexample
18109
18110 @need 1250
18111 @noindent
18112 For a @file{.xinitrc} or @file{.Xsession} file when the @key{Caps
18113 Lock} key is at the far left of the home row:
18114
18115 @smallexample
18116 @group
18117 # Bind the key labeled `Caps Lock' to `Control'
18118 # (Such a broken user interface suggests that keyboard manufacturers
18119 # think that computers are typewriters from 1885.)
18120
18121 xmodmap -e "clear Lock"
18122 xmodmap -e "add Control = Caps_Lock"
18123 @end group
18124 @end smallexample
18125
18126 @need 1250
18127 @noindent
18128 In a @file{.xinitrc} or @file{.Xsession} file, to convert an @key{ALT}
18129 key to a @key{META} key:
18130
18131 @smallexample
18132 @group
18133 # Some ill designed keyboards have a key labeled ALT and no Meta
18134 xmodmap -e "keysym Alt_L = Meta_L Alt_L"
18135 @end group
18136 @end smallexample
18137
18138 @need 1700
18139 @node Mode Line
18140 @section A Modified Mode Line
18141 @vindex mode-line-format
18142 @cindex Mode line format
18143
18144 Finally, a feature I really like: a modified mode line.
18145
18146 When I work over a network, I forget which machine I am using. Also,
18147 I tend to I lose track of where I am, and which line point is on.
18148
18149 So I reset my mode line to look like this:
18150
18151 @smallexample
18152 -:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
18153 @end smallexample
18154
18155 I am visiting a file called @file{foo.texi}, on my machine
18156 @file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
18157 Texinfo mode, and am at the top of the buffer.
18158
18159 @need 1200
18160 My @file{.emacs} file has a section that looks like this:
18161
18162 @smallexample
18163 @group
18164 ;; Set a Mode Line that tells me which machine, which directory,
18165 ;; and which line I am on, plus the other customary information.
18166 (setq-default mode-line-format
18167 (quote
18168 (#("-" 0 1
18169 (help-echo
18170 "mouse-1: select window, mouse-2: delete others ..."))
18171 mode-line-mule-info
18172 mode-line-modified
18173 mode-line-frame-identification
18174 " "
18175 @end group
18176 @group
18177 mode-line-buffer-identification
18178 " "
18179 (:eval (substring
18180 (system-name) 0 (string-match "\\..+" (system-name))))
18181 ":"
18182 default-directory
18183 #(" " 0 1
18184 (help-echo
18185 "mouse-1: select window, mouse-2: delete others ..."))
18186 (line-number-mode " Line %l ")
18187 global-mode-string
18188 @end group
18189 @group
18190 #(" %[(" 0 6
18191 (help-echo
18192 "mouse-1: select window, mouse-2: delete others ..."))
18193 (:eval (mode-line-mode-name))
18194 mode-line-process
18195 minor-mode-alist
18196 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
18197 ")%] "
18198 (-3 . "%P")
18199 ;; "-%-"
18200 )))
18201 @end group
18202 @end smallexample
18203
18204 @noindent
18205 Here, I redefine the default mode line. Most of the parts are from
18206 the original; but I make a few changes. I set the @emph{default} mode
18207 line format so as to permit various modes, such as Info, to override
18208 it.
18209
18210 Many elements in the list are self-explanatory:
18211 @code{mode-line-modified} is a variable that tells whether the buffer
18212 has been modified, @code{mode-name} tells the name of the mode, and so
18213 on. However, the format looks complicated because of two features we
18214 have not discussed.
18215
18216 @cindex Properties, in mode line example
18217 The first string in the mode line is a dash or hyphen, @samp{-}. In
18218 the old days, it would have been specified simply as @code{"-"}. But
18219 nowadays, Emacs can add properties to a string, such as highlighting
18220 or, as in this case, a help feature. If you place your mouse cursor
18221 over the hyphen, some help information appears (By default, you must
18222 wait seven-tenths of a second before the information appears. You can
18223 change that timing by changing the value of @code{tooltip-delay}.)
18224
18225 @need 1000
18226 The new string format has a special syntax:
18227
18228 @smallexample
18229 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
18230 @end smallexample
18231
18232 @noindent
18233 The @code{#(} begins a list. The first element of the list is the
18234 string itself, just one @samp{-}. The second and third
18235 elements specify the range over which the fourth element applies. A
18236 range starts @emph{after} a character, so a zero means the range
18237 starts just before the first character; a 1 means that the range ends
18238 just after the first character. The third element is the property for
18239 the range. It consists of a property list, a
18240 property name, in this case, @samp{help-echo}, followed by a value, in this
18241 case, a string. The second, third, and fourth elements of this new
18242 string format can be repeated.
18243
18244 @xref{Text Properties, , Text Properties, elisp, The GNU Emacs Lisp
18245 Reference Manual}, and see @ref{Mode Line Format, , Mode Line Format,
18246 elisp, The GNU Emacs Lisp Reference Manual}, for more information.
18247
18248 @code{mode-line-buffer-identification}
18249 displays the current buffer name. It is a list
18250 beginning @code{(#("%12b" 0 4 @dots{}}.
18251 The @code{#(} begins the list.
18252
18253 The @samp{"%12b"} displays the current buffer name, using the
18254 @code{buffer-name} function with which we are familiar; the `12'
18255 specifies the maximum number of characters that will be displayed.
18256 When a name has fewer characters, whitespace is added to fill out to
18257 this number. (Buffer names can and often should be longer than 12
18258 characters; this length works well in a typical 80 column wide
18259 window.)
18260
18261 @code{:eval} says to evaluate the following form and use the result as
18262 a string to display. In this case, the expression displays the first
18263 component of the full system name. The end of the first component is
18264 a @samp{.} (`period'), so I use the @code{string-match} function to
18265 tell me the length of the first component. The substring from the
18266 zeroth character to that length is the name of the machine.
18267
18268 @need 1250
18269 This is the expression:
18270
18271 @smallexample
18272 @group
18273 (:eval (substring
18274 (system-name) 0 (string-match "\\..+" (system-name))))
18275 @end group
18276 @end smallexample
18277
18278 @samp{%[} and @samp{%]} cause a pair of square brackets
18279 to appear for each recursive editing level. @samp{%n} says `Narrow'
18280 when narrowing is in effect. @samp{%P} tells you the percentage of
18281 the buffer that is above the bottom of the window, or `Top', `Bottom',
18282 or `All'. (A lower case @samp{p} tell you the percentage above the
18283 @emph{top} of the window.) @samp{%-} inserts enough dashes to fill
18284 out the line.
18285
18286 Remember, ``You don't have to like Emacs to like it''---your own
18287 Emacs can have different colors, different commands, and different
18288 keys than a default Emacs.
18289
18290 On the other hand, if you want to bring up a plain `out of the box'
18291 Emacs, with no customization, type:
18292
18293 @smallexample
18294 emacs -q
18295 @end smallexample
18296
18297 @noindent
18298 This will start an Emacs that does @emph{not} load your
18299 @file{~/.emacs} initialization file. A plain, default Emacs. Nothing
18300 more.
18301
18302 @node Debugging
18303 @chapter Debugging
18304 @cindex debugging
18305
18306 GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
18307 first is built into the internals of Emacs and is always with you;
18308 the second requires that you instrument a function before you can use it.
18309
18310 Both debuggers are described extensively in @ref{Debugging, ,
18311 Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
18312 In this chapter, I will walk through a short example of each.
18313
18314 @menu
18315 * debug:: How to use the built-in debugger.
18316 * debug-on-entry:: Start debugging when you call a function.
18317 * debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
18318 * edebug:: How to use Edebug, a source level debugger.
18319 * Debugging Exercises::
18320 @end menu
18321
18322 @node debug
18323 @section @code{debug}
18324 @findex debug
18325
18326 Suppose you have written a function definition that is intended to
18327 return the sum of the numbers 1 through a given number. (This is the
18328 @code{triangle} function discussed earlier. @xref{Decrementing
18329 Example, , Example with Decrementing Counter}, for a discussion.)
18330 @c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
18331
18332 However, your function definition has a bug. You have mistyped
18333 @samp{1=} for @samp{1-}. Here is the broken definition:
18334
18335 @findex triangle-bugged
18336 @smallexample
18337 @group
18338 (defun triangle-bugged (number)
18339 "Return sum of numbers 1 through NUMBER inclusive."
18340 (let ((total 0))
18341 (while (> number 0)
18342 (setq total (+ total number))
18343 (setq number (1= number))) ; @r{Error here.}
18344 total))
18345 @end group
18346 @end smallexample
18347
18348 If you are reading this in Info, you can evaluate this definition in
18349 the normal fashion. You will see @code{triangle-bugged} appear in the
18350 echo area.
18351
18352 @need 1250
18353 Now evaluate the @code{triangle-bugged} function with an
18354 argument of 4:
18355
18356 @smallexample
18357 (triangle-bugged 4)
18358 @end smallexample
18359
18360 @noindent
18361 In a recent GNU Emacs, you will create and enter a @file{*Backtrace*}
18362 buffer that says:
18363
18364 @noindent
18365 @smallexample
18366 @group
18367 ---------- Buffer: *Backtrace* ----------
18368 Debugger entered--Lisp error: (void-function 1=)
18369 (1= number)
18370 (setq number (1= number))
18371 (while (> number 0) (setq total (+ total number))
18372 (setq number (1= number)))
18373 (let ((total 0)) (while (> number 0) (setq total ...)
18374 (setq number ...)) total)
18375 triangle-bugged(4)
18376 @end group
18377 @group
18378 eval((triangle-bugged 4))
18379 eval-last-sexp-1(nil)
18380 eval-last-sexp(nil)
18381 call-interactively(eval-last-sexp)
18382 ---------- Buffer: *Backtrace* ----------
18383 @end group
18384 @end smallexample
18385
18386 @noindent
18387 (I have reformatted this example slightly; the debugger does not fold
18388 long lines. As usual, you can quit the debugger by typing @kbd{q} in
18389 the @file{*Backtrace*} buffer.)
18390
18391 In practice, for a bug as simple as this, the `Lisp error' line will
18392 tell you what you need to know to correct the definition. The
18393 function @code{1=} is `void'.
18394
18395 @ignore
18396 @need 800
18397 In GNU Emacs 20 and before, you will see:
18398
18399 @smallexample
18400 Symbol's function definition is void:@: 1=
18401 @end smallexample
18402
18403 @noindent
18404 which has the same meaning as the @file{*Backtrace*} buffer line in
18405 version 21.
18406 @end ignore
18407
18408 However, suppose you are not quite certain what is going on?
18409 You can read the complete backtrace.
18410
18411 In this case, you need to run a recent GNU Emacs, which automatically
18412 starts the debugger that puts you in the @file{*Backtrace*} buffer; or
18413 else, you need to start the debugger manually as described below.
18414
18415 Read the @file{*Backtrace*} buffer from the bottom up; it tells you
18416 what Emacs did that led to the error. Emacs made an interactive call
18417 to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
18418 of the @code{triangle-bugged} expression. Each line above tells you
18419 what the Lisp interpreter evaluated next.
18420
18421 @need 1250
18422 The third line from the top of the buffer is
18423
18424 @smallexample
18425 (setq number (1= number))
18426 @end smallexample
18427
18428 @noindent
18429 Emacs tried to evaluate this expression; in order to do so, it tried
18430 to evaluate the inner expression shown on the second line from the
18431 top:
18432
18433 @smallexample
18434 (1= number)
18435 @end smallexample
18436
18437 @need 1250
18438 @noindent
18439 This is where the error occurred; as the top line says:
18440
18441 @smallexample
18442 Debugger entered--Lisp error: (void-function 1=)
18443 @end smallexample
18444
18445 @noindent
18446 You can correct the mistake, re-evaluate the function definition, and
18447 then run your test again.
18448
18449 @node debug-on-entry
18450 @section @code{debug-on-entry}
18451 @findex debug-on-entry
18452
18453 A recent GNU Emacs starts the debugger automatically when your
18454 function has an error.
18455
18456 @ignore
18457 GNU Emacs version 20 and before did not; it simply
18458 presented you with an error message. You had to start the debugger
18459 manually.
18460 @end ignore
18461
18462 Incidentally, you can start the debugger manually for all versions of
18463 Emacs; the advantage is that the debugger runs even if you do not have
18464 a bug in your code. Sometimes your code will be free of bugs!
18465
18466 You can enter the debugger when you call the function by calling
18467 @code{debug-on-entry}.
18468
18469 @need 1250
18470 @noindent
18471 Type:
18472
18473 @smallexample
18474 M-x debug-on-entry RET triangle-bugged RET
18475 @end smallexample
18476
18477 @need 1250
18478 @noindent
18479 Now, evaluate the following:
18480
18481 @smallexample
18482 (triangle-bugged 5)
18483 @end smallexample
18484
18485 @noindent
18486 All versions of Emacs will create a @file{*Backtrace*} buffer and tell
18487 you that it is beginning to evaluate the @code{triangle-bugged}
18488 function:
18489
18490 @smallexample
18491 @group
18492 ---------- Buffer: *Backtrace* ----------
18493 Debugger entered--entering a function:
18494 * triangle-bugged(5)
18495 eval((triangle-bugged 5))
18496 @end group
18497 @group
18498 eval-last-sexp-1(nil)
18499 eval-last-sexp(nil)
18500 call-interactively(eval-last-sexp)
18501 ---------- Buffer: *Backtrace* ----------
18502 @end group
18503 @end smallexample
18504
18505 In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
18506 the first expression in @code{triangle-bugged}; the buffer will look
18507 like this:
18508
18509 @smallexample
18510 @group
18511 ---------- Buffer: *Backtrace* ----------
18512 Debugger entered--beginning evaluation of function call form:
18513 * (let ((total 0)) (while (> number 0) (setq total ...)
18514 (setq number ...)) total)
18515 * triangle-bugged(5)
18516 eval((triangle-bugged 5))
18517 @end group
18518 @group
18519 eval-last-sexp-1(nil)
18520 eval-last-sexp(nil)
18521 call-interactively(eval-last-sexp)
18522 ---------- Buffer: *Backtrace* ----------
18523 @end group
18524 @end smallexample
18525
18526 @noindent
18527 Now, type @kbd{d} again, eight times, slowly. Each time you type
18528 @kbd{d}, Emacs will evaluate another expression in the function
18529 definition.
18530
18531 @need 1750
18532 Eventually, the buffer will look like this:
18533
18534 @smallexample
18535 @group
18536 ---------- Buffer: *Backtrace* ----------
18537 Debugger entered--beginning evaluation of function call form:
18538 * (setq number (1= number))
18539 * (while (> number 0) (setq total (+ total number))
18540 (setq number (1= number)))
18541 @group
18542 @end group
18543 * (let ((total 0)) (while (> number 0) (setq total ...)
18544 (setq number ...)) total)
18545 * triangle-bugged(5)
18546 eval((triangle-bugged 5))
18547 @group
18548 @end group
18549 eval-last-sexp-1(nil)
18550 eval-last-sexp(nil)
18551 call-interactively(eval-last-sexp)
18552 ---------- Buffer: *Backtrace* ----------
18553 @end group
18554 @end smallexample
18555
18556 @need 1500
18557 @noindent
18558 Finally, after you type @kbd{d} two more times, Emacs will reach the
18559 error, and the top two lines of the @file{*Backtrace*} buffer will look
18560 like this:
18561
18562 @smallexample
18563 @group
18564 ---------- Buffer: *Backtrace* ----------
18565 Debugger entered--Lisp error: (void-function 1=)
18566 * (1= number)
18567 @dots{}
18568 ---------- Buffer: *Backtrace* ----------
18569 @end group
18570 @end smallexample
18571
18572 By typing @kbd{d}, you were able to step through the function.
18573
18574 You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
18575 quits the trace, but does not cancel @code{debug-on-entry}.
18576
18577 @findex cancel-debug-on-entry
18578 To cancel the effect of @code{debug-on-entry}, call
18579 @code{cancel-debug-on-entry} and the name of the function, like this:
18580
18581 @smallexample
18582 M-x cancel-debug-on-entry RET triangle-bugged RET
18583 @end smallexample
18584
18585 @noindent
18586 (If you are reading this in Info, cancel @code{debug-on-entry} now.)
18587
18588 @node debug-on-quit
18589 @section @code{debug-on-quit} and @code{(debug)}
18590
18591 In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
18592 there are two other ways to start @code{debug}.
18593
18594 @findex debug-on-quit
18595 You can start @code{debug} whenever you type @kbd{C-g}
18596 (@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
18597 @code{t}. This is useful for debugging infinite loops.
18598
18599 @need 1500
18600 @cindex @code{(debug)} in code
18601 Or, you can insert a line that says @code{(debug)} into your code
18602 where you want the debugger to start, like this:
18603
18604 @smallexample
18605 @group
18606 (defun triangle-bugged (number)
18607 "Return sum of numbers 1 through NUMBER inclusive."
18608 (let ((total 0))
18609 (while (> number 0)
18610 (setq total (+ total number))
18611 (debug) ; @r{Start debugger.}
18612 (setq number (1= number))) ; @r{Error here.}
18613 total))
18614 @end group
18615 @end smallexample
18616
18617 The @code{debug} function is described in detail in @ref{Debugger, ,
18618 The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
18619
18620 @node edebug
18621 @section The @code{edebug} Source Level Debugger
18622 @cindex Source level debugger
18623 @findex edebug
18624
18625 Edebug is a source level debugger. Edebug normally displays the
18626 source of the code you are debugging, with an arrow at the left that
18627 shows which line you are currently executing.
18628
18629 You can walk through the execution of a function, line by line, or run
18630 quickly until reaching a @dfn{breakpoint} where execution stops.
18631
18632 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18633 Lisp Reference Manual}.
18634
18635 @need 1250
18636 Here is a bugged function definition for @code{triangle-recursively}.
18637 @xref{Recursive triangle function, , Recursion in place of a counter},
18638 for a review of it.
18639
18640 @smallexample
18641 @group
18642 (defun triangle-recursively-bugged (number)
18643 "Return sum of numbers 1 through NUMBER inclusive.
18644 Uses recursion."
18645 (if (= number 1)
18646 1
18647 (+ number
18648 (triangle-recursively-bugged
18649 (1= number))))) ; @r{Error here.}
18650 @end group
18651 @end smallexample
18652
18653 @noindent
18654 Normally, you would install this definition by positioning your cursor
18655 after the function's closing parenthesis and typing @kbd{C-x C-e}
18656 (@code{eval-last-sexp}) or else by positioning your cursor within the
18657 definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
18658 the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
18659 Interaction mode.)
18660
18661 @need 1500
18662 However, to prepare this function definition for Edebug, you must
18663 first @dfn{instrument} the code using a different command. You can do
18664 this by positioning your cursor within or just after the definition
18665 and typing
18666
18667 @smallexample
18668 M-x edebug-defun RET
18669 @end smallexample
18670
18671 @noindent
18672 This will cause Emacs to load Edebug automatically if it is not
18673 already loaded, and properly instrument the function.
18674
18675 After instrumenting the function, place your cursor after the
18676 following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
18677
18678 @smallexample
18679 (triangle-recursively-bugged 3)
18680 @end smallexample
18681
18682 @noindent
18683 You will be jumped back to the source for
18684 @code{triangle-recursively-bugged} and the cursor positioned at the
18685 beginning of the @code{if} line of the function. Also, you will see
18686 an arrowhead at the left hand side of that line. The arrowhead marks
18687 the line where the function is executing. (In the following examples,
18688 we show the arrowhead with @samp{=>}; in a windowing system, you may
18689 see the arrowhead as a solid triangle in the window `fringe'.)
18690
18691 @smallexample
18692 =>@point{}(if (= number 1)
18693 @end smallexample
18694
18695 @noindent
18696 @iftex
18697 In the example, the location of point is displayed with a star,
18698 @samp{@point{}} (in Info, it is displayed as @samp{-!-}).
18699 @end iftex
18700 @ifnottex
18701 In the example, the location of point is displayed as @samp{@point{}}
18702 (in a printed book, it is displayed with a five pointed star).
18703 @end ifnottex
18704
18705 If you now press @key{SPC}, point will move to the next expression to
18706 be executed; the line will look like this:
18707
18708 @smallexample
18709 =>(if @point{}(= number 1)
18710 @end smallexample
18711
18712 @noindent
18713 As you continue to press @key{SPC}, point will move from expression to
18714 expression. At the same time, whenever an expression returns a value,
18715 that value will be displayed in the echo area. For example, after you
18716 move point past @code{number}, you will see the following:
18717
18718 @smallexample
18719 Result: 3 (#o3, #x3, ?\C-c)
18720 @end smallexample
18721
18722 @noindent
18723 This means the value of @code{number} is 3, which is octal three,
18724 hexadecimal three, and @sc{ascii} `control-c' (the third letter of the
18725 alphabet, in case you need to know this information).
18726
18727 You can continue moving through the code until you reach the line with
18728 the error. Before evaluation, that line looks like this:
18729
18730 @smallexample
18731 => @point{}(1= number))))) ; @r{Error here.}
18732 @end smallexample
18733
18734 @need 1250
18735 @noindent
18736 When you press @key{SPC} once again, you will produce an error message
18737 that says:
18738
18739 @smallexample
18740 Symbol's function definition is void:@: 1=
18741 @end smallexample
18742
18743 @noindent
18744 This is the bug.
18745
18746 Press @kbd{q} to quit Edebug.
18747
18748 To remove instrumentation from a function definition, simply
18749 re-evaluate it with a command that does not instrument it.
18750 For example, you could place your cursor after the definition's
18751 closing parenthesis and type @kbd{C-x C-e}.
18752
18753 Edebug does a great deal more than walk with you through a function.
18754 You can set it so it races through on its own, stopping only at an
18755 error or at specified stopping points; you can cause it to display the
18756 changing values of various expressions; you can find out how many
18757 times a function is called, and more.
18758
18759 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18760 Lisp Reference Manual}.
18761
18762 @need 1500
18763 @node Debugging Exercises
18764 @section Debugging Exercises
18765
18766 @itemize @bullet
18767 @item
18768 Install the @code{@value{COUNT-WORDS}} function and then cause it to
18769 enter the built-in debugger when you call it. Run the command on a
18770 region containing two words. You will need to press @kbd{d} a
18771 remarkable number of times. On your system, is a `hook' called after
18772 the command finishes? (For information on hooks, see @ref{Command
18773 Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
18774 Manual}.)
18775
18776 @item
18777 Copy @code{@value{COUNT-WORDS}} into the @file{*scratch*} buffer,
18778 instrument the function for Edebug, and walk through its execution.
18779 The function does not need to have a bug, although you can introduce
18780 one if you wish. If the function lacks a bug, the walk-through
18781 completes without problems.
18782
18783 @item
18784 While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
18785 (The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.,
18786 @kbd{@key{CTRL}-x} followed by an upper case @kbd{X}; use this prefix
18787 for commands made outside of the Edebug debugging buffer.)
18788
18789 @item
18790 In the Edebug debugging buffer, use the @kbd{p}
18791 (@code{edebug-bounce-point}) command to see where in the region the
18792 @code{@value{COUNT-WORDS}} is working.
18793
18794 @item
18795 Move point to some spot further down the function and then type the
18796 @kbd{h} (@code{edebug-goto-here}) command to jump to that location.
18797
18798 @item
18799 Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
18800 walk through the function on its own; use an upper case @kbd{T} for
18801 @code{edebug-Trace-fast-mode}.
18802
18803 @item
18804 Set a breakpoint, then run Edebug in Trace mode until it reaches the
18805 stopping point.
18806 @end itemize
18807
18808 @node Conclusion
18809 @chapter Conclusion
18810
18811 We have now reached the end of this Introduction. You have now
18812 learned enough about programming in Emacs Lisp to set values, to write
18813 simple @file{.emacs} files for yourself and your friends, and write
18814 simple customizations and extensions to Emacs.
18815
18816 This is a place to stop. Or, if you wish, you can now go onward, and
18817 teach yourself.
18818
18819 You have learned some of the basic nuts and bolts of programming. But
18820 only some. There are a great many more brackets and hinges that are
18821 easy to use that we have not touched.
18822
18823 A path you can follow right now lies among the sources to GNU Emacs
18824 and in
18825 @ifnotinfo
18826 @cite{The GNU Emacs Lisp Reference Manual}.
18827 @end ifnotinfo
18828 @ifinfo
18829 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
18830 Emacs Lisp Reference Manual}.
18831 @end ifinfo
18832
18833 The Emacs Lisp sources are an adventure. When you read the sources and
18834 come across a function or expression that is unfamiliar, you need to
18835 figure out or find out what it does.
18836
18837 Go to the Reference Manual. It is a thorough, complete, and fairly
18838 easy-to-read description of Emacs Lisp. It is written not only for
18839 experts, but for people who know what you know. (The @cite{Reference
18840 Manual} comes with the standard GNU Emacs distribution. Like this
18841 introduction, it comes as a Texinfo source file, so you can read it
18842 on-line and as a typeset, printed book.)
18843
18844 Go to the other on-line help that is part of GNU Emacs: the on-line
18845 documentation for all functions and variables, and @code{find-tag},
18846 the program that takes you to sources.
18847
18848 Here is an example of how I explore the sources. Because of its name,
18849 @file{simple.el} is the file I looked at first, a long time ago. As
18850 it happens some of the functions in @file{simple.el} are complicated,
18851 or at least look complicated at first sight. The @code{open-line}
18852 function, for example, looks complicated.
18853
18854 You may want to walk through this function slowly, as we did with the
18855 @code{forward-sentence} function. (@xref{forward-sentence, The
18856 @code{forward-sentence} function}.) Or you may want to skip that
18857 function and look at another, such as @code{split-line}. You don't
18858 need to read all the functions. According to
18859 @code{count-words-in-defun}, the @code{split-line} function contains
18860 102 words and symbols.
18861
18862 Even though it is short, @code{split-line} contains expressions
18863 we have not studied: @code{skip-chars-forward}, @code{indent-to},
18864 @code{current-column} and @code{insert-and-inherit}.
18865
18866 Consider the @code{skip-chars-forward} function. (It is part of the
18867 function definition for @code{back-to-indentation}, which is shown in
18868 @ref{Review, , Review}.)
18869
18870 In GNU Emacs, you can find out more about @code{skip-chars-forward} by
18871 typing @kbd{C-h f} (@code{describe-function}) and the name of the
18872 function. This gives you the function documentation.
18873
18874 You may be able to guess what is done by a well named function such as
18875 @code{indent-to}; or you can look it up, too. Incidentally, the
18876 @code{describe-function} function itself is in @file{help.el}; it is
18877 one of those long, but decipherable functions. You can look up
18878 @code{describe-function} using the @kbd{C-h f} command!
18879
18880 In this instance, since the code is Lisp, the @file{*Help*} buffer
18881 contains the name of the library containing the function's source.
18882 You can put point over the name of the library and press the RET key,
18883 which in this situation is bound to @code{help-follow}, and be taken
18884 directly to the source, in the same way as @kbd{M-.}
18885 (@code{find-tag}).
18886
18887 The definition for @code{describe-function} illustrates how to
18888 customize the @code{interactive} expression without using the standard
18889 character codes; and it shows how to create a temporary buffer.
18890
18891 (The @code{indent-to} function is written in C rather than Emacs Lisp;
18892 it is a `built-in' function. @code{help-follow} takes you to its
18893 source as does @code{find-tag}, when properly set up.)
18894
18895 You can look at a function's source using @code{find-tag}, which is
18896 bound to @kbd{M-.} Finally, you can find out what the Reference
18897 Manual has to say by visiting the manual in Info, and typing @kbd{i}
18898 (@code{Info-index}) and the name of the function, or by looking up the
18899 function in the index to a printed copy of the manual.
18900
18901 Similarly, you can find out what is meant by
18902 @code{insert-and-inherit}.
18903
18904 Other interesting source files include @file{paragraphs.el},
18905 @file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
18906 file includes short, easily understood functions as well as longer
18907 ones. The @file{loaddefs.el} file contains the many standard
18908 autoloads and many keymaps. I have never looked at it all; only at
18909 parts. @file{loadup.el} is the file that loads the standard parts of
18910 Emacs; it tells you a great deal about how Emacs is built.
18911 (@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
18912 Reference Manual}, for more about building.)
18913
18914 As I said, you have learned some nuts and bolts; however, and very
18915 importantly, we have hardly touched major aspects of programming; I
18916 have said nothing about how to sort information, except to use the
18917 predefined @code{sort} function; I have said nothing about how to store
18918 information, except to use variables and lists; I have said nothing
18919 about how to write programs that write programs. These are topics for
18920 another, and different kind of book, a different kind of learning.
18921
18922 What you have done is learn enough for much practical work with GNU
18923 Emacs. What you have done is get started. This is the end of a
18924 beginning.
18925
18926 @c ================ Appendix ================
18927
18928 @node the-the
18929 @appendix The @code{the-the} Function
18930 @findex the-the
18931 @cindex Duplicated words function
18932 @cindex Words, duplicated
18933
18934 Sometimes when you you write text, you duplicate words---as with ``you
18935 you'' near the beginning of this sentence. I find that most
18936 frequently, I duplicate ``the''; hence, I call the function for
18937 detecting duplicated words, @code{the-the}.
18938
18939 @need 1250
18940 As a first step, you could use the following regular expression to
18941 search for duplicates:
18942
18943 @smallexample
18944 \\(\\w+[ \t\n]+\\)\\1
18945 @end smallexample
18946
18947 @noindent
18948 This regexp matches one or more word-constituent characters followed
18949 by one or more spaces, tabs, or newlines. However, it does not detect
18950 duplicated words on different lines, since the ending of the first
18951 word, the end of the line, is different from the ending of the second
18952 word, a space. (For more information about regular expressions, see
18953 @ref{Regexp Search, , Regular Expression Searches}, as well as
18954 @ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
18955 Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
18956 The GNU Emacs Lisp Reference Manual}.)
18957
18958 You might try searching just for duplicated word-constituent
18959 characters but that does not work since the pattern detects doubles
18960 such as the two occurrences of `th' in `with the'.
18961
18962 Another possible regexp searches for word-constituent characters
18963 followed by non-word-constituent characters, reduplicated. Here,
18964 @w{@samp{\\w+}} matches one or more word-constituent characters and
18965 @w{@samp{\\W*}} matches zero or more non-word-constituent characters.
18966
18967 @smallexample
18968 \\(\\(\\w+\\)\\W*\\)\\1
18969 @end smallexample
18970
18971 @noindent
18972 Again, not useful.
18973
18974 Here is the pattern that I use. It is not perfect, but good enough.
18975 @w{@samp{\\b}} matches the empty string, provided it is at the beginning
18976 or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
18977 any characters that are @emph{not} an @@-sign, space, newline, or tab.
18978
18979 @smallexample
18980 \\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
18981 @end smallexample
18982
18983 One can write more complicated expressions, but I found that this
18984 expression is good enough, so I use it.
18985
18986 Here is the @code{the-the} function, as I include it in my
18987 @file{.emacs} file, along with a handy global key binding:
18988
18989 @smallexample
18990 @group
18991 (defun the-the ()
18992 "Search forward for for a duplicated word."
18993 (interactive)
18994 (message "Searching for for duplicated words ...")
18995 (push-mark)
18996 @end group
18997 @group
18998 ;; This regexp is not perfect
18999 ;; but is fairly good over all:
19000 (if (re-search-forward
19001 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
19002 (message "Found duplicated word.")
19003 (message "End of buffer")))
19004 @end group
19005
19006 @group
19007 ;; Bind `the-the' to C-c \
19008 (global-set-key "\C-c\\" 'the-the)
19009 @end group
19010 @end smallexample
19011
19012 @sp 1
19013 Here is test text:
19014
19015 @smallexample
19016 @group
19017 one two two three four five
19018 five six seven
19019 @end group
19020 @end smallexample
19021
19022 You can substitute the other regular expressions shown above in the
19023 function definition and try each of them on this list.
19024
19025 @node Kill Ring
19026 @appendix Handling the Kill Ring
19027 @cindex Kill ring handling
19028 @cindex Handling the kill ring
19029 @cindex Ring, making a list like a
19030
19031 The kill ring is a list that is transformed into a ring by the
19032 workings of the @code{current-kill} function. The @code{yank} and
19033 @code{yank-pop} commands use the @code{current-kill} function.
19034
19035 This appendix describes the @code{current-kill} function as well as
19036 both the @code{yank} and the @code{yank-pop} commands, but first,
19037 consider the workings of the kill ring.
19038
19039 @menu
19040 * What the Kill Ring Does::
19041 * current-kill::
19042 * yank:: Paste a copy of a clipped element.
19043 * yank-pop:: Insert element pointed to.
19044 * ring file::
19045 @end menu
19046
19047 @ifnottex
19048 @node What the Kill Ring Does
19049 @unnumberedsec What the Kill Ring Does
19050 @end ifnottex
19051
19052 @need 1250
19053 The kill ring has a default maximum length of sixty items; this number
19054 is too large for an explanation. Instead, set it to four. Please
19055 evaluate the following:
19056
19057 @smallexample
19058 @group
19059 (setq old-kill-ring-max kill-ring-max)
19060 (setq kill-ring-max 4)
19061 @end group
19062 @end smallexample
19063
19064 @noindent
19065 Then, please copy each line of the following indented example into the
19066 kill ring. You may kill each line with @kbd{C-k} or mark it and copy
19067 it with @kbd{M-w}.
19068
19069 @noindent
19070 (In a read-only buffer, such as the @file{*info*} buffer, the kill
19071 command, @kbd{C-k} (@code{kill-line}), will not remove the text,
19072 merely copy it to the kill ring. However, your machine may beep at
19073 you. Alternatively, for silence, you may copy the region of each line
19074 with the @kbd{M-w} (@code{kill-ring-save}) command. You must mark
19075 each line for this command to succeed, but it does not matter at which
19076 end you put point or mark.)
19077
19078 @need 1250
19079 @noindent
19080 Please invoke the calls in order, so that five elements attempt to
19081 fill the kill ring:
19082
19083 @smallexample
19084 @group
19085 first some text
19086 second piece of text
19087 third line
19088 fourth line of text
19089 fifth bit of text
19090 @end group
19091 @end smallexample
19092
19093 @need 1250
19094 @noindent
19095 Then find the value of @code{kill-ring} by evaluating
19096
19097 @smallexample
19098 kill-ring
19099 @end smallexample
19100
19101 @need 800
19102 @noindent
19103 It is:
19104
19105 @smallexample
19106 @group
19107 ("fifth bit of text" "fourth line of text"
19108 "third line" "second piece of text")
19109 @end group
19110 @end smallexample
19111
19112 @noindent
19113 The first element, @samp{first some text}, was dropped.
19114
19115 @need 1250
19116 To return to the old value for the length of the kill ring, evaluate:
19117
19118 @smallexample
19119 (setq kill-ring-max old-kill-ring-max)
19120 @end smallexample
19121
19122 @node current-kill
19123 @appendixsec The @code{current-kill} Function
19124 @findex current-kill
19125
19126 The @code{current-kill} function changes the element in the kill ring
19127 to which @code{kill-ring-yank-pointer} points. (Also, the
19128 @code{kill-new} function sets @code{kill-ring-yank-pointer} to point
19129 to the latest element of the kill ring. The @code{kill-new}
19130 function is used directly or indirectly by @code{kill-append},
19131 @code{copy-region-as-kill}, @code{kill-ring-save}, @code{kill-line},
19132 and @code{kill-region}.)
19133
19134 @menu
19135 * Code for current-kill::
19136 * Understanding current-kill::
19137 @end menu
19138
19139 @ifnottex
19140 @node Code for current-kill
19141 @unnumberedsubsec The code for @code{current-kill}
19142 @end ifnottex
19143
19144
19145 @need 1500
19146 The @code{current-kill} function is used by @code{yank} and by
19147 @code{yank-pop}. Here is the code for @code{current-kill}:
19148
19149 @smallexample
19150 @group
19151 (defun current-kill (n &optional do-not-move)
19152 "Rotate the yanking point by N places, and then return that kill.
19153 If N is zero, `interprogram-paste-function' is set, and calling it
19154 returns a string, then that string is added to the front of the
19155 kill ring and returned as the latest kill.
19156 @end group
19157 @group
19158 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
19159 yanking point; just return the Nth kill forward."
19160 (let ((interprogram-paste (and (= n 0)
19161 interprogram-paste-function
19162 (funcall interprogram-paste-function))))
19163 @end group
19164 @group
19165 (if interprogram-paste
19166 (progn
19167 ;; Disable the interprogram cut function when we add the new
19168 ;; text to the kill ring, so Emacs doesn't try to own the
19169 ;; selection, with identical text.
19170 (let ((interprogram-cut-function nil))
19171 (kill-new interprogram-paste))
19172 interprogram-paste)
19173 @end group
19174 @group
19175 (or kill-ring (error "Kill ring is empty"))
19176 (let ((ARGth-kill-element
19177 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19178 (length kill-ring))
19179 kill-ring)))
19180 (or do-not-move
19181 (setq kill-ring-yank-pointer ARGth-kill-element))
19182 (car ARGth-kill-element)))))
19183 @end group
19184 @end smallexample
19185
19186 Remember also that the @code{kill-new} function sets
19187 @code{kill-ring-yank-pointer} to the latest element of the kill
19188 ring, which means that all the functions that call it set the value
19189 indirectly: @code{kill-append}, @code{copy-region-as-kill},
19190 @code{kill-ring-save}, @code{kill-line}, and @code{kill-region}.
19191
19192 @need 1500
19193 Here is the line in @code{kill-new}, which is explained in
19194 @ref{kill-new function, , The @code{kill-new} function}.
19195
19196 @smallexample
19197 (setq kill-ring-yank-pointer kill-ring)
19198 @end smallexample
19199
19200 @ifnottex
19201 @node Understanding current-kill
19202 @unnumberedsubsec @code{current-kill} in Outline
19203 @end ifnottex
19204
19205 The @code{current-kill} function looks complex, but as usual, it can
19206 be understood by taking it apart piece by piece. First look at it in
19207 skeletal form:
19208
19209 @smallexample
19210 @group
19211 (defun current-kill (n &optional do-not-move)
19212 "Rotate the yanking point by N places, and then return that kill."
19213 (let @var{varlist}
19214 @var{body}@dots{})
19215 @end group
19216 @end smallexample
19217
19218 This function takes two arguments, one of which is optional. It has a
19219 documentation string. It is @emph{not} interactive.
19220
19221 @menu
19222 * Body of current-kill::
19223 * Digression concerning error:: How to mislead humans, but not computers.
19224 * Determining the Element::
19225 @end menu
19226
19227 @ifnottex
19228 @node Body of current-kill
19229 @unnumberedsubsubsec The Body of @code{current-kill}
19230 @end ifnottex
19231
19232 The body of the function definition is a @code{let} expression, which
19233 itself has a body as well as a @var{varlist}.
19234
19235 The @code{let} expression declares a variable that will be only usable
19236 within the bounds of this function. This variable is called
19237 @code{interprogram-paste} and is for copying to another program. It
19238 is not for copying within this instance of GNU Emacs. Most window
19239 systems provide a facility for interprogram pasting. Sadly, that
19240 facility usually provides only for the last element. Most windowing
19241 systems have not adopted a ring of many possibilities, even though
19242 Emacs has provided it for decades.
19243
19244 The @code{if} expression has two parts, one if there exists
19245 @code{interprogram-paste} and one if not.
19246
19247 @need 2000
19248 Let us consider the `if not' or else-part of the @code{current-kill}
19249 function. (The then-part uses the @code{kill-new} function, which
19250 we have already described. @xref{kill-new function, , The
19251 @code{kill-new} function}.)
19252
19253 @smallexample
19254 @group
19255 (or kill-ring (error "Kill ring is empty"))
19256 (let ((ARGth-kill-element
19257 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19258 (length kill-ring))
19259 kill-ring)))
19260 (or do-not-move
19261 (setq kill-ring-yank-pointer ARGth-kill-element))
19262 (car ARGth-kill-element))
19263 @end group
19264 @end smallexample
19265
19266 @noindent
19267 The code first checks whether the kill ring has content; otherwise it
19268 signals an error.
19269
19270 @need 1000
19271 Note that the @code{or} expression is very similar to testing length
19272 with an @code{if}:
19273
19274 @findex zerop
19275 @findex error
19276 @smallexample
19277 @group
19278 (if (zerop (length kill-ring)) ; @r{if-part}
19279 (error "Kill ring is empty")) ; @r{then-part}
19280 ;; No else-part
19281 @end group
19282 @end smallexample
19283
19284 @noindent
19285 If there is not anything in the kill ring, its length must be zero and
19286 an error message sent to the user: @samp{Kill ring is empty}. The
19287 @code{current-kill} function uses an @code{or} expression which is
19288 simpler. But an @code{if} expression reminds us what goes on.
19289
19290 This @code{if} expression uses the function @code{zerop} which returns
19291 true if the value it is testing is zero. When @code{zerop} tests
19292 true, the then-part of the @code{if} is evaluated. The then-part is a
19293 list starting with the function @code{error}, which is a function that
19294 is similar to the @code{message} function
19295 (@pxref{message, , The @code{message} Function}) in that
19296 it prints a one-line message in the echo area. However, in addition
19297 to printing a message, @code{error} also stops evaluation of the
19298 function within which it is embedded. This means that the rest of the
19299 function will not be evaluated if the length of the kill ring is zero.
19300
19301 Then the @code{current-kill} function selects the element to return.
19302 The selection depends on the number of places that @code{current-kill}
19303 rotates and on where @code{kill-ring-yank-pointer} points.
19304
19305 Next, either the optional @code{do-not-move} argument is true or the
19306 current value of @code{kill-ring-yank-pointer} is set to point to the
19307 list. Finally, another expression returns the first element of the
19308 list even if the @code{do-not-move} argument is true.
19309
19310 @ifnottex
19311 @node Digression concerning error
19312 @unnumberedsubsubsec Digression about the word `error'
19313 @end ifnottex
19314
19315 In my opinion, it is slightly misleading, at least to humans, to use
19316 the term `error' as the name of the @code{error} function. A better
19317 term would be `cancel'. Strictly speaking, of course, you cannot
19318 point to, much less rotate a pointer to a list that has no length, so
19319 from the point of view of the computer, the word `error' is correct.
19320 But a human expects to attempt this sort of thing, if only to find out
19321 whether the kill ring is full or empty. This is an act of
19322 exploration.
19323
19324 From the human point of view, the act of exploration and discovery is
19325 not necessarily an error, and therefore should not be labeled as one,
19326 even in the bowels of a computer. As it is, the code in Emacs implies
19327 that a human who is acting virtuously, by exploring his or her
19328 environment, is making an error. This is bad. Even though the computer
19329 takes the same steps as it does when there is an `error', a term such as
19330 `cancel' would have a clearer connotation.
19331
19332 @ifnottex
19333 @node Determining the Element
19334 @unnumberedsubsubsec Determining the Element
19335 @end ifnottex
19336
19337 Among other actions, the else-part of the @code{if} expression sets
19338 the value of @code{kill-ring-yank-pointer} to
19339 @code{ARGth-kill-element} when the kill ring has something in it and
19340 the value of @code{do-not-move} is @code{nil}.
19341
19342 @need 800
19343 The code looks like this:
19344
19345 @smallexample
19346 @group
19347 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19348 (length kill-ring))
19349 kill-ring)))
19350 @end group
19351 @end smallexample
19352
19353 This needs some examination. Unless it is not supposed to move the
19354 pointer, the @code{current-kill} function changes where
19355 @code{kill-ring-yank-pointer} points.
19356 That is what the
19357 @w{@code{(setq kill-ring-yank-pointer ARGth-kill-element))}}
19358 expression does. Also, clearly, @code{ARGth-kill-element} is being
19359 set to be equal to some @sc{cdr} of the kill ring, using the
19360 @code{nthcdr} function that is described in an earlier section.
19361 (@xref{copy-region-as-kill}.) How does it do this?
19362
19363 As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
19364 works by repeatedly taking the @sc{cdr} of a list---it takes the
19365 @sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
19366
19367 @need 800
19368 The two following expressions produce the same result:
19369
19370 @smallexample
19371 @group
19372 (setq kill-ring-yank-pointer (cdr kill-ring))
19373
19374 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
19375 @end group
19376 @end smallexample
19377
19378 However, the @code{nthcdr} expression is more complicated. It uses
19379 the @code{mod} function to determine which @sc{cdr} to select.
19380
19381 (You will remember to look at inner functions first; indeed, we will
19382 have to go inside the @code{mod}.)
19383
19384 The @code{mod} function returns the value of its first argument modulo
19385 the second; that is to say, it returns the remainder after dividing
19386 the first argument by the second. The value returned has the same
19387 sign as the second argument.
19388
19389 @need 800
19390 Thus,
19391
19392 @smallexample
19393 @group
19394 (mod 12 4)
19395 @result{} 0 ;; @r{because there is no remainder}
19396 (mod 13 4)
19397 @result{} 1
19398 @end group
19399 @end smallexample
19400
19401 @need 1250
19402 In this case, the first argument is often smaller than the second.
19403 That is fine.
19404
19405 @smallexample
19406 @group
19407 (mod 0 4)
19408 @result{} 0
19409 (mod 1 4)
19410 @result{} 1
19411 @end group
19412 @end smallexample
19413
19414 We can guess what the @code{-} function does. It is like @code{+} but
19415 subtracts instead of adds; the @code{-} function subtracts its second
19416 argument from its first. Also, we already know what the @code{length}
19417 function does (@pxref{length}). It returns the length of a list.
19418
19419 And @code{n} is the name of the required argument to the
19420 @code{current-kill} function.
19421
19422 @need 1250
19423 So when the first argument to @code{nthcdr} is zero, the @code{nthcdr}
19424 expression returns the whole list, as you can see by evaluating the
19425 following:
19426
19427 @smallexample
19428 @group
19429 ;; kill-ring-yank-pointer @r{and} kill-ring @r{have a length of four}
19430 ;; @r{and} (mod (- 0 4) 4) @result{} 0
19431 (nthcdr (mod (- 0 4) 4)
19432 '("fourth line of text"
19433 "third line"
19434 "second piece of text"
19435 "first some text"))
19436 @end group
19437 @end smallexample
19438
19439 @need 1250
19440 When the first argument to the @code{current-kill} function is one,
19441 the @code{nthcdr} expression returns the list without its first
19442 element.
19443
19444 @smallexample
19445 @group
19446 (nthcdr (mod (- 1 4) 4)
19447 '("fourth line of text"
19448 "third line"
19449 "second piece of text"
19450 "first some text"))
19451 @end group
19452 @end smallexample
19453
19454 @cindex @samp{global variable} defined
19455 @cindex @samp{variable, global}, defined
19456 Incidentally, both @code{kill-ring} and @code{kill-ring-yank-pointer}
19457 are @dfn{global variables}. That means that any expression in Emacs
19458 Lisp can access them. They are not like the local variables set by
19459 @code{let} or like the symbols in an argument list.
19460 Local variables can only be accessed
19461 within the @code{let} that defines them or the function that specifies
19462 them in an argument list (and within expressions called by them).
19463
19464 @ignore
19465 @c texi2dvi fails when the name of the section is within ifnottex ...
19466 (@xref{Prevent confusion, , @code{let} Prevents Confusion}, and
19467 @ref{defun, , The @code{defun} Special Form}.)
19468 @end ignore
19469
19470 @node yank
19471 @appendixsec @code{yank}
19472 @findex yank
19473
19474 After learning about @code{current-kill}, the code for the
19475 @code{yank} function is almost easy.
19476
19477 The @code{yank} function does not use the
19478 @code{kill-ring-yank-pointer} variable directly. It calls
19479 @code{insert-for-yank} which calls @code{current-kill} which sets the
19480 @code{kill-ring-yank-pointer} variable.
19481
19482 @need 1250
19483 The code looks like this:
19484
19485 @c in GNU Emacs 22
19486 @smallexample
19487 @group
19488 (defun yank (&optional arg)
19489 "Reinsert (\"paste\") the last stretch of killed text.
19490 More precisely, reinsert the stretch of killed text most recently
19491 killed OR yanked. Put point at end, and set mark at beginning.
19492 With just \\[universal-argument] as argument, same but put point at
19493 beginning (and mark at end). With argument N, reinsert the Nth most
19494 recently killed stretch of killed text.
19495
19496 When this command inserts killed text into the buffer, it honors
19497 `yank-excluded-properties' and `yank-handler' as described in the
19498 doc string for `insert-for-yank-1', which see.
19499
19500 See also the command \\[yank-pop]."
19501 @end group
19502 @group
19503 (interactive "*P")
19504 (setq yank-window-start (window-start))
19505 ;; If we don't get all the way thru, make last-command indicate that
19506 ;; for the following command.
19507 (setq this-command t)
19508 (push-mark (point))
19509 @end group
19510 @group
19511 (insert-for-yank (current-kill (cond
19512 ((listp arg) 0)
19513 ((eq arg '-) -2)
19514 (t (1- arg)))))
19515 (if (consp arg)
19516 ;; This is like exchange-point-and-mark,
19517 ;; but doesn't activate the mark.
19518 ;; It is cleaner to avoid activation, even though the command
19519 ;; loop would deactivate the mark because we inserted text.
19520 (goto-char (prog1 (mark t)
19521 (set-marker (mark-marker) (point) (current-buffer)))))
19522 @end group
19523 @group
19524 ;; If we do get all the way thru, make this-command indicate that.
19525 (if (eq this-command t)
19526 (setq this-command 'yank))
19527 nil)
19528 @end group
19529 @end smallexample
19530
19531 The key expression is @code{insert-for-yank}, which inserts the string
19532 returned by @code{current-kill}, but removes some text properties from
19533 it.
19534
19535 However, before getting to that expression, the function sets the value
19536 of @code{yank-window-start} to the position returned by the
19537 @code{(window-start)} expression, the position at which the display
19538 currently starts. The @code{yank} function also sets
19539 @code{this-command} and pushes the mark.
19540
19541 After it yanks the appropriate element, if the optional argument is a
19542 @sc{cons} rather than a number or nothing, it puts point at beginning
19543 of the yanked text and mark at its end.
19544
19545 (The @code{prog1} function is like @code{progn} but returns the value
19546 of its first argument rather than the value of its last argument. Its
19547 first argument is forced to return the buffer's mark as an integer.
19548 You can see the documentation for these functions by placing point
19549 over them in this buffer and then typing @kbd{C-h f}
19550 (@code{describe-function}) followed by a @kbd{RET}; the default is the
19551 function.)
19552
19553 The last part of the function tells what to do when it succeeds.
19554
19555 @node yank-pop
19556 @appendixsec @code{yank-pop}
19557 @findex yank-pop
19558
19559 After understanding @code{yank} and @code{current-kill}, you know how
19560 to approach the @code{yank-pop} function. Leaving out the
19561 documentation to save space, it looks like this:
19562
19563 @c GNU Emacs 22
19564 @smallexample
19565 @group
19566 (defun yank-pop (&optional arg)
19567 "@dots{}"
19568 (interactive "*p")
19569 (if (not (eq last-command 'yank))
19570 (error "Previous command was not a yank"))
19571 @end group
19572 @group
19573 (setq this-command 'yank)
19574 (unless arg (setq arg 1))
19575 (let ((inhibit-read-only t)
19576 (before (< (point) (mark t))))
19577 @end group
19578 @group
19579 (if before
19580 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
19581 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
19582 (setq yank-undo-function nil)
19583 @end group
19584 @group
19585 (set-marker (mark-marker) (point) (current-buffer))
19586 (insert-for-yank (current-kill arg))
19587 ;; Set the window start back where it was in the yank command,
19588 ;; if possible.
19589 (set-window-start (selected-window) yank-window-start t)
19590 @end group
19591 @group
19592 (if before
19593 ;; This is like exchange-point-and-mark,
19594 ;; but doesn't activate the mark.
19595 ;; It is cleaner to avoid activation, even though the command
19596 ;; loop would deactivate the mark because we inserted text.
19597 (goto-char (prog1 (mark t)
19598 (set-marker (mark-marker)
19599 (point)
19600 (current-buffer))))))
19601 nil)
19602 @end group
19603 @end smallexample
19604
19605 The function is interactive with a small @samp{p} so the prefix
19606 argument is processed and passed to the function. The command can
19607 only be used after a previous yank; otherwise an error message is
19608 sent. This check uses the variable @code{last-command} which is set
19609 by @code{yank} and is discussed elsewhere.
19610 (@xref{copy-region-as-kill}.)
19611
19612 The @code{let} clause sets the variable @code{before} to true or false
19613 depending whether point is before or after mark and then the region
19614 between point and mark is deleted. This is the region that was just
19615 inserted by the previous yank and it is this text that will be
19616 replaced.
19617
19618 @code{funcall} calls its first argument as a function, passing
19619 remaining arguments to it. The first argument is whatever the
19620 @code{or} expression returns. The two remaining arguments are the
19621 positions of point and mark set by the preceding @code{yank} command.
19622
19623 There is more, but that is the hardest part.
19624
19625 @node ring file
19626 @appendixsec The @file{ring.el} File
19627 @cindex @file{ring.el} file
19628
19629 Interestingly, GNU Emacs posses a file called @file{ring.el} that
19630 provides many of the features we just discussed. But functions such
19631 as @code{kill-ring-yank-pointer} do not use this library, possibly
19632 because they were written earlier.
19633
19634 @node Full Graph
19635 @appendix A Graph with Labeled Axes
19636
19637 Printed axes help you understand a graph. They convey scale. In an
19638 earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
19639 wrote the code to print the body of a graph. Here we write the code
19640 for printing and labeling vertical and horizontal axes, along with the
19641 body itself.
19642
19643 @menu
19644 * Labeled Example::
19645 * print-graph Varlist:: @code{let} expression in @code{print-graph}.
19646 * print-Y-axis:: Print a label for the vertical axis.
19647 * print-X-axis:: Print a horizontal label.
19648 * Print Whole Graph:: The function to print a complete graph.
19649 @end menu
19650
19651 @ifnottex
19652 @node Labeled Example
19653 @unnumberedsec Labeled Example Graph
19654 @end ifnottex
19655
19656 Since insertions fill a buffer to the right and below point, the new
19657 graph printing function should first print the Y or vertical axis,
19658 then the body of the graph, and finally the X or horizontal axis.
19659 This sequence lays out for us the contents of the function:
19660
19661 @enumerate
19662 @item
19663 Set up code.
19664
19665 @item
19666 Print Y axis.
19667
19668 @item
19669 Print body of graph.
19670
19671 @item
19672 Print X axis.
19673 @end enumerate
19674
19675 @need 800
19676 Here is an example of how a finished graph should look:
19677
19678 @smallexample
19679 @group
19680 10 -
19681 *
19682 * *
19683 * **
19684 * ***
19685 5 - * *******
19686 * *** *******
19687 *************
19688 ***************
19689 1 - ****************
19690 | | | |
19691 1 5 10 15
19692 @end group
19693 @end smallexample
19694
19695 @noindent
19696 In this graph, both the vertical and the horizontal axes are labeled
19697 with numbers. However, in some graphs, the horizontal axis is time
19698 and would be better labeled with months, like this:
19699
19700 @smallexample
19701 @group
19702 5 - *
19703 * ** *
19704 *******
19705 ********** **
19706 1 - **************
19707 | ^ |
19708 Jan June Jan
19709 @end group
19710 @end smallexample
19711
19712 Indeed, with a little thought, we can easily come up with a variety of
19713 vertical and horizontal labeling schemes. Our task could become
19714 complicated. But complications breed confusion. Rather than permit
19715 this, it is better choose a simple labeling scheme for our first
19716 effort, and to modify or replace it later.
19717
19718 @need 1200
19719 These considerations suggest the following outline for the
19720 @code{print-graph} function:
19721
19722 @smallexample
19723 @group
19724 (defun print-graph (numbers-list)
19725 "@var{documentation}@dots{}"
19726 (let ((height @dots{}
19727 @dots{}))
19728 @end group
19729 @group
19730 (print-Y-axis height @dots{} )
19731 (graph-body-print numbers-list)
19732 (print-X-axis @dots{} )))
19733 @end group
19734 @end smallexample
19735
19736 We can work on each part of the @code{print-graph} function definition
19737 in turn.
19738
19739 @node print-graph Varlist
19740 @appendixsec The @code{print-graph} Varlist
19741 @cindex @code{print-graph} varlist
19742
19743 In writing the @code{print-graph} function, the first task is to write
19744 the varlist in the @code{let} expression. (We will leave aside for the
19745 moment any thoughts about making the function interactive or about the
19746 contents of its documentation string.)
19747
19748 The varlist should set several values. Clearly, the top of the label
19749 for the vertical axis must be at least the height of the graph, which
19750 means that we must obtain this information here. Note that the
19751 @code{print-graph-body} function also requires this information. There
19752 is no reason to calculate the height of the graph in two different
19753 places, so we should change @code{print-graph-body} from the way we
19754 defined it earlier to take advantage of the calculation.
19755
19756 Similarly, both the function for printing the X axis labels and the
19757 @code{print-graph-body} function need to learn the value of the width of
19758 each symbol. We can perform the calculation here and change the
19759 definition for @code{print-graph-body} from the way we defined it in the
19760 previous chapter.
19761
19762 The length of the label for the horizontal axis must be at least as long
19763 as the graph. However, this information is used only in the function
19764 that prints the horizontal axis, so it does not need to be calculated here.
19765
19766 These thoughts lead us directly to the following form for the varlist
19767 in the @code{let} for @code{print-graph}:
19768
19769 @smallexample
19770 @group
19771 (let ((height (apply 'max numbers-list)) ; @r{First version.}
19772 (symbol-width (length graph-blank)))
19773 @end group
19774 @end smallexample
19775
19776 @noindent
19777 As we shall see, this expression is not quite right.
19778
19779 @need 2000
19780 @node print-Y-axis
19781 @appendixsec The @code{print-Y-axis} Function
19782 @cindex Axis, print vertical
19783 @cindex Y axis printing
19784 @cindex Vertical axis printing
19785 @cindex Print vertical axis
19786
19787 The job of the @code{print-Y-axis} function is to print a label for
19788 the vertical axis that looks like this:
19789
19790 @smallexample
19791 @group
19792 10 -
19793
19794
19795
19796
19797 5 -
19798
19799
19800
19801 1 -
19802 @end group
19803 @end smallexample
19804
19805 @noindent
19806 The function should be passed the height of the graph, and then should
19807 construct and insert the appropriate numbers and marks.
19808
19809 @menu
19810 * print-Y-axis in Detail::
19811 * Height of label:: What height for the Y axis?
19812 * Compute a Remainder:: How to compute the remainder of a division.
19813 * Y Axis Element:: Construct a line for the Y axis.
19814 * Y-axis-column:: Generate a list of Y axis labels.
19815 * print-Y-axis Penultimate:: A not quite final version.
19816 @end menu
19817
19818 @ifnottex
19819 @node print-Y-axis in Detail
19820 @unnumberedsubsec The @code{print-Y-axis} Function in Detail
19821 @end ifnottex
19822
19823 It is easy enough to see in the figure what the Y axis label should
19824 look like; but to say in words, and then to write a function
19825 definition to do the job is another matter. It is not quite true to
19826 say that we want a number and a tic every five lines: there are only
19827 three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
19828 but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
19829 and 9). It is better to say that we want a number and a tic mark on
19830 the base line (number 1) and then that we want a number and a tic on
19831 the fifth line from the bottom and on every line that is a multiple of
19832 five.
19833
19834 @ifnottex
19835 @node Height of label
19836 @unnumberedsubsec What height should the label be?
19837 @end ifnottex
19838
19839 The next issue is what height the label should be? Suppose the maximum
19840 height of tallest column of the graph is seven. Should the highest
19841 label on the Y axis be @samp{5 -}, and should the graph stick up above
19842 the label? Or should the highest label be @samp{7 -}, and mark the peak
19843 of the graph? Or should the highest label be @code{10 -}, which is a
19844 multiple of five, and be higher than the topmost value of the graph?
19845
19846 The latter form is preferred. Most graphs are drawn within rectangles
19847 whose sides are an integral number of steps long---5, 10, 15, and so
19848 on for a step distance of five. But as soon as we decide to use a
19849 step height for the vertical axis, we discover that the simple
19850 expression in the varlist for computing the height is wrong. The
19851 expression is @code{(apply 'max numbers-list)}. This returns the
19852 precise height, not the maximum height plus whatever is necessary to
19853 round up to the nearest multiple of five. A more complex expression
19854 is required.
19855
19856 As usual in cases like this, a complex problem becomes simpler if it is
19857 divided into several smaller problems.
19858
19859 First, consider the case when the highest value of the graph is an
19860 integral multiple of five---when it is 5, 10, 15, or some higher
19861 multiple of five. We can use this value as the Y axis height.
19862
19863 A fairly simply way to determine whether a number is a multiple of
19864 five is to divide it by five and see if the division results in a
19865 remainder. If there is no remainder, the number is a multiple of
19866 five. Thus, seven divided by five has a remainder of two, and seven
19867 is not an integral multiple of five. Put in slightly different
19868 language, more reminiscent of the classroom, five goes into seven
19869 once, with a remainder of two. However, five goes into ten twice,
19870 with no remainder: ten is an integral multiple of five.
19871
19872 @node Compute a Remainder
19873 @appendixsubsec Side Trip: Compute a Remainder
19874
19875 @findex % @r{(remainder function)}
19876 @cindex Remainder function, @code{%}
19877 In Lisp, the function for computing a remainder is @code{%}. The
19878 function returns the remainder of its first argument divided by its
19879 second argument. As it happens, @code{%} is a function in Emacs Lisp
19880 that you cannot discover using @code{apropos}: you find nothing if you
19881 type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
19882 learn of the existence of @code{%} is to read about it in a book such
19883 as this or in the Emacs Lisp sources.
19884
19885 You can try the @code{%} function by evaluating the following two
19886 expressions:
19887
19888 @smallexample
19889 @group
19890 (% 7 5)
19891
19892 (% 10 5)
19893 @end group
19894 @end smallexample
19895
19896 @noindent
19897 The first expression returns 2 and the second expression returns 0.
19898
19899 To test whether the returned value is zero or some other number, we
19900 can use the @code{zerop} function. This function returns @code{t} if
19901 its argument, which must be a number, is zero.
19902
19903 @smallexample
19904 @group
19905 (zerop (% 7 5))
19906 @result{} nil
19907
19908 (zerop (% 10 5))
19909 @result{} t
19910 @end group
19911 @end smallexample
19912
19913 Thus, the following expression will return @code{t} if the height
19914 of the graph is evenly divisible by five:
19915
19916 @smallexample
19917 (zerop (% height 5))
19918 @end smallexample
19919
19920 @noindent
19921 (The value of @code{height}, of course, can be found from @code{(apply
19922 'max numbers-list)}.)
19923
19924 On the other hand, if the value of @code{height} is not a multiple of
19925 five, we want to reset the value to the next higher multiple of five.
19926 This is straightforward arithmetic using functions with which we are
19927 already familiar. First, we divide the value of @code{height} by five
19928 to determine how many times five goes into the number. Thus, five
19929 goes into twelve twice. If we add one to this quotient and multiply by
19930 five, we will obtain the value of the next multiple of five that is
19931 larger than the height. Five goes into twelve twice. Add one to two,
19932 and multiply by five; the result is fifteen, which is the next multiple
19933 of five that is higher than twelve. The Lisp expression for this is:
19934
19935 @smallexample
19936 (* (1+ (/ height 5)) 5)
19937 @end smallexample
19938
19939 @noindent
19940 For example, if you evaluate the following, the result is 15:
19941
19942 @smallexample
19943 (* (1+ (/ 12 5)) 5)
19944 @end smallexample
19945
19946 All through this discussion, we have been using `five' as the value
19947 for spacing labels on the Y axis; but we may want to use some other
19948 value. For generality, we should replace `five' with a variable to
19949 which we can assign a value. The best name I can think of for this
19950 variable is @code{Y-axis-label-spacing}.
19951
19952 @need 1250
19953 Using this term, and an @code{if} expression, we produce the
19954 following:
19955
19956 @smallexample
19957 @group
19958 (if (zerop (% height Y-axis-label-spacing))
19959 height
19960 ;; @r{else}
19961 (* (1+ (/ height Y-axis-label-spacing))
19962 Y-axis-label-spacing))
19963 @end group
19964 @end smallexample
19965
19966 @noindent
19967 This expression returns the value of @code{height} itself if the height
19968 is an even multiple of the value of the @code{Y-axis-label-spacing} or
19969 else it computes and returns a value of @code{height} that is equal to
19970 the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19971
19972 We can now include this expression in the @code{let} expression of the
19973 @code{print-graph} function (after first setting the value of
19974 @code{Y-axis-label-spacing}):
19975 @vindex Y-axis-label-spacing
19976
19977 @smallexample
19978 @group
19979 (defvar Y-axis-label-spacing 5
19980 "Number of lines from one Y axis label to next.")
19981 @end group
19982
19983 @group
19984 @dots{}
19985 (let* ((height (apply 'max numbers-list))
19986 (height-of-top-line
19987 (if (zerop (% height Y-axis-label-spacing))
19988 height
19989 @end group
19990 @group
19991 ;; @r{else}
19992 (* (1+ (/ height Y-axis-label-spacing))
19993 Y-axis-label-spacing)))
19994 (symbol-width (length graph-blank))))
19995 @dots{}
19996 @end group
19997 @end smallexample
19998
19999 @noindent
20000 (Note use of the @code{let*} function: the initial value of height is
20001 computed once by the @code{(apply 'max numbers-list)} expression and
20002 then the resulting value of @code{height} is used to compute its
20003 final value. @xref{fwd-para let, , The @code{let*} expression}, for
20004 more about @code{let*}.)
20005
20006 @node Y Axis Element
20007 @appendixsubsec Construct a Y Axis Element
20008
20009 When we print the vertical axis, we want to insert strings such as
20010 @w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
20011 Moreover, we want the numbers and dashes to line up, so shorter
20012 numbers must be padded with leading spaces. If some of the strings
20013 use two digit numbers, the strings with single digit numbers must
20014 include a leading blank space before the number.
20015
20016 @findex number-to-string
20017 To figure out the length of the number, the @code{length} function is
20018 used. But the @code{length} function works only with a string, not with
20019 a number. So the number has to be converted from being a number to
20020 being a string. This is done with the @code{number-to-string} function.
20021 For example,
20022
20023 @smallexample
20024 @group
20025 (length (number-to-string 35))
20026 @result{} 2
20027
20028 (length (number-to-string 100))
20029 @result{} 3
20030 @end group
20031 @end smallexample
20032
20033 @noindent
20034 (@code{number-to-string} is also called @code{int-to-string}; you will
20035 see this alternative name in various sources.)
20036
20037 In addition, in each label, each number is followed by a string such
20038 as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
20039 This variable is defined with @code{defvar}:
20040
20041 @vindex Y-axis-tic
20042 @smallexample
20043 @group
20044 (defvar Y-axis-tic " - "
20045 "String that follows number in a Y axis label.")
20046 @end group
20047 @end smallexample
20048
20049 The length of the Y label is the sum of the length of the Y axis tic
20050 mark and the length of the number of the top of the graph.
20051
20052 @smallexample
20053 (length (concat (number-to-string height) Y-axis-tic)))
20054 @end smallexample
20055
20056 This value will be calculated by the @code{print-graph} function in
20057 its varlist as @code{full-Y-label-width} and passed on. (Note that we
20058 did not think to include this in the varlist when we first proposed it.)
20059
20060 To make a complete vertical axis label, a tic mark is concatenated
20061 with a number; and the two together may be preceded by one or more
20062 spaces depending on how long the number is. The label consists of
20063 three parts: the (optional) leading spaces, the number, and the tic
20064 mark. The function is passed the value of the number for the specific
20065 row, and the value of the width of the top line, which is calculated
20066 (just once) by @code{print-graph}.
20067
20068 @smallexample
20069 @group
20070 (defun Y-axis-element (number full-Y-label-width)
20071 "Construct a NUMBERed label element.
20072 A numbered element looks like this ` 5 - ',
20073 and is padded as needed so all line up with
20074 the element for the largest number."
20075 @end group
20076 @group
20077 (let* ((leading-spaces
20078 (- full-Y-label-width
20079 (length
20080 (concat (number-to-string number)
20081 Y-axis-tic)))))
20082 @end group
20083 @group
20084 (concat
20085 (make-string leading-spaces ? )
20086 (number-to-string number)
20087 Y-axis-tic)))
20088 @end group
20089 @end smallexample
20090
20091 The @code{Y-axis-element} function concatenates together the leading
20092 spaces, if any; the number, as a string; and the tic mark.
20093
20094 To figure out how many leading spaces the label will need, the
20095 function subtracts the actual length of the label---the length of the
20096 number plus the length of the tic mark---from the desired label width.
20097
20098 @findex make-string
20099 Blank spaces are inserted using the @code{make-string} function. This
20100 function takes two arguments: the first tells it how long the string
20101 will be and the second is a symbol for the character to insert, in a
20102 special format. The format is a question mark followed by a blank
20103 space, like this, @samp{? }. @xref{Character Type, , Character Type,
20104 elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
20105 syntax for characters. (Of course, you might want to replace the
20106 blank space by some other character @dots{} You know what to do.)
20107
20108 The @code{number-to-string} function is used in the concatenation
20109 expression, to convert the number to a string that is concatenated
20110 with the leading spaces and the tic mark.
20111
20112 @node Y-axis-column
20113 @appendixsubsec Create a Y Axis Column
20114
20115 The preceding functions provide all the tools needed to construct a
20116 function that generates a list of numbered and blank strings to insert
20117 as the label for the vertical axis:
20118
20119 @findex Y-axis-column
20120 @smallexample
20121 @group
20122 (defun Y-axis-column (height width-of-label)
20123 "Construct list of Y axis labels and blank strings.
20124 For HEIGHT of line above base and WIDTH-OF-LABEL."
20125 (let (Y-axis)
20126 @group
20127 @end group
20128 (while (> height 1)
20129 (if (zerop (% height Y-axis-label-spacing))
20130 ;; @r{Insert label.}
20131 (setq Y-axis
20132 (cons
20133 (Y-axis-element height width-of-label)
20134 Y-axis))
20135 @group
20136 @end group
20137 ;; @r{Else, insert blanks.}
20138 (setq Y-axis
20139 (cons
20140 (make-string width-of-label ? )
20141 Y-axis)))
20142 (setq height (1- height)))
20143 ;; @r{Insert base line.}
20144 (setq Y-axis
20145 (cons (Y-axis-element 1 width-of-label) Y-axis))
20146 (nreverse Y-axis)))
20147 @end group
20148 @end smallexample
20149
20150 In this function, we start with the value of @code{height} and
20151 repetitively subtract one from its value. After each subtraction, we
20152 test to see whether the value is an integral multiple of the
20153 @code{Y-axis-label-spacing}. If it is, we construct a numbered label
20154 using the @code{Y-axis-element} function; if not, we construct a
20155 blank label using the @code{make-string} function. The base line
20156 consists of the number one followed by a tic mark.
20157
20158 @need 2000
20159 @node print-Y-axis Penultimate
20160 @appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
20161
20162 The list constructed by the @code{Y-axis-column} function is passed to
20163 the @code{print-Y-axis} function, which inserts the list as a column.
20164
20165 @findex print-Y-axis
20166 @smallexample
20167 @group
20168 (defun print-Y-axis (height full-Y-label-width)
20169 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
20170 Height must be the maximum height of the graph.
20171 Full width is the width of the highest label element."
20172 ;; Value of height and full-Y-label-width
20173 ;; are passed by `print-graph'.
20174 @end group
20175 @group
20176 (let ((start (point)))
20177 (insert-rectangle
20178 (Y-axis-column height full-Y-label-width))
20179 ;; @r{Place point ready for inserting graph.}
20180 (goto-char start)
20181 ;; @r{Move point forward by value of} full-Y-label-width
20182 (forward-char full-Y-label-width)))
20183 @end group
20184 @end smallexample
20185
20186 The @code{print-Y-axis} uses the @code{insert-rectangle} function to
20187 insert the Y axis labels created by the @code{Y-axis-column} function.
20188 In addition, it places point at the correct position for printing the body of
20189 the graph.
20190
20191 You can test @code{print-Y-axis}:
20192
20193 @enumerate
20194 @item
20195 Install
20196
20197 @smallexample
20198 @group
20199 Y-axis-label-spacing
20200 Y-axis-tic
20201 Y-axis-element
20202 Y-axis-column
20203 print-Y-axis
20204 @end group
20205 @end smallexample
20206
20207 @item
20208 Copy the following expression:
20209
20210 @smallexample
20211 (print-Y-axis 12 5)
20212 @end smallexample
20213
20214 @item
20215 Switch to the @file{*scratch*} buffer and place the cursor where you
20216 want the axis labels to start.
20217
20218 @item
20219 Type @kbd{M-:} (@code{eval-expression}).
20220
20221 @item
20222 Yank the @code{graph-body-print} expression into the minibuffer
20223 with @kbd{C-y} (@code{yank)}.
20224
20225 @item
20226 Press @key{RET} to evaluate the expression.
20227 @end enumerate
20228
20229 Emacs will print labels vertically, the top one being @w{@samp{10 -@w{
20230 }}}. (The @code{print-graph} function will pass the value of
20231 @code{height-of-top-line}, which in this case will end up as 15,
20232 thereby getting rid of what might appear as a bug.)
20233
20234 @need 2000
20235 @node print-X-axis
20236 @appendixsec The @code{print-X-axis} Function
20237 @cindex Axis, print horizontal
20238 @cindex X axis printing
20239 @cindex Print horizontal axis
20240 @cindex Horizontal axis printing
20241
20242 X axis labels are much like Y axis labels, except that the ticks are on a
20243 line above the numbers. Labels should look like this:
20244
20245 @smallexample
20246 @group
20247 | | | |
20248 1 5 10 15
20249 @end group
20250 @end smallexample
20251
20252 The first tic is under the first column of the graph and is preceded by
20253 several blank spaces. These spaces provide room in rows above for the Y
20254 axis labels. The second, third, fourth, and subsequent ticks are all
20255 spaced equally, according to the value of @code{X-axis-label-spacing}.
20256
20257 The second row of the X axis consists of numbers, preceded by several
20258 blank spaces and also separated according to the value of the variable
20259 @code{X-axis-label-spacing}.
20260
20261 The value of the variable @code{X-axis-label-spacing} should itself be
20262 measured in units of @code{symbol-width}, since you may want to change
20263 the width of the symbols that you are using to print the body of the
20264 graph without changing the ways the graph is labeled.
20265
20266 @menu
20267 * Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
20268 * X Axis Tic Marks:: Create tic marks for the horizontal axis.
20269 @end menu
20270
20271 @ifnottex
20272 @node Similarities differences
20273 @unnumberedsubsec Similarities and differences
20274 @end ifnottex
20275
20276 The @code{print-X-axis} function is constructed in more or less the
20277 same fashion as the @code{print-Y-axis} function except that it has
20278 two lines: the line of tic marks and the numbers. We will write a
20279 separate function to print each line and then combine them within the
20280 @code{print-X-axis} function.
20281
20282 This is a three step process:
20283
20284 @enumerate
20285 @item
20286 Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
20287
20288 @item
20289 Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
20290
20291 @item
20292 Write a function to print both lines, the @code{print-X-axis} function,
20293 using @code{print-X-axis-tic-line} and
20294 @code{print-X-axis-numbered-line}.
20295 @end enumerate
20296
20297 @node X Axis Tic Marks
20298 @appendixsubsec X Axis Tic Marks
20299
20300 The first function should print the X axis tic marks. We must specify
20301 the tic marks themselves and their spacing:
20302
20303 @smallexample
20304 @group
20305 (defvar X-axis-label-spacing
20306 (if (boundp 'graph-blank)
20307 (* 5 (length graph-blank)) 5)
20308 "Number of units from one X axis label to next.")
20309 @end group
20310 @end smallexample
20311
20312 @noindent
20313 (Note that the value of @code{graph-blank} is set by another
20314 @code{defvar}. The @code{boundp} predicate checks whether it has
20315 already been set; @code{boundp} returns @code{nil} if it has not. If
20316 @code{graph-blank} were unbound and we did not use this conditional
20317 construction, in a recent GNU Emacs, we would enter the debugger and
20318 see an error message saying @samp{@w{Debugger entered--Lisp error:}
20319 @w{(void-variable graph-blank)}}.)
20320
20321 @need 1200
20322 Here is the @code{defvar} for @code{X-axis-tic-symbol}:
20323
20324 @smallexample
20325 @group
20326 (defvar X-axis-tic-symbol "|"
20327 "String to insert to point to a column in X axis.")
20328 @end group
20329 @end smallexample
20330
20331 @need 1250
20332 The goal is to make a line that looks like this:
20333
20334 @smallexample
20335 | | | |
20336 @end smallexample
20337
20338 The first tic is indented so that it is under the first column, which is
20339 indented to provide space for the Y axis labels.
20340
20341 A tic element consists of the blank spaces that stretch from one tic to
20342 the next plus a tic symbol. The number of blanks is determined by the
20343 width of the tic symbol and the @code{X-axis-label-spacing}.
20344
20345 @need 1250
20346 The code looks like this:
20347
20348 @smallexample
20349 @group
20350 ;;; X-axis-tic-element
20351 @dots{}
20352 (concat
20353 (make-string
20354 ;; @r{Make a string of blanks.}
20355 (- (* symbol-width X-axis-label-spacing)
20356 (length X-axis-tic-symbol))
20357 ? )
20358 ;; @r{Concatenate blanks with tic symbol.}
20359 X-axis-tic-symbol)
20360 @dots{}
20361 @end group
20362 @end smallexample
20363
20364 Next, we determine how many blanks are needed to indent the first tic
20365 mark to the first column of the graph. This uses the value of
20366 @code{full-Y-label-width} passed it by the @code{print-graph} function.
20367
20368 @need 1250
20369 The code to make @code{X-axis-leading-spaces}
20370 looks like this:
20371
20372 @smallexample
20373 @group
20374 ;; X-axis-leading-spaces
20375 @dots{}
20376 (make-string full-Y-label-width ? )
20377 @dots{}
20378 @end group
20379 @end smallexample
20380
20381 We also need to determine the length of the horizontal axis, which is
20382 the length of the numbers list, and the number of ticks in the horizontal
20383 axis:
20384
20385 @smallexample
20386 @group
20387 ;; X-length
20388 @dots{}
20389 (length numbers-list)
20390 @end group
20391
20392 @group
20393 ;; tic-width
20394 @dots{}
20395 (* symbol-width X-axis-label-spacing)
20396 @end group
20397
20398 @group
20399 ;; number-of-X-ticks
20400 (if (zerop (% (X-length tic-width)))
20401 (/ (X-length tic-width))
20402 (1+ (/ (X-length tic-width))))
20403 @end group
20404 @end smallexample
20405
20406 @need 1250
20407 All this leads us directly to the function for printing the X axis tic line:
20408
20409 @findex print-X-axis-tic-line
20410 @smallexample
20411 @group
20412 (defun print-X-axis-tic-line
20413 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20414 "Print ticks for X axis."
20415 (insert X-axis-leading-spaces)
20416 (insert X-axis-tic-symbol) ; @r{Under first column.}
20417 @end group
20418 @group
20419 ;; @r{Insert second tic in the right spot.}
20420 (insert (concat
20421 (make-string
20422 (- (* symbol-width X-axis-label-spacing)
20423 ;; @r{Insert white space up to second tic symbol.}
20424 (* 2 (length X-axis-tic-symbol)))
20425 ? )
20426 X-axis-tic-symbol))
20427 @end group
20428 @group
20429 ;; @r{Insert remaining ticks.}
20430 (while (> number-of-X-tics 1)
20431 (insert X-axis-tic-element)
20432 (setq number-of-X-tics (1- number-of-X-tics))))
20433 @end group
20434 @end smallexample
20435
20436 The line of numbers is equally straightforward:
20437
20438 @need 1250
20439 First, we create a numbered element with blank spaces before each number:
20440
20441 @findex X-axis-element
20442 @smallexample
20443 @group
20444 (defun X-axis-element (number)
20445 "Construct a numbered X axis element."
20446 (let ((leading-spaces
20447 (- (* symbol-width X-axis-label-spacing)
20448 (length (number-to-string number)))))
20449 (concat (make-string leading-spaces ? )
20450 (number-to-string number))))
20451 @end group
20452 @end smallexample
20453
20454 Next, we create the function to print the numbered line, starting with
20455 the number ``1'' under the first column:
20456
20457 @findex print-X-axis-numbered-line
20458 @smallexample
20459 @group
20460 (defun print-X-axis-numbered-line
20461 (number-of-X-tics X-axis-leading-spaces)
20462 "Print line of X-axis numbers"
20463 (let ((number X-axis-label-spacing))
20464 (insert X-axis-leading-spaces)
20465 (insert "1")
20466 @end group
20467 @group
20468 (insert (concat
20469 (make-string
20470 ;; @r{Insert white space up to next number.}
20471 (- (* symbol-width X-axis-label-spacing) 2)
20472 ? )
20473 (number-to-string number)))
20474 @end group
20475 @group
20476 ;; @r{Insert remaining numbers.}
20477 (setq number (+ number X-axis-label-spacing))
20478 (while (> number-of-X-tics 1)
20479 (insert (X-axis-element number))
20480 (setq number (+ number X-axis-label-spacing))
20481 (setq number-of-X-tics (1- number-of-X-tics)))))
20482 @end group
20483 @end smallexample
20484
20485 Finally, we need to write the @code{print-X-axis} that uses
20486 @code{print-X-axis-tic-line} and
20487 @code{print-X-axis-numbered-line}.
20488
20489 The function must determine the local values of the variables used by both
20490 @code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
20491 then it must call them. Also, it must print the carriage return that
20492 separates the two lines.
20493
20494 The function consists of a varlist that specifies five local variables,
20495 and calls to each of the two line printing functions:
20496
20497 @findex print-X-axis
20498 @smallexample
20499 @group
20500 (defun print-X-axis (numbers-list)
20501 "Print X axis labels to length of NUMBERS-LIST."
20502 (let* ((leading-spaces
20503 (make-string full-Y-label-width ? ))
20504 @end group
20505 @group
20506 ;; symbol-width @r{is provided by} graph-body-print
20507 (tic-width (* symbol-width X-axis-label-spacing))
20508 (X-length (length numbers-list))
20509 @end group
20510 @group
20511 (X-tic
20512 (concat
20513 (make-string
20514 @end group
20515 @group
20516 ;; @r{Make a string of blanks.}
20517 (- (* symbol-width X-axis-label-spacing)
20518 (length X-axis-tic-symbol))
20519 ? )
20520 @end group
20521 @group
20522 ;; @r{Concatenate blanks with tic symbol.}
20523 X-axis-tic-symbol))
20524 @end group
20525 @group
20526 (tic-number
20527 (if (zerop (% X-length tic-width))
20528 (/ X-length tic-width)
20529 (1+ (/ X-length tic-width)))))
20530 @end group
20531 @group
20532 (print-X-axis-tic-line tic-number leading-spaces X-tic)
20533 (insert "\n")
20534 (print-X-axis-numbered-line tic-number leading-spaces)))
20535 @end group
20536 @end smallexample
20537
20538 @need 1250
20539 You can test @code{print-X-axis}:
20540
20541 @enumerate
20542 @item
20543 Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
20544 @code{print-X-axis-tic-line}, as well as @code{X-axis-element},
20545 @code{print-X-axis-numbered-line}, and @code{print-X-axis}.
20546
20547 @item
20548 Copy the following expression:
20549
20550 @smallexample
20551 @group
20552 (progn
20553 (let ((full-Y-label-width 5)
20554 (symbol-width 1))
20555 (print-X-axis
20556 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
20557 @end group
20558 @end smallexample
20559
20560 @item
20561 Switch to the @file{*scratch*} buffer and place the cursor where you
20562 want the axis labels to start.
20563
20564 @item
20565 Type @kbd{M-:} (@code{eval-expression}).
20566
20567 @item
20568 Yank the test expression into the minibuffer
20569 with @kbd{C-y} (@code{yank)}.
20570
20571 @item
20572 Press @key{RET} to evaluate the expression.
20573 @end enumerate
20574
20575 @need 1250
20576 Emacs will print the horizontal axis like this:
20577 @sp 1
20578
20579 @smallexample
20580 @group
20581 | | | | |
20582 1 5 10 15 20
20583 @end group
20584 @end smallexample
20585
20586 @node Print Whole Graph
20587 @appendixsec Printing the Whole Graph
20588 @cindex Printing the whole graph
20589 @cindex Whole graph printing
20590 @cindex Graph, printing all
20591
20592 Now we are nearly ready to print the whole graph.
20593
20594 The function to print the graph with the proper labels follows the
20595 outline we created earlier (@pxref{Full Graph, , A Graph with Labeled
20596 Axes}), but with additions.
20597
20598 @need 1250
20599 Here is the outline:
20600
20601 @smallexample
20602 @group
20603 (defun print-graph (numbers-list)
20604 "@var{documentation}@dots{}"
20605 (let ((height @dots{}
20606 @dots{}))
20607 @end group
20608 @group
20609 (print-Y-axis height @dots{} )
20610 (graph-body-print numbers-list)
20611 (print-X-axis @dots{} )))
20612 @end group
20613 @end smallexample
20614
20615 @menu
20616 * The final version:: A few changes.
20617 * Test print-graph:: Run a short test.
20618 * Graphing words in defuns:: Executing the final code.
20619 * lambda:: How to write an anonymous function.
20620 * mapcar:: Apply a function to elements of a list.
20621 * Another Bug:: Yet another bug @dots{} most insidious.
20622 * Final printed graph:: The graph itself!
20623 @end menu
20624
20625 @ifnottex
20626 @node The final version
20627 @unnumberedsubsec Changes for the Final Version
20628 @end ifnottex
20629
20630 The final version is different from what we planned in two ways:
20631 first, it contains additional values calculated once in the varlist;
20632 second, it carries an option to specify the labels' increment per row.
20633 This latter feature turns out to be essential; otherwise, a graph may
20634 have more rows than fit on a display or on a sheet of paper.
20635
20636 @need 1500
20637 This new feature requires a change to the @code{Y-axis-column}
20638 function, to add @code{vertical-step} to it. The function looks like
20639 this:
20640
20641 @findex Y-axis-column @r{Final version.}
20642 @smallexample
20643 @group
20644 ;;; @r{Final version.}
20645 (defun Y-axis-column
20646 (height width-of-label &optional vertical-step)
20647 "Construct list of labels for Y axis.
20648 HEIGHT is maximum height of graph.
20649 WIDTH-OF-LABEL is maximum width of label.
20650 VERTICAL-STEP, an option, is a positive integer
20651 that specifies how much a Y axis label increments
20652 for each line. For example, a step of 5 means
20653 that each line is five units of the graph."
20654 @end group
20655 @group
20656 (let (Y-axis
20657 (number-per-line (or vertical-step 1)))
20658 (while (> height 1)
20659 (if (zerop (% height Y-axis-label-spacing))
20660 @end group
20661 @group
20662 ;; @r{Insert label.}
20663 (setq Y-axis
20664 (cons
20665 (Y-axis-element
20666 (* height number-per-line)
20667 width-of-label)
20668 Y-axis))
20669 @end group
20670 @group
20671 ;; @r{Else, insert blanks.}
20672 (setq Y-axis
20673 (cons
20674 (make-string width-of-label ? )
20675 Y-axis)))
20676 (setq height (1- height)))
20677 @end group
20678 @group
20679 ;; @r{Insert base line.}
20680 (setq Y-axis (cons (Y-axis-element
20681 (or vertical-step 1)
20682 width-of-label)
20683 Y-axis))
20684 (nreverse Y-axis)))
20685 @end group
20686 @end smallexample
20687
20688 The values for the maximum height of graph and the width of a symbol
20689 are computed by @code{print-graph} in its @code{let} expression; so
20690 @code{graph-body-print} must be changed to accept them.
20691
20692 @findex graph-body-print @r{Final version.}
20693 @smallexample
20694 @group
20695 ;;; @r{Final version.}
20696 (defun graph-body-print (numbers-list height symbol-width)
20697 "Print a bar graph of the NUMBERS-LIST.
20698 The numbers-list consists of the Y-axis values.
20699 HEIGHT is maximum height of graph.
20700 SYMBOL-WIDTH is number of each column."
20701 @end group
20702 @group
20703 (let (from-position)
20704 (while numbers-list
20705 (setq from-position (point))
20706 (insert-rectangle
20707 (column-of-graph height (car numbers-list)))
20708 (goto-char from-position)
20709 (forward-char symbol-width)
20710 @end group
20711 @group
20712 ;; @r{Draw graph column by column.}
20713 (sit-for 0)
20714 (setq numbers-list (cdr numbers-list)))
20715 ;; @r{Place point for X axis labels.}
20716 (forward-line height)
20717 (insert "\n")))
20718 @end group
20719 @end smallexample
20720
20721 @need 1250
20722 Finally, the code for the @code{print-graph} function:
20723
20724 @findex print-graph @r{Final version.}
20725 @smallexample
20726 @group
20727 ;;; @r{Final version.}
20728 (defun print-graph
20729 (numbers-list &optional vertical-step)
20730 "Print labeled bar graph of the NUMBERS-LIST.
20731 The numbers-list consists of the Y-axis values.
20732 @end group
20733
20734 @group
20735 Optionally, VERTICAL-STEP, a positive integer,
20736 specifies how much a Y axis label increments for
20737 each line. For example, a step of 5 means that
20738 each row is five units."
20739 @end group
20740 @group
20741 (let* ((symbol-width (length graph-blank))
20742 ;; @code{height} @r{is both the largest number}
20743 ;; @r{and the number with the most digits.}
20744 (height (apply 'max numbers-list))
20745 @end group
20746 @group
20747 (height-of-top-line
20748 (if (zerop (% height Y-axis-label-spacing))
20749 height
20750 ;; @r{else}
20751 (* (1+ (/ height Y-axis-label-spacing))
20752 Y-axis-label-spacing)))
20753 @end group
20754 @group
20755 (vertical-step (or vertical-step 1))
20756 (full-Y-label-width
20757 (length
20758 @end group
20759 @group
20760 (concat
20761 (number-to-string
20762 (* height-of-top-line vertical-step))
20763 Y-axis-tic))))
20764 @end group
20765
20766 @group
20767 (print-Y-axis
20768 height-of-top-line full-Y-label-width vertical-step)
20769 @end group
20770 @group
20771 (graph-body-print
20772 numbers-list height-of-top-line symbol-width)
20773 (print-X-axis numbers-list)))
20774 @end group
20775 @end smallexample
20776
20777 @node Test print-graph
20778 @appendixsubsec Testing @code{print-graph}
20779
20780 @need 1250
20781 We can test the @code{print-graph} function with a short list of numbers:
20782
20783 @enumerate
20784 @item
20785 Install the final versions of @code{Y-axis-column},
20786 @code{graph-body-print}, and @code{print-graph} (in addition to the
20787 rest of the code.)
20788
20789 @item
20790 Copy the following expression:
20791
20792 @smallexample
20793 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
20794 @end smallexample
20795
20796 @item
20797 Switch to the @file{*scratch*} buffer and place the cursor where you
20798 want the axis labels to start.
20799
20800 @item
20801 Type @kbd{M-:} (@code{eval-expression}).
20802
20803 @item
20804 Yank the test expression into the minibuffer
20805 with @kbd{C-y} (@code{yank)}.
20806
20807 @item
20808 Press @key{RET} to evaluate the expression.
20809 @end enumerate
20810
20811 @need 1250
20812 Emacs will print a graph that looks like this:
20813
20814 @smallexample
20815 @group
20816 10 -
20817
20818
20819 *
20820 ** *
20821 5 - **** *
20822 **** ***
20823 * *********
20824 ************
20825 1 - *************
20826
20827 | | | |
20828 1 5 10 15
20829 @end group
20830 @end smallexample
20831
20832 @need 1200
20833 On the other hand, if you pass @code{print-graph} a
20834 @code{vertical-step} value of 2, by evaluating this expression:
20835
20836 @smallexample
20837 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
20838 @end smallexample
20839
20840 @need 1250
20841 @noindent
20842 The graph looks like this:
20843
20844 @smallexample
20845 @group
20846 20 -
20847
20848
20849 *
20850 ** *
20851 10 - **** *
20852 **** ***
20853 * *********
20854 ************
20855 2 - *************
20856
20857 | | | |
20858 1 5 10 15
20859 @end group
20860 @end smallexample
20861
20862 @noindent
20863 (A question: is the `2' on the bottom of the vertical axis a bug or a
20864 feature? If you think it is a bug, and should be a `1' instead, (or
20865 even a `0'), you can modify the sources.)
20866
20867 @node Graphing words in defuns
20868 @appendixsubsec Graphing Numbers of Words and Symbols
20869
20870 Now for the graph for which all this code was written: a graph that
20871 shows how many function definitions contain fewer than 10 words and
20872 symbols, how many contain between 10 and 19 words and symbols, how
20873 many contain between 20 and 29 words and symbols, and so on.
20874
20875 This is a multi-step process. First make sure you have loaded all the
20876 requisite code.
20877
20878 @need 1500
20879 It is a good idea to reset the value of @code{top-of-ranges} in case
20880 you have set it to some different value. You can evaluate the
20881 following:
20882
20883 @smallexample
20884 @group
20885 (setq top-of-ranges
20886 '(10 20 30 40 50
20887 60 70 80 90 100
20888 110 120 130 140 150
20889 160 170 180 190 200
20890 210 220 230 240 250
20891 260 270 280 290 300)
20892 @end group
20893 @end smallexample
20894
20895 @noindent
20896 Next create a list of the number of words and symbols in each range.
20897
20898 @need 1500
20899 @noindent
20900 Evaluate the following:
20901
20902 @smallexample
20903 @group
20904 (setq list-for-graph
20905 (defuns-per-range
20906 (sort
20907 (recursive-lengths-list-many-files
20908 (directory-files "/usr/local/emacs/lisp"
20909 t ".+el$"))
20910 '<)
20911 top-of-ranges))
20912 @end group
20913 @end smallexample
20914
20915 @noindent
20916 On my old machine, this took about an hour. It looked though 303 Lisp
20917 files in my copy of Emacs version 19.23. After all that computing,
20918 the @code{list-for-graph} had this value:
20919
20920 @smallexample
20921 @group
20922 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
20923 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20924 @end group
20925 @end smallexample
20926
20927 @noindent
20928 This means that my copy of Emacs had 537 function definitions with
20929 fewer than 10 words or symbols in them, 1,027 function definitions
20930 with 10 to 19 words or symbols in them, 955 function definitions with
20931 20 to 29 words or symbols in them, and so on.
20932
20933 Clearly, just by looking at this list we can see that most function
20934 definitions contain ten to thirty words and symbols.
20935
20936 Now for printing. We do @emph{not} want to print a graph that is
20937 1,030 lines high @dots{} Instead, we should print a graph that is
20938 fewer than twenty-five lines high. A graph that height can be
20939 displayed on almost any monitor, and easily printed on a sheet of paper.
20940
20941 This means that each value in @code{list-for-graph} must be reduced to
20942 one-fiftieth its present value.
20943
20944 Here is a short function to do just that, using two functions we have
20945 not yet seen, @code{mapcar} and @code{lambda}.
20946
20947 @smallexample
20948 @group
20949 (defun one-fiftieth (full-range)
20950 "Return list, each number one-fiftieth of previous."
20951 (mapcar (lambda (arg) (/ arg 50)) full-range))
20952 @end group
20953 @end smallexample
20954
20955 @node lambda
20956 @appendixsubsec A @code{lambda} Expression: Useful Anonymity
20957 @cindex Anonymous function
20958 @findex lambda
20959
20960 @code{lambda} is the symbol for an anonymous function, a function
20961 without a name. Every time you use an anonymous function, you need to
20962 include its whole body.
20963
20964 @need 1250
20965 @noindent
20966 Thus,
20967
20968 @smallexample
20969 (lambda (arg) (/ arg 50))
20970 @end smallexample
20971
20972 @noindent
20973 is a function definition that says `return the value resulting from
20974 dividing whatever is passed to me as @code{arg} by 50'.
20975
20976 @need 1200
20977 Earlier, for example, we had a function @code{multiply-by-seven}; it
20978 multiplied its argument by 7. This function is similar, except it
20979 divides its argument by 50; and, it has no name. The anonymous
20980 equivalent of @code{multiply-by-seven} is:
20981
20982 @smallexample
20983 (lambda (number) (* 7 number))
20984 @end smallexample
20985
20986 @noindent
20987 (@xref{defun, , The @code{defun} Special Form}.)
20988
20989 @need 1250
20990 @noindent
20991 If we want to multiply 3 by 7, we can write:
20992
20993 @c !!! Clear print-postscript-figures if the computer formatting this
20994 @c document is too small and cannot handle all the diagrams and figures.
20995 @c clear print-postscript-figures
20996 @c set print-postscript-figures
20997 @c lambda example diagram #1
20998 @ifnottex
20999 @smallexample
21000 @group
21001 (multiply-by-seven 3)
21002 \_______________/ ^
21003 | |
21004 function argument
21005 @end group
21006 @end smallexample
21007 @end ifnottex
21008 @ifset print-postscript-figures
21009 @sp 1
21010 @tex
21011 @center @image{lambda-1}
21012 %%%% old method of including an image
21013 % \input /usr/local/lib/tex/inputs/psfig.tex
21014 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
21015 % \catcode`\@=0 %
21016 @end tex
21017 @sp 1
21018 @end ifset
21019 @ifclear print-postscript-figures
21020 @iftex
21021 @smallexample
21022 @group
21023 (multiply-by-seven 3)
21024 \_______________/ ^
21025 | |
21026 function argument
21027 @end group
21028 @end smallexample
21029 @end iftex
21030 @end ifclear
21031
21032 @noindent
21033 This expression returns 21.
21034
21035 @need 1250
21036 @noindent
21037 Similarly, we can write:
21038
21039 @c lambda example diagram #2
21040 @ifnottex
21041 @smallexample
21042 @group
21043 ((lambda (number) (* 7 number)) 3)
21044 \____________________________/ ^
21045 | |
21046 anonymous function argument
21047 @end group
21048 @end smallexample
21049 @end ifnottex
21050 @ifset print-postscript-figures
21051 @sp 1
21052 @tex
21053 @center @image{lambda-2}
21054 %%%% old method of including an image
21055 % \input /usr/local/lib/tex/inputs/psfig.tex
21056 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
21057 % \catcode`\@=0 %
21058 @end tex
21059 @sp 1
21060 @end ifset
21061 @ifclear print-postscript-figures
21062 @iftex
21063 @smallexample
21064 @group
21065 ((lambda (number) (* 7 number)) 3)
21066 \____________________________/ ^
21067 | |
21068 anonymous function argument
21069 @end group
21070 @end smallexample
21071 @end iftex
21072 @end ifclear
21073
21074 @need 1250
21075 @noindent
21076 If we want to divide 100 by 50, we can write:
21077
21078 @c lambda example diagram #3
21079 @ifnottex
21080 @smallexample
21081 @group
21082 ((lambda (arg) (/ arg 50)) 100)
21083 \______________________/ \_/
21084 | |
21085 anonymous function argument
21086 @end group
21087 @end smallexample
21088 @end ifnottex
21089 @ifset print-postscript-figures
21090 @sp 1
21091 @tex
21092 @center @image{lambda-3}
21093 %%%% old method of including an image
21094 % \input /usr/local/lib/tex/inputs/psfig.tex
21095 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
21096 % \catcode`\@=0 %
21097 @end tex
21098 @sp 1
21099 @end ifset
21100 @ifclear print-postscript-figures
21101 @iftex
21102 @smallexample
21103 @group
21104 ((lambda (arg) (/ arg 50)) 100)
21105 \______________________/ \_/
21106 | |
21107 anonymous function argument
21108 @end group
21109 @end smallexample
21110 @end iftex
21111 @end ifclear
21112
21113 @noindent
21114 This expression returns 2. The 100 is passed to the function, which
21115 divides that number by 50.
21116
21117 @xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
21118 Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
21119 expressions derive from the Lambda Calculus.
21120
21121 @node mapcar
21122 @appendixsubsec The @code{mapcar} Function
21123 @findex mapcar
21124
21125 @code{mapcar} is a function that calls its first argument with each
21126 element of its second argument, in turn. The second argument must be
21127 a sequence.
21128
21129 The @samp{map} part of the name comes from the mathematical phrase,
21130 `mapping over a domain', meaning to apply a function to each of the
21131 elements in a domain. The mathematical phrase is based on the
21132 metaphor of a surveyor walking, one step at a time, over an area he is
21133 mapping. And @samp{car}, of course, comes from the Lisp notion of the
21134 first of a list.
21135
21136 @need 1250
21137 @noindent
21138 For example,
21139
21140 @smallexample
21141 @group
21142 (mapcar '1+ '(2 4 6))
21143 @result{} (3 5 7)
21144 @end group
21145 @end smallexample
21146
21147 @noindent
21148 The function @code{1+} which adds one to its argument, is executed on
21149 @emph{each} element of the list, and a new list is returned.
21150
21151 Contrast this with @code{apply}, which applies its first argument to
21152 all the remaining.
21153 (@xref{Readying a Graph, , Readying a Graph}, for a explanation of
21154 @code{apply}.)
21155
21156 @need 1250
21157 In the definition of @code{one-fiftieth}, the first argument is the
21158 anonymous function:
21159
21160 @smallexample
21161 (lambda (arg) (/ arg 50))
21162 @end smallexample
21163
21164 @noindent
21165 and the second argument is @code{full-range}, which will be bound to
21166 @code{list-for-graph}.
21167
21168 @need 1250
21169 The whole expression looks like this:
21170
21171 @smallexample
21172 (mapcar (lambda (arg) (/ arg 50)) full-range))
21173 @end smallexample
21174
21175 @xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
21176 Lisp Reference Manual}, for more about @code{mapcar}.
21177
21178 Using the @code{one-fiftieth} function, we can generate a list in
21179 which each element is one-fiftieth the size of the corresponding
21180 element in @code{list-for-graph}.
21181
21182 @smallexample
21183 @group
21184 (setq fiftieth-list-for-graph
21185 (one-fiftieth list-for-graph))
21186 @end group
21187 @end smallexample
21188
21189 @need 1250
21190 The resulting list looks like this:
21191
21192 @smallexample
21193 @group
21194 (10 20 19 15 11 9 6 5 4 3 3 2 2
21195 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
21196 @end group
21197 @end smallexample
21198
21199 @noindent
21200 This, we are almost ready to print! (We also notice the loss of
21201 information: many of the higher ranges are 0, meaning that fewer than
21202 50 defuns had that many words or symbols---but not necessarily meaning
21203 that none had that many words or symbols.)
21204
21205 @node Another Bug
21206 @appendixsubsec Another Bug @dots{} Most Insidious
21207 @cindex Bug, most insidious type
21208 @cindex Insidious type of bug
21209
21210 I said `almost ready to print'! Of course, there is a bug in the
21211 @code{print-graph} function @dots{} It has a @code{vertical-step}
21212 option, but not a @code{horizontal-step} option. The
21213 @code{top-of-range} scale goes from 10 to 300 by tens. But the
21214 @code{print-graph} function will print only by ones.
21215
21216 This is a classic example of what some consider the most insidious
21217 type of bug, the bug of omission. This is not the kind of bug you can
21218 find by studying the code, for it is not in the code; it is an omitted
21219 feature. Your best actions are to try your program early and often;
21220 and try to arrange, as much as you can, to write code that is easy to
21221 understand and easy to change. Try to be aware, whenever you can,
21222 that whatever you have written, @emph{will} be rewritten, if not soon,
21223 eventually. A hard maxim to follow.
21224
21225 It is the @code{print-X-axis-numbered-line} function that needs the
21226 work; and then the @code{print-X-axis} and the @code{print-graph}
21227 functions need to be adapted. Not much needs to be done; there is one
21228 nicety: the numbers ought to line up under the tic marks. This takes
21229 a little thought.
21230
21231 @need 1250
21232 Here is the corrected @code{print-X-axis-numbered-line}:
21233
21234 @smallexample
21235 @group
21236 (defun print-X-axis-numbered-line
21237 (number-of-X-tics X-axis-leading-spaces
21238 &optional horizontal-step)
21239 "Print line of X-axis numbers"
21240 (let ((number X-axis-label-spacing)
21241 (horizontal-step (or horizontal-step 1)))
21242 @end group
21243 @group
21244 (insert X-axis-leading-spaces)
21245 ;; @r{Delete extra leading spaces.}
21246 (delete-char
21247 (- (1-
21248 (length (number-to-string horizontal-step)))))
21249 (insert (concat
21250 (make-string
21251 @end group
21252 @group
21253 ;; @r{Insert white space.}
21254 (- (* symbol-width
21255 X-axis-label-spacing)
21256 (1-
21257 (length
21258 (number-to-string horizontal-step)))
21259 2)
21260 ? )
21261 (number-to-string
21262 (* number horizontal-step))))
21263 @end group
21264 @group
21265 ;; @r{Insert remaining numbers.}
21266 (setq number (+ number X-axis-label-spacing))
21267 (while (> number-of-X-tics 1)
21268 (insert (X-axis-element
21269 (* number horizontal-step)))
21270 (setq number (+ number X-axis-label-spacing))
21271 (setq number-of-X-tics (1- number-of-X-tics)))))
21272 @end group
21273 @end smallexample
21274
21275 @need 1500
21276 If you are reading this in Info, you can see the new versions of
21277 @code{print-X-axis} @code{print-graph} and evaluate them. If you are
21278 reading this in a printed book, you can see the changed lines here
21279 (the full text is too much to print).
21280
21281 @iftex
21282 @smallexample
21283 @group
21284 (defun print-X-axis (numbers-list horizontal-step)
21285 @dots{}
21286 (print-X-axis-numbered-line
21287 tic-number leading-spaces horizontal-step))
21288 @end group
21289 @end smallexample
21290
21291 @smallexample
21292 @group
21293 (defun print-graph
21294 (numbers-list
21295 &optional vertical-step horizontal-step)
21296 @dots{}
21297 (print-X-axis numbers-list horizontal-step))
21298 @end group
21299 @end smallexample
21300 @end iftex
21301
21302 @ifnottex
21303 @smallexample
21304 @group
21305 (defun print-X-axis (numbers-list horizontal-step)
21306 "Print X axis labels to length of NUMBERS-LIST.
21307 Optionally, HORIZONTAL-STEP, a positive integer,
21308 specifies how much an X axis label increments for
21309 each column."
21310 @end group
21311 @group
21312 ;; Value of symbol-width and full-Y-label-width
21313 ;; are passed by `print-graph'.
21314 (let* ((leading-spaces
21315 (make-string full-Y-label-width ? ))
21316 ;; symbol-width @r{is provided by} graph-body-print
21317 (tic-width (* symbol-width X-axis-label-spacing))
21318 (X-length (length numbers-list))
21319 @end group
21320 @group
21321 (X-tic
21322 (concat
21323 (make-string
21324 ;; @r{Make a string of blanks.}
21325 (- (* symbol-width X-axis-label-spacing)
21326 (length X-axis-tic-symbol))
21327 ? )
21328 @end group
21329 @group
21330 ;; @r{Concatenate blanks with tic symbol.}
21331 X-axis-tic-symbol))
21332 (tic-number
21333 (if (zerop (% X-length tic-width))
21334 (/ X-length tic-width)
21335 (1+ (/ X-length tic-width)))))
21336 @end group
21337
21338 @group
21339 (print-X-axis-tic-line
21340 tic-number leading-spaces X-tic)
21341 (insert "\n")
21342 (print-X-axis-numbered-line
21343 tic-number leading-spaces horizontal-step)))
21344 @end group
21345 @end smallexample
21346
21347 @smallexample
21348 @group
21349 (defun print-graph
21350 (numbers-list &optional vertical-step horizontal-step)
21351 "Print labeled bar graph of the NUMBERS-LIST.
21352 The numbers-list consists of the Y-axis values.
21353 @end group
21354
21355 @group
21356 Optionally, VERTICAL-STEP, a positive integer,
21357 specifies how much a Y axis label increments for
21358 each line. For example, a step of 5 means that
21359 each row is five units.
21360 @end group
21361
21362 @group
21363 Optionally, HORIZONTAL-STEP, a positive integer,
21364 specifies how much an X axis label increments for
21365 each column."
21366 (let* ((symbol-width (length graph-blank))
21367 ;; @code{height} @r{is both the largest number}
21368 ;; @r{and the number with the most digits.}
21369 (height (apply 'max numbers-list))
21370 @end group
21371 @group
21372 (height-of-top-line
21373 (if (zerop (% height Y-axis-label-spacing))
21374 height
21375 ;; @r{else}
21376 (* (1+ (/ height Y-axis-label-spacing))
21377 Y-axis-label-spacing)))
21378 @end group
21379 @group
21380 (vertical-step (or vertical-step 1))
21381 (full-Y-label-width
21382 (length
21383 (concat
21384 (number-to-string
21385 (* height-of-top-line vertical-step))
21386 Y-axis-tic))))
21387 @end group
21388 @group
21389 (print-Y-axis
21390 height-of-top-line full-Y-label-width vertical-step)
21391 (graph-body-print
21392 numbers-list height-of-top-line symbol-width)
21393 (print-X-axis numbers-list horizontal-step)))
21394 @end group
21395 @end smallexample
21396 @end ifnottex
21397
21398 @c qqq
21399 @ignore
21400 Graphing Definitions Re-listed
21401
21402 @need 1250
21403 Here are all the graphing definitions in their final form:
21404
21405 @smallexample
21406 @group
21407 (defvar top-of-ranges
21408 '(10 20 30 40 50
21409 60 70 80 90 100
21410 110 120 130 140 150
21411 160 170 180 190 200
21412 210 220 230 240 250)
21413 "List specifying ranges for `defuns-per-range'.")
21414 @end group
21415
21416 @group
21417 (defvar graph-symbol "*"
21418 "String used as symbol in graph, usually an asterisk.")
21419 @end group
21420
21421 @group
21422 (defvar graph-blank " "
21423 "String used as blank in graph, usually a blank space.
21424 graph-blank must be the same number of columns wide
21425 as graph-symbol.")
21426 @end group
21427
21428 @group
21429 (defvar Y-axis-tic " - "
21430 "String that follows number in a Y axis label.")
21431 @end group
21432
21433 @group
21434 (defvar Y-axis-label-spacing 5
21435 "Number of lines from one Y axis label to next.")
21436 @end group
21437
21438 @group
21439 (defvar X-axis-tic-symbol "|"
21440 "String to insert to point to a column in X axis.")
21441 @end group
21442
21443 @group
21444 (defvar X-axis-label-spacing
21445 (if (boundp 'graph-blank)
21446 (* 5 (length graph-blank)) 5)
21447 "Number of units from one X axis label to next.")
21448 @end group
21449 @end smallexample
21450
21451 @smallexample
21452 @group
21453 (defun count-words-in-defun ()
21454 "Return the number of words and symbols in a defun."
21455 (beginning-of-defun)
21456 (let ((count 0)
21457 (end (save-excursion (end-of-defun) (point))))
21458 @end group
21459
21460 @group
21461 (while
21462 (and (< (point) end)
21463 (re-search-forward
21464 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
21465 end t))
21466 (setq count (1+ count)))
21467 count))
21468 @end group
21469 @end smallexample
21470
21471 @smallexample
21472 @group
21473 (defun lengths-list-file (filename)
21474 "Return list of definitions' lengths within FILE.
21475 The returned list is a list of numbers.
21476 Each number is the number of words or
21477 symbols in one function definition."
21478 @end group
21479
21480 @group
21481 (message "Working on `%s' ... " filename)
21482 (save-excursion
21483 (let ((buffer (find-file-noselect filename))
21484 (lengths-list))
21485 (set-buffer buffer)
21486 (setq buffer-read-only t)
21487 (widen)
21488 (goto-char (point-min))
21489 @end group
21490
21491 @group
21492 (while (re-search-forward "^(defun" nil t)
21493 (setq lengths-list
21494 (cons (count-words-in-defun) lengths-list)))
21495 (kill-buffer buffer)
21496 lengths-list)))
21497 @end group
21498 @end smallexample
21499
21500 @smallexample
21501 @group
21502 (defun lengths-list-many-files (list-of-files)
21503 "Return list of lengths of defuns in LIST-OF-FILES."
21504 (let (lengths-list)
21505 ;;; @r{true-or-false-test}
21506 (while list-of-files
21507 (setq lengths-list
21508 (append
21509 lengths-list
21510 @end group
21511 @group
21512 ;;; @r{Generate a lengths' list.}
21513 (lengths-list-file
21514 (expand-file-name (car list-of-files)))))
21515 ;;; @r{Make files' list shorter.}
21516 (setq list-of-files (cdr list-of-files)))
21517 ;;; @r{Return final value of lengths' list.}
21518 lengths-list))
21519 @end group
21520 @end smallexample
21521
21522 @smallexample
21523 @group
21524 (defun defuns-per-range (sorted-lengths top-of-ranges)
21525 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
21526 (let ((top-of-range (car top-of-ranges))
21527 (number-within-range 0)
21528 defuns-per-range-list)
21529 @end group
21530
21531 @group
21532 ;; @r{Outer loop.}
21533 (while top-of-ranges
21534
21535 ;; @r{Inner loop.}
21536 (while (and
21537 ;; @r{Need number for numeric test.}
21538 (car sorted-lengths)
21539 (< (car sorted-lengths) top-of-range))
21540
21541 ;; @r{Count number of definitions within current range.}
21542 (setq number-within-range (1+ number-within-range))
21543 (setq sorted-lengths (cdr sorted-lengths)))
21544 @end group
21545
21546 @group
21547 ;; @r{Exit inner loop but remain within outer loop.}
21548
21549 (setq defuns-per-range-list
21550 (cons number-within-range defuns-per-range-list))
21551 (setq number-within-range 0) ; @r{Reset count to zero.}
21552
21553 ;; @r{Move to next range.}
21554 (setq top-of-ranges (cdr top-of-ranges))
21555 ;; @r{Specify next top of range value.}
21556 (setq top-of-range (car top-of-ranges)))
21557 @end group
21558
21559 @group
21560 ;; @r{Exit outer loop and count the number of defuns larger than}
21561 ;; @r{ the largest top-of-range value.}
21562 (setq defuns-per-range-list
21563 (cons
21564 (length sorted-lengths)
21565 defuns-per-range-list))
21566
21567 ;; @r{Return a list of the number of definitions within each range,}
21568 ;; @r{ smallest to largest.}
21569 (nreverse defuns-per-range-list)))
21570 @end group
21571 @end smallexample
21572
21573 @smallexample
21574 @group
21575 (defun column-of-graph (max-graph-height actual-height)
21576 "Return list of MAX-GRAPH-HEIGHT strings;
21577 ACTUAL-HEIGHT are graph-symbols.
21578 The graph-symbols are contiguous entries at the end
21579 of the list.
21580 The list will be inserted as one column of a graph.
21581 The strings are either graph-blank or graph-symbol."
21582 @end group
21583
21584 @group
21585 (let ((insert-list nil)
21586 (number-of-top-blanks
21587 (- max-graph-height actual-height)))
21588
21589 ;; @r{Fill in @code{graph-symbols}.}
21590 (while (> actual-height 0)
21591 (setq insert-list (cons graph-symbol insert-list))
21592 (setq actual-height (1- actual-height)))
21593 @end group
21594
21595 @group
21596 ;; @r{Fill in @code{graph-blanks}.}
21597 (while (> number-of-top-blanks 0)
21598 (setq insert-list (cons graph-blank insert-list))
21599 (setq number-of-top-blanks
21600 (1- number-of-top-blanks)))
21601
21602 ;; @r{Return whole list.}
21603 insert-list))
21604 @end group
21605 @end smallexample
21606
21607 @smallexample
21608 @group
21609 (defun Y-axis-element (number full-Y-label-width)
21610 "Construct a NUMBERed label element.
21611 A numbered element looks like this ` 5 - ',
21612 and is padded as needed so all line up with
21613 the element for the largest number."
21614 @end group
21615 @group
21616 (let* ((leading-spaces
21617 (- full-Y-label-width
21618 (length
21619 (concat (number-to-string number)
21620 Y-axis-tic)))))
21621 @end group
21622 @group
21623 (concat
21624 (make-string leading-spaces ? )
21625 (number-to-string number)
21626 Y-axis-tic)))
21627 @end group
21628 @end smallexample
21629
21630 @smallexample
21631 @group
21632 (defun print-Y-axis
21633 (height full-Y-label-width &optional vertical-step)
21634 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
21635 Height must be the maximum height of the graph.
21636 Full width is the width of the highest label element.
21637 Optionally, print according to VERTICAL-STEP."
21638 @end group
21639 @group
21640 ;; Value of height and full-Y-label-width
21641 ;; are passed by `print-graph'.
21642 (let ((start (point)))
21643 (insert-rectangle
21644 (Y-axis-column height full-Y-label-width vertical-step))
21645 @end group
21646 @group
21647 ;; @r{Place point ready for inserting graph.}
21648 (goto-char start)
21649 ;; @r{Move point forward by value of} full-Y-label-width
21650 (forward-char full-Y-label-width)))
21651 @end group
21652 @end smallexample
21653
21654 @smallexample
21655 @group
21656 (defun print-X-axis-tic-line
21657 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
21658 "Print ticks for X axis."
21659 (insert X-axis-leading-spaces)
21660 (insert X-axis-tic-symbol) ; @r{Under first column.}
21661 @end group
21662 @group
21663 ;; @r{Insert second tic in the right spot.}
21664 (insert (concat
21665 (make-string
21666 (- (* symbol-width X-axis-label-spacing)
21667 ;; @r{Insert white space up to second tic symbol.}
21668 (* 2 (length X-axis-tic-symbol)))
21669 ? )
21670 X-axis-tic-symbol))
21671 @end group
21672 @group
21673 ;; @r{Insert remaining ticks.}
21674 (while (> number-of-X-tics 1)
21675 (insert X-axis-tic-element)
21676 (setq number-of-X-tics (1- number-of-X-tics))))
21677 @end group
21678 @end smallexample
21679
21680 @smallexample
21681 @group
21682 (defun X-axis-element (number)
21683 "Construct a numbered X axis element."
21684 (let ((leading-spaces
21685 (- (* symbol-width X-axis-label-spacing)
21686 (length (number-to-string number)))))
21687 (concat (make-string leading-spaces ? )
21688 (number-to-string number))))
21689 @end group
21690 @end smallexample
21691
21692 @smallexample
21693 @group
21694 (defun graph-body-print (numbers-list height symbol-width)
21695 "Print a bar graph of the NUMBERS-LIST.
21696 The numbers-list consists of the Y-axis values.
21697 HEIGHT is maximum height of graph.
21698 SYMBOL-WIDTH is number of each column."
21699 @end group
21700 @group
21701 (let (from-position)
21702 (while numbers-list
21703 (setq from-position (point))
21704 (insert-rectangle
21705 (column-of-graph height (car numbers-list)))
21706 (goto-char from-position)
21707 (forward-char symbol-width)
21708 @end group
21709 @group
21710 ;; @r{Draw graph column by column.}
21711 (sit-for 0)
21712 (setq numbers-list (cdr numbers-list)))
21713 ;; @r{Place point for X axis labels.}
21714 (forward-line height)
21715 (insert "\n")))
21716 @end group
21717 @end smallexample
21718
21719 @smallexample
21720 @group
21721 (defun Y-axis-column
21722 (height width-of-label &optional vertical-step)
21723 "Construct list of labels for Y axis.
21724 HEIGHT is maximum height of graph.
21725 WIDTH-OF-LABEL is maximum width of label.
21726 @end group
21727 @group
21728 VERTICAL-STEP, an option, is a positive integer
21729 that specifies how much a Y axis label increments
21730 for each line. For example, a step of 5 means
21731 that each line is five units of the graph."
21732 (let (Y-axis
21733 (number-per-line (or vertical-step 1)))
21734 @end group
21735 @group
21736 (while (> height 1)
21737 (if (zerop (% height Y-axis-label-spacing))
21738 ;; @r{Insert label.}
21739 (setq Y-axis
21740 (cons
21741 (Y-axis-element
21742 (* height number-per-line)
21743 width-of-label)
21744 Y-axis))
21745 @end group
21746 @group
21747 ;; @r{Else, insert blanks.}
21748 (setq Y-axis
21749 (cons
21750 (make-string width-of-label ? )
21751 Y-axis)))
21752 (setq height (1- height)))
21753 @end group
21754 @group
21755 ;; @r{Insert base line.}
21756 (setq Y-axis (cons (Y-axis-element
21757 (or vertical-step 1)
21758 width-of-label)
21759 Y-axis))
21760 (nreverse Y-axis)))
21761 @end group
21762 @end smallexample
21763
21764 @smallexample
21765 @group
21766 (defun print-X-axis-numbered-line
21767 (number-of-X-tics X-axis-leading-spaces
21768 &optional horizontal-step)
21769 "Print line of X-axis numbers"
21770 (let ((number X-axis-label-spacing)
21771 (horizontal-step (or horizontal-step 1)))
21772 @end group
21773 @group
21774 (insert X-axis-leading-spaces)
21775 ;; line up number
21776 (delete-char (- (1- (length (number-to-string horizontal-step)))))
21777 (insert (concat
21778 (make-string
21779 ;; @r{Insert white space up to next number.}
21780 (- (* symbol-width X-axis-label-spacing)
21781 (1- (length (number-to-string horizontal-step)))
21782 2)
21783 ? )
21784 (number-to-string (* number horizontal-step))))
21785 @end group
21786 @group
21787 ;; @r{Insert remaining numbers.}
21788 (setq number (+ number X-axis-label-spacing))
21789 (while (> number-of-X-tics 1)
21790 (insert (X-axis-element (* number horizontal-step)))
21791 (setq number (+ number X-axis-label-spacing))
21792 (setq number-of-X-tics (1- number-of-X-tics)))))
21793 @end group
21794 @end smallexample
21795
21796 @smallexample
21797 @group
21798 (defun print-X-axis (numbers-list horizontal-step)
21799 "Print X axis labels to length of NUMBERS-LIST.
21800 Optionally, HORIZONTAL-STEP, a positive integer,
21801 specifies how much an X axis label increments for
21802 each column."
21803 @end group
21804 @group
21805 ;; Value of symbol-width and full-Y-label-width
21806 ;; are passed by `print-graph'.
21807 (let* ((leading-spaces
21808 (make-string full-Y-label-width ? ))
21809 ;; symbol-width @r{is provided by} graph-body-print
21810 (tic-width (* symbol-width X-axis-label-spacing))
21811 (X-length (length numbers-list))
21812 @end group
21813 @group
21814 (X-tic
21815 (concat
21816 (make-string
21817 ;; @r{Make a string of blanks.}
21818 (- (* symbol-width X-axis-label-spacing)
21819 (length X-axis-tic-symbol))
21820 ? )
21821 @end group
21822 @group
21823 ;; @r{Concatenate blanks with tic symbol.}
21824 X-axis-tic-symbol))
21825 (tic-number
21826 (if (zerop (% X-length tic-width))
21827 (/ X-length tic-width)
21828 (1+ (/ X-length tic-width)))))
21829 @end group
21830
21831 @group
21832 (print-X-axis-tic-line
21833 tic-number leading-spaces X-tic)
21834 (insert "\n")
21835 (print-X-axis-numbered-line
21836 tic-number leading-spaces horizontal-step)))
21837 @end group
21838 @end smallexample
21839
21840 @smallexample
21841 @group
21842 (defun one-fiftieth (full-range)
21843 "Return list, each number of which is 1/50th previous."
21844 (mapcar (lambda (arg) (/ arg 50)) full-range))
21845 @end group
21846 @end smallexample
21847
21848 @smallexample
21849 @group
21850 (defun print-graph
21851 (numbers-list &optional vertical-step horizontal-step)
21852 "Print labeled bar graph of the NUMBERS-LIST.
21853 The numbers-list consists of the Y-axis values.
21854 @end group
21855
21856 @group
21857 Optionally, VERTICAL-STEP, a positive integer,
21858 specifies how much a Y axis label increments for
21859 each line. For example, a step of 5 means that
21860 each row is five units.
21861 @end group
21862
21863 @group
21864 Optionally, HORIZONTAL-STEP, a positive integer,
21865 specifies how much an X axis label increments for
21866 each column."
21867 (let* ((symbol-width (length graph-blank))
21868 ;; @code{height} @r{is both the largest number}
21869 ;; @r{and the number with the most digits.}
21870 (height (apply 'max numbers-list))
21871 @end group
21872 @group
21873 (height-of-top-line
21874 (if (zerop (% height Y-axis-label-spacing))
21875 height
21876 ;; @r{else}
21877 (* (1+ (/ height Y-axis-label-spacing))
21878 Y-axis-label-spacing)))
21879 @end group
21880 @group
21881 (vertical-step (or vertical-step 1))
21882 (full-Y-label-width
21883 (length
21884 (concat
21885 (number-to-string
21886 (* height-of-top-line vertical-step))
21887 Y-axis-tic))))
21888 @end group
21889 @group
21890
21891 (print-Y-axis
21892 height-of-top-line full-Y-label-width vertical-step)
21893 (graph-body-print
21894 numbers-list height-of-top-line symbol-width)
21895 (print-X-axis numbers-list horizontal-step)))
21896 @end group
21897 @end smallexample
21898 @c qqq
21899 @end ignore
21900
21901 @page
21902 @node Final printed graph
21903 @appendixsubsec The Printed Graph
21904
21905 When made and installed, you can call the @code{print-graph} command
21906 like this:
21907 @sp 1
21908
21909 @smallexample
21910 @group
21911 (print-graph fiftieth-list-for-graph 50 10)
21912 @end group
21913 @end smallexample
21914 @sp 1
21915
21916 @noindent
21917 Here is the graph:
21918 @sp 2
21919
21920 @smallexample
21921 @group
21922 1000 - *
21923 **
21924 **
21925 **
21926 **
21927 750 - ***
21928 ***
21929 ***
21930 ***
21931 ****
21932 500 - *****
21933 ******
21934 ******
21935 ******
21936 *******
21937 250 - ********
21938 ********* *
21939 *********** *
21940 ************* *
21941 50 - ***************** * *
21942 | | | | | | | |
21943 10 50 100 150 200 250 300 350
21944 @end group
21945 @end smallexample
21946
21947 @sp 2
21948
21949 @noindent
21950 The largest group of functions contain 10--19 words and symbols each.
21951
21952 @node Free Software and Free Manuals
21953 @appendix Free Software and Free Manuals
21954
21955 @strong{by Richard M. Stallman}
21956 @sp 1
21957
21958 The biggest deficiency in free operating systems is not in the
21959 software---it is the lack of good free manuals that we can include in
21960 these systems. Many of our most important programs do not come with
21961 full manuals. Documentation is an essential part of any software
21962 package; when an important free software package does not come with a
21963 free manual, that is a major gap. We have many such gaps today.
21964
21965 Once upon a time, many years ago, I thought I would learn Perl. I got
21966 a copy of a free manual, but I found it hard to read. When I asked
21967 Perl users about alternatives, they told me that there were better
21968 introductory manuals---but those were not free.
21969
21970 Why was this? The authors of the good manuals had written them for
21971 O'Reilly Associates, which published them with restrictive terms---no
21972 copying, no modification, source files not available---which exclude
21973 them from the free software community.
21974
21975 That wasn't the first time this sort of thing has happened, and (to
21976 our community's great loss) it was far from the last. Proprietary
21977 manual publishers have enticed a great many authors to restrict their
21978 manuals since then. Many times I have heard a GNU user eagerly tell me
21979 about a manual that he is writing, with which he expects to help the
21980 GNU project---and then had my hopes dashed, as he proceeded to explain
21981 that he had signed a contract with a publisher that would restrict it
21982 so that we cannot use it.
21983
21984 Given that writing good English is a rare skill among programmers, we
21985 can ill afford to lose manuals this way.
21986
21987 Free documentation, like free software, is a matter of freedom, not
21988 price. The problem with these manuals was not that O'Reilly Associates
21989 charged a price for printed copies---that in itself is fine. The Free
21990 Software Foundation @uref{http://shop.fsf.org, sells printed copies} of
21991 free @uref{http://www.gnu.org/doc/doc.html, GNU manuals}, too.
21992 But GNU manuals are available in source code form, while these manuals
21993 are available only on paper. GNU manuals come with permission to copy
21994 and modify; the Perl manuals do not. These restrictions are the
21995 problems.
21996
21997 The criterion for a free manual is pretty much the same as for free
21998 software: it is a matter of giving all users certain
21999 freedoms. Redistribution (including commercial redistribution) must be
22000 permitted, so that the manual can accompany every copy of the program,
22001 on-line or on paper. Permission for modification is crucial too.
22002
22003 As a general rule, I don't believe that it is essential for people to
22004 have permission to modify all sorts of articles and books. The issues
22005 for writings are not necessarily the same as those for software. For
22006 example, I don't think you or I are obliged to give permission to
22007 modify articles like this one, which describe our actions and our
22008 views.
22009
22010 But there is a particular reason why the freedom to modify is crucial
22011 for documentation for free software. When people exercise their right
22012 to modify the software, and add or change its features, if they are
22013 conscientious they will change the manual too---so they can provide
22014 accurate and usable documentation with the modified program. A manual
22015 which forbids programmers to be conscientious and finish the job, or
22016 more precisely requires them to write a new manual from scratch if
22017 they change the program, does not fill our community's needs.
22018
22019 While a blanket prohibition on modification is unacceptable, some
22020 kinds of limits on the method of modification pose no problem. For
22021 example, requirements to preserve the original author's copyright
22022 notice, the distribution terms, or the list of authors, are ok. It is
22023 also no problem to require modified versions to include notice that
22024 they were modified, even to have entire sections that may not be
22025 deleted or changed, as long as these sections deal with nontechnical
22026 topics. (Some GNU manuals have them.)
22027
22028 These kinds of restrictions are not a problem because, as a practical
22029 matter, they don't stop the conscientious programmer from adapting the
22030 manual to fit the modified program. In other words, they don't block
22031 the free software community from making full use of the manual.
22032
22033 However, it must be possible to modify all the technical content of
22034 the manual, and then distribute the result in all the usual media,
22035 through all the usual channels; otherwise, the restrictions do block
22036 the community, the manual is not free, and so we need another manual.
22037
22038 Unfortunately, it is often hard to find someone to write another
22039 manual when a proprietary manual exists. The obstacle is that many
22040 users think that a proprietary manual is good enough---so they don't
22041 see the need to write a free manual. They do not see that the free
22042 operating system has a gap that needs filling.
22043
22044 Why do users think that proprietary manuals are good enough? Some have
22045 not considered the issue. I hope this article will do something to
22046 change that.
22047
22048 Other users consider proprietary manuals acceptable for the same
22049 reason so many people consider proprietary software acceptable: they
22050 judge in purely practical terms, not using freedom as a
22051 criterion. These people are entitled to their opinions, but since
22052 those opinions spring from values which do not include freedom, they
22053 are no guide for those of us who do value freedom.
22054
22055 Please spread the word about this issue. We continue to lose manuals
22056 to proprietary publishing. If we spread the word that proprietary
22057 manuals are not sufficient, perhaps the next person who wants to help
22058 GNU by writing documentation will realize, before it is too late, that
22059 he must above all make it free.
22060
22061 We can also encourage commercial publishers to sell free, copylefted
22062 manuals instead of proprietary ones. One way you can help this is to
22063 check the distribution terms of a manual before you buy it, and prefer
22064 copylefted manuals to non-copylefted ones.
22065
22066 @sp 2
22067 @noindent
22068 Note: The Free Software Foundation maintains a page on its Web site
22069 that lists free books available from other publishers:@*
22070 @uref{http://www.gnu.org/doc/other-free-books.html}
22071
22072 @node GNU Free Documentation License
22073 @appendix GNU Free Documentation License
22074
22075 @cindex FDL, GNU Free Documentation License
22076 @include doclicense.texi
22077
22078 @node Index
22079 @unnumbered Index
22080
22081 @ignore
22082 MENU ENTRY: NODE NAME.
22083 @end ignore
22084
22085 @printindex cp
22086
22087 @iftex
22088 @c Place biographical information on right-hand (verso) page
22089
22090 @tex
22091 \par\vfill\supereject
22092 \ifodd\pageno
22093 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22094 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
22095 %\page\hbox{}\page
22096 \else
22097 % \par\vfill\supereject
22098 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22099 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
22100 %\page\hbox{}%\page
22101 %\page\hbox{}%\page
22102 \fi
22103 @end tex
22104
22105 @c page
22106 @w{ }
22107
22108 @c ================ Biographical information ================
22109
22110 @w{ }
22111 @sp 8
22112 @center About the Author
22113 @sp 1
22114 @end iftex
22115
22116 @ifnottex
22117 @node About the Author
22118 @unnumbered About the Author
22119 @end ifnottex
22120
22121 @quotation
22122 Robert J. Chassell has worked with GNU Emacs since 1985. He writes
22123 and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
22124 world on software freedom. Chassell was a founding Director and
22125 Treasurer of the Free Software Foundation, Inc. He is co-author of
22126 the @cite{Texinfo} manual, and has edited more than a dozen other
22127 books. He graduated from Cambridge University, in England. He has an
22128 abiding interest in social and economic history and flies his own
22129 airplane.
22130 @end quotation
22131
22132 @c @page
22133 @c @w{ }
22134 @c
22135 @c @c Prevent page number on blank verso, so eject it first.
22136 @c @tex
22137 @c \par\vfill\supereject
22138 @c @end tex
22139
22140 @c @iftex
22141 @c @headings off
22142 @c @evenheading @thispage @| @| @thistitle
22143 @c @oddheading @| @| @thispage
22144 @c @end iftex
22145
22146 @bye