* emacs-lisp-intro.texi (defcustom): Fix typo.
[bpt/emacs.git] / 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 @item 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 24 in src/editfns.c
9120 @c the DEFUN for delete-and-extract-region
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 ("delete-and-extract-region", Fdelete_and_extract_region,
9131 Sdelete_and_extract_region, 2, 2, 0,
9132 doc: /* Delete the text between START and END and return it. */)
9133 (Lisp_Object start, Lisp_Object end)
9134 @{
9135 validate_region (&start, &end);
9136 if (XINT (start) == XINT (end))
9137 return empty_unibyte_string;
9138 return del_range_1 (XINT (start), XINT (end), 1, 1);
9139 @}
9140 @end group
9141 @end smallexample
9142
9143 Without going into the details of the macro writing process, let me
9144 point out that this macro starts with the word @code{DEFUN}. The word
9145 @code{DEFUN} was chosen since the code serves the same purpose as
9146 @code{defun} does in Lisp. (The @code{DEFUN} C macro is defined in
9147 @file{emacs/src/lisp.h}.)
9148
9149 The word @code{DEFUN} is followed by seven parts inside of
9150 parentheses:
9151
9152 @itemize @bullet
9153 @item
9154 The first part is the name given to the function in Lisp,
9155 @code{delete-and-extract-region}.
9156
9157 @item
9158 The second part is the name of the function in C,
9159 @code{Fdelete_and_extract_region}. By convention, it starts with
9160 @samp{F}. Since C does not use hyphens in names, underscores are used
9161 instead.
9162
9163 @item
9164 The third part is the name for the C constant structure that records
9165 information on this function for internal use. It is the name of the
9166 function in C but begins with an @samp{S} instead of an @samp{F}.
9167
9168 @item
9169 The fourth and fifth parts specify the minimum and maximum number of
9170 arguments the function can have. This function demands exactly 2
9171 arguments.
9172
9173 @item
9174 The sixth part is nearly like the argument that follows the
9175 @code{interactive} declaration in a function written in Lisp: a letter
9176 followed, perhaps, by a prompt. The only difference from the Lisp is
9177 when the macro is called with no arguments. Then you write a @code{0}
9178 (which is a `null string'), as in this macro.
9179
9180 If you were to specify arguments, you would place them between
9181 quotation marks. The C macro for @code{goto-char} includes
9182 @code{"NGoto char: "} in this position to indicate that the function
9183 expects a raw prefix, in this case, a numerical location in a buffer,
9184 and provides a prompt.
9185
9186 @item
9187 The seventh part is a documentation string, just like the one for a
9188 function written in Emacs Lisp. This is written as a C comment. (When
9189 you build Emacs, the program @command{lib-src/make-docfile} extracts
9190 these comments and uses them to make the ``real'' documentation.)
9191 @end itemize
9192
9193 @need 1200
9194 In a C macro, the formal parameters come next, with a statement of
9195 what kind of object they are, followed by what might be called the `body'
9196 of the macro. For @code{delete-and-extract-region} the `body'
9197 consists of the following four lines:
9198
9199 @smallexample
9200 @group
9201 validate_region (&start, &end);
9202 if (XINT (start) == XINT (end))
9203 return empty_unibyte_string;
9204 return del_range_1 (XINT (start), XINT (end), 1, 1);
9205 @end group
9206 @end smallexample
9207
9208 The @code{validate_region} function checks whether the values
9209 passed as the beginning and end of the region are the proper type and
9210 are within range. If the beginning and end positions are the same,
9211 then return an empty string.
9212
9213 The @code{del_range_1} function actually deletes the text. It is a
9214 complex function we will not look into. It updates the buffer and
9215 does other things. However, it is worth looking at the two arguments
9216 passed to @code{del_range}. These are @w{@code{XINT (start)}} and
9217 @w{@code{XINT (end)}}.
9218
9219 As far as the C language is concerned, @code{start} and @code{end} are
9220 two integers that mark the beginning and end of the region to be
9221 deleted@footnote{More precisely, and requiring more expert knowledge
9222 to understand, the two integers are of type `Lisp_Object', which can
9223 also be a C union instead of an integer type.}.
9224
9225 In early versions of Emacs, these two numbers were thirty-two bits
9226 long, but the code is slowly being generalized to handle other
9227 lengths. Three of the available bits are used to specify the type of
9228 information; the remaining bits are used as `content'.
9229
9230 @samp{XINT} is a C macro that extracts the relevant number from the
9231 longer collection of bits; the three other bits are discarded.
9232
9233 @need 800
9234 The command in @code{delete-and-extract-region} looks like this:
9235
9236 @smallexample
9237 del_range_1 (XINT (start), XINT (end), 1, 1);
9238 @end smallexample
9239
9240 @noindent
9241 It deletes the region between the beginning position, @code{start},
9242 and the ending position, @code{end}.
9243
9244 From the point of view of the person writing Lisp, Emacs is all very
9245 simple; but hidden underneath is a great deal of complexity to make it
9246 all work.
9247
9248 @node defvar
9249 @section Initializing a Variable with @code{defvar}
9250 @findex defvar
9251 @cindex Initializing a variable
9252 @cindex Variable initialization
9253
9254 @ignore
9255 2006 Oct 24
9256 In Emacs 22,
9257 copy-region-as-kill is short, 12 lines, and uses
9258 filter-buffer-substring, which is longer, 39 lines
9259 and has delete-and-extract-region in it.
9260 delete-and-extract-region is written in C.
9261
9262 see Initializing a Variable with @code{defvar}
9263
9264 @end ignore
9265
9266 The @code{copy-region-as-kill} function is written in Emacs Lisp. Two
9267 functions within it, @code{kill-append} and @code{kill-new}, copy a
9268 region in a buffer and save it in a variable called the
9269 @code{kill-ring}. This section describes how the @code{kill-ring}
9270 variable is created and initialized using the @code{defvar} special
9271 form.
9272
9273 (Again we note that the term @code{kill-ring} is a misnomer. The text
9274 that is clipped out of the buffer can be brought back; it is not a ring
9275 of corpses, but a ring of resurrectable text.)
9276
9277 In Emacs Lisp, a variable such as the @code{kill-ring} is created and
9278 given an initial value by using the @code{defvar} special form. The
9279 name comes from ``define variable''.
9280
9281 The @code{defvar} special form is similar to @code{setq} in that it sets
9282 the value of a variable. It is unlike @code{setq} in two ways: first,
9283 it only sets the value of the variable if the variable does not already
9284 have a value. If the variable already has a value, @code{defvar} does
9285 not override the existing value. Second, @code{defvar} has a
9286 documentation string.
9287
9288 (Another special form, @code{defcustom}, is designed for variables
9289 that people customize. It has more features than @code{defvar}.
9290 (@xref{defcustom, , Setting Variables with @code{defcustom}}.)
9291
9292 @menu
9293 * See variable current value::
9294 * defvar and asterisk::
9295 @end menu
9296
9297 @ifnottex
9298 @node See variable current value
9299 @unnumberedsubsec Seeing the Current Value of a Variable
9300 @end ifnottex
9301
9302 You can see the current value of a variable, any variable, by using
9303 the @code{describe-variable} function, which is usually invoked by
9304 typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
9305 (followed by @key{RET}) when prompted, you will see what is in your
9306 current kill ring---this may be quite a lot! Conversely, if you have
9307 been doing nothing this Emacs session except read this document, you
9308 may have nothing in it. Also, you will see the documentation for
9309 @code{kill-ring}:
9310
9311 @smallexample
9312 @group
9313 Documentation:
9314 List of killed text sequences.
9315 Since the kill ring is supposed to interact nicely with cut-and-paste
9316 facilities offered by window systems, use of this variable should
9317 @end group
9318 @group
9319 interact nicely with `interprogram-cut-function' and
9320 `interprogram-paste-function'. The functions `kill-new',
9321 `kill-append', and `current-kill' are supposed to implement this
9322 interaction; you may want to use them instead of manipulating the kill
9323 ring directly.
9324 @end group
9325 @end smallexample
9326
9327 @need 800
9328 The kill ring is defined by a @code{defvar} in the following way:
9329
9330 @smallexample
9331 @group
9332 (defvar kill-ring nil
9333 "List of killed text sequences.
9334 @dots{}")
9335 @end group
9336 @end smallexample
9337
9338 @noindent
9339 In this variable definition, the variable is given an initial value of
9340 @code{nil}, which makes sense, since if you have saved nothing, you want
9341 nothing back if you give a @code{yank} command. The documentation
9342 string is written just like the documentation string of a @code{defun}.
9343 As with the documentation string of the @code{defun}, the first line of
9344 the documentation should be a complete sentence, since some commands,
9345 like @code{apropos}, print only the first line of documentation.
9346 Succeeding lines should not be indented; otherwise they look odd when
9347 you use @kbd{C-h v} (@code{describe-variable}).
9348
9349 @node defvar and asterisk
9350 @subsection @code{defvar} and an asterisk
9351 @findex defvar @r{for a user customizable variable}
9352 @findex defvar @r{with an asterisk}
9353
9354 In the past, Emacs used the @code{defvar} special form both for
9355 internal variables that you would not expect a user to change and for
9356 variables that you do expect a user to change. Although you can still
9357 use @code{defvar} for user customizable variables, please use
9358 @code{defcustom} instead, since that special form provides a path into
9359 the Customization commands. (@xref{defcustom, , Specifying Variables
9360 using @code{defcustom}}.)
9361
9362 When you specified a variable using the @code{defvar} special form,
9363 you could distinguish a variable that a user might want to change from
9364 others by typing an asterisk, @samp{*}, in the first column of its
9365 documentation string. For example:
9366
9367 @smallexample
9368 @group
9369 (defvar shell-command-default-error-buffer nil
9370 "*Buffer name for `shell-command' @dots{} error output.
9371 @dots{} ")
9372 @end group
9373 @end smallexample
9374
9375 @findex set-variable
9376 @noindent
9377 You could (and still can) use the @code{set-variable} command to
9378 change the value of @code{shell-command-default-error-buffer}
9379 temporarily. However, options set using @code{set-variable} are set
9380 only for the duration of your editing session. The new values are not
9381 saved between sessions. Each time Emacs starts, it reads the original
9382 value, unless you change the value within your @file{.emacs} file,
9383 either by setting it manually or by using @code{customize}.
9384 @xref{Emacs Initialization, , Your @file{.emacs} File}.
9385
9386 For me, the major use of the @code{set-variable} command is to suggest
9387 variables that I might want to set in my @file{.emacs} file. There
9388 are now more than 700 such variables, far too many to remember
9389 readily. Fortunately, you can press @key{TAB} after calling the
9390 @code{M-x set-variable} command to see the list of variables.
9391 (@xref{Examining, , Examining and Setting Variables, emacs,
9392 The GNU Emacs Manual}.)
9393
9394 @need 1250
9395 @node cons & search-fwd Review
9396 @section Review
9397
9398 Here is a brief summary of some recently introduced functions.
9399
9400 @table @code
9401 @item car
9402 @itemx cdr
9403 @code{car} returns the first element of a list; @code{cdr} returns the
9404 second and subsequent elements of a list.
9405
9406 @need 1250
9407 For example:
9408
9409 @smallexample
9410 @group
9411 (car '(1 2 3 4 5 6 7))
9412 @result{} 1
9413 (cdr '(1 2 3 4 5 6 7))
9414 @result{} (2 3 4 5 6 7)
9415 @end group
9416 @end smallexample
9417
9418 @item cons
9419 @code{cons} constructs a list by prepending its first argument to its
9420 second argument.
9421
9422 @need 1250
9423 For example:
9424
9425 @smallexample
9426 @group
9427 (cons 1 '(2 3 4))
9428 @result{} (1 2 3 4)
9429 @end group
9430 @end smallexample
9431
9432 @item funcall
9433 @code{funcall} evaluates its first argument as a function. It passes
9434 its remaining arguments to its first argument.
9435
9436 @item nthcdr
9437 Return the result of taking @sc{cdr} `n' times on a list.
9438 @iftex
9439 The
9440 @tex
9441 $n^{th}$
9442 @end tex
9443 @code{cdr}.
9444 @end iftex
9445 The `rest of the rest', as it were.
9446
9447 @need 1250
9448 For example:
9449
9450 @smallexample
9451 @group
9452 (nthcdr 3 '(1 2 3 4 5 6 7))
9453 @result{} (4 5 6 7)
9454 @end group
9455 @end smallexample
9456
9457 @item setcar
9458 @itemx setcdr
9459 @code{setcar} changes the first element of a list; @code{setcdr}
9460 changes the second and subsequent elements of a list.
9461
9462 @need 1250
9463 For example:
9464
9465 @smallexample
9466 @group
9467 (setq triple '(1 2 3))
9468
9469 (setcar triple '37)
9470
9471 triple
9472 @result{} (37 2 3)
9473
9474 (setcdr triple '("foo" "bar"))
9475
9476 triple
9477 @result{} (37 "foo" "bar")
9478 @end group
9479 @end smallexample
9480
9481 @item progn
9482 Evaluate each argument in sequence and then return the value of the
9483 last.
9484
9485 @need 1250
9486 For example:
9487
9488 @smallexample
9489 @group
9490 (progn 1 2 3 4)
9491 @result{} 4
9492 @end group
9493 @end smallexample
9494
9495 @item save-restriction
9496 Record whatever narrowing is in effect in the current buffer, if any,
9497 and restore that narrowing after evaluating the arguments.
9498
9499 @item search-forward
9500 Search for a string, and if the string is found, move point. With a
9501 regular expression, use the similar @code{re-search-forward}.
9502 (@xref{Regexp Search, , Regular Expression Searches}, for an
9503 explanation of regular expression patterns and searches.)
9504
9505 @need 1250
9506 @noindent
9507 @code{search-forward} and @code{re-search-forward} take four
9508 arguments:
9509
9510 @enumerate
9511 @item
9512 The string or regular expression to search for.
9513
9514 @item
9515 Optionally, the limit of the search.
9516
9517 @item
9518 Optionally, what to do if the search fails, return @code{nil} or an
9519 error message.
9520
9521 @item
9522 Optionally, how many times to repeat the search; if negative, the
9523 search goes backwards.
9524 @end enumerate
9525
9526 @item kill-region
9527 @itemx delete-and-extract-region
9528 @itemx copy-region-as-kill
9529
9530 @code{kill-region} cuts the text between point and mark from the
9531 buffer and stores that text in the kill ring, so you can get it back
9532 by yanking.
9533
9534 @code{copy-region-as-kill} copies the text between point and mark into
9535 the kill ring, from which you can get it by yanking. The function
9536 does not cut or remove the text from the buffer.
9537 @end table
9538
9539 @code{delete-and-extract-region} removes the text between point and
9540 mark from the buffer and throws it away. You cannot get it back.
9541 (This is not an interactive command.)
9542
9543 @need 1500
9544 @node search Exercises
9545 @section Searching Exercises
9546
9547 @itemize @bullet
9548 @item
9549 Write an interactive function that searches for a string. If the
9550 search finds the string, leave point after it and display a message
9551 that says ``Found!''. (Do not use @code{search-forward} for the name
9552 of this function; if you do, you will overwrite the existing version of
9553 @code{search-forward} that comes with Emacs. Use a name such as
9554 @code{test-search} instead.)
9555
9556 @item
9557 Write a function that prints the third element of the kill ring in the
9558 echo area, if any; if the kill ring does not contain a third element,
9559 print an appropriate message.
9560 @end itemize
9561
9562 @node List Implementation
9563 @chapter How Lists are Implemented
9564 @cindex Lists in a computer
9565
9566 In Lisp, atoms are recorded in a straightforward fashion; if the
9567 implementation is not straightforward in practice, it is, nonetheless,
9568 straightforward in theory. The atom @samp{rose}, for example, is
9569 recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
9570 @samp{e}. A list, on the other hand, is kept differently. The mechanism
9571 is equally simple, but it takes a moment to get used to the idea. A
9572 list is kept using a series of pairs of pointers. In the series, the
9573 first pointer in each pair points to an atom or to another list, and the
9574 second pointer in each pair points to the next pair, or to the symbol
9575 @code{nil}, which marks the end of the list.
9576
9577 A pointer itself is quite simply the electronic address of what is
9578 pointed to. Hence, a list is kept as a series of electronic addresses.
9579
9580 @menu
9581 * Lists diagrammed::
9582 * Symbols as Chest:: Exploring a powerful metaphor.
9583 * List Exercise::
9584 @end menu
9585
9586 @ifnottex
9587 @node Lists diagrammed
9588 @unnumberedsec Lists diagrammed
9589 @end ifnottex
9590
9591 For example, the list @code{(rose violet buttercup)} has three elements,
9592 @samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
9593 electronic address of @samp{rose} is recorded in a segment of computer
9594 memory along with the address that gives the electronic address of where
9595 the atom @samp{violet} is located; and that address (the one that tells
9596 where @samp{violet} is located) is kept along with an address that tells
9597 where the address for the atom @samp{buttercup} is located.
9598
9599 @need 1200
9600 This sounds more complicated than it is and is easier seen in a diagram:
9601
9602 @c clear print-postscript-figures
9603 @c !!! cons-cell-diagram #1
9604 @ifnottex
9605 @smallexample
9606 @group
9607 ___ ___ ___ ___ ___ ___
9608 |___|___|--> |___|___|--> |___|___|--> nil
9609 | | |
9610 | | |
9611 --> rose --> violet --> buttercup
9612 @end group
9613 @end smallexample
9614 @end ifnottex
9615 @ifset print-postscript-figures
9616 @sp 1
9617 @tex
9618 @center @image{cons-1}
9619 %%%% old method of including an image
9620 % \input /usr/local/lib/tex/inputs/psfig.tex
9621 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
9622 % \catcode`\@=0 %
9623 @end tex
9624 @sp 1
9625 @end ifset
9626 @ifclear print-postscript-figures
9627 @iftex
9628 @smallexample
9629 @group
9630 ___ ___ ___ ___ ___ ___
9631 |___|___|--> |___|___|--> |___|___|--> nil
9632 | | |
9633 | | |
9634 --> rose --> violet --> buttercup
9635 @end group
9636 @end smallexample
9637 @end iftex
9638 @end ifclear
9639
9640 @noindent
9641 In the diagram, each box represents a word of computer memory that
9642 holds a Lisp object, usually in the form of a memory address. The boxes,
9643 i.e., the addresses, are in pairs. Each arrow points to what the address
9644 is the address of, either an atom or another pair of addresses. The
9645 first box is the electronic address of @samp{rose} and the arrow points
9646 to @samp{rose}; the second box is the address of the next pair of boxes,
9647 the first part of which is the address of @samp{violet} and the second
9648 part of which is the address of the next pair. The very last box
9649 points to the symbol @code{nil}, which marks the end of the list.
9650
9651 @need 1200
9652 When a variable is set to a list with a function such as @code{setq},
9653 it stores the address of the first box in the variable. Thus,
9654 evaluation of the expression
9655
9656 @smallexample
9657 (setq bouquet '(rose violet buttercup))
9658 @end smallexample
9659
9660 @need 1250
9661 @noindent
9662 creates a situation like this:
9663
9664 @c cons-cell-diagram #2
9665 @ifnottex
9666 @smallexample
9667 @group
9668 bouquet
9669 |
9670 | ___ ___ ___ ___ ___ ___
9671 --> |___|___|--> |___|___|--> |___|___|--> nil
9672 | | |
9673 | | |
9674 --> rose --> violet --> buttercup
9675 @end group
9676 @end smallexample
9677 @end ifnottex
9678 @ifset print-postscript-figures
9679 @sp 1
9680 @tex
9681 @center @image{cons-2}
9682 %%%% old method of including an image
9683 % \input /usr/local/lib/tex/inputs/psfig.tex
9684 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
9685 % \catcode`\@=0 %
9686 @end tex
9687 @sp 1
9688 @end ifset
9689 @ifclear print-postscript-figures
9690 @iftex
9691 @smallexample
9692 @group
9693 bouquet
9694 |
9695 | ___ ___ ___ ___ ___ ___
9696 --> |___|___|--> |___|___|--> |___|___|--> nil
9697 | | |
9698 | | |
9699 --> rose --> violet --> buttercup
9700 @end group
9701 @end smallexample
9702 @end iftex
9703 @end ifclear
9704
9705 @noindent
9706 In this example, the symbol @code{bouquet} holds the address of the first
9707 pair of boxes.
9708
9709 @need 1200
9710 This same list can be illustrated in a different sort of box notation
9711 like this:
9712
9713 @c cons-cell-diagram #2a
9714 @ifnottex
9715 @smallexample
9716 @group
9717 bouquet
9718 |
9719 | -------------- --------------- ----------------
9720 | | car | cdr | | car | cdr | | car | cdr |
9721 -->| rose | o------->| violet | o------->| butter- | nil |
9722 | | | | | | | cup | |
9723 -------------- --------------- ----------------
9724 @end group
9725 @end smallexample
9726 @end ifnottex
9727 @ifset print-postscript-figures
9728 @sp 1
9729 @tex
9730 @center @image{cons-2a}
9731 %%%% old method of including an image
9732 % \input /usr/local/lib/tex/inputs/psfig.tex
9733 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9734 % \catcode`\@=0 %
9735 @end tex
9736 @sp 1
9737 @end ifset
9738 @ifclear print-postscript-figures
9739 @iftex
9740 @smallexample
9741 @group
9742 bouquet
9743 |
9744 | -------------- --------------- ----------------
9745 | | car | cdr | | car | cdr | | car | cdr |
9746 -->| rose | o------->| violet | o------->| butter- | nil |
9747 | | | | | | | cup | |
9748 -------------- --------------- ----------------
9749 @end group
9750 @end smallexample
9751 @end iftex
9752 @end ifclear
9753
9754 (Symbols consist of more than pairs of addresses, but the structure of
9755 a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9756 consists of a group of address-boxes, one of which is the address of
9757 the printed word @samp{bouquet}, a second of which is the address of a
9758 function definition attached to the symbol, if any, a third of which
9759 is the address of the first pair of address-boxes for the list
9760 @code{(rose violet buttercup)}, and so on. Here we are showing that
9761 the symbol's third address-box points to the first pair of
9762 address-boxes for the list.)
9763
9764 If a symbol is set to the @sc{cdr} of a list, the list itself is not
9765 changed; the symbol simply has an address further down the list. (In
9766 the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9767 evaluation of the following expression
9768
9769 @smallexample
9770 (setq flowers (cdr bouquet))
9771 @end smallexample
9772
9773 @need 800
9774 @noindent
9775 produces this:
9776
9777 @c cons-cell-diagram #3
9778 @ifnottex
9779 @sp 1
9780 @smallexample
9781 @group
9782 bouquet flowers
9783 | |
9784 | ___ ___ | ___ ___ ___ ___
9785 --> | | | --> | | | | | |
9786 |___|___|----> |___|___|--> |___|___|--> nil
9787 | | |
9788 | | |
9789 --> rose --> violet --> buttercup
9790 @end group
9791 @end smallexample
9792 @sp 1
9793 @end ifnottex
9794 @ifset print-postscript-figures
9795 @sp 1
9796 @tex
9797 @center @image{cons-3}
9798 %%%% old method of including an image
9799 % \input /usr/local/lib/tex/inputs/psfig.tex
9800 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9801 % \catcode`\@=0 %
9802 @end tex
9803 @sp 1
9804 @end ifset
9805 @ifclear print-postscript-figures
9806 @iftex
9807 @sp 1
9808 @smallexample
9809 @group
9810 bouquet flowers
9811 | |
9812 | ___ ___ | ___ ___ ___ ___
9813 --> | | | --> | | | | | |
9814 |___|___|----> |___|___|--> |___|___|--> nil
9815 | | |
9816 | | |
9817 --> rose --> violet --> buttercup
9818 @end group
9819 @end smallexample
9820 @sp 1
9821 @end iftex
9822 @end ifclear
9823
9824 @noindent
9825 The value of @code{flowers} is @code{(violet buttercup)}, which is
9826 to say, the symbol @code{flowers} holds the address of the pair of
9827 address-boxes, the first of which holds the address of @code{violet},
9828 and the second of which holds the address of @code{buttercup}.
9829
9830 A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9831 pair}. @xref{Cons Cell Type, , Cons Cell and List Types, elisp, The GNU Emacs Lisp
9832 Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9833 Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9834 information about cons cells and dotted pairs.
9835
9836 @need 1200
9837 The function @code{cons} adds a new pair of addresses to the front of
9838 a series of addresses like that shown above. For example, evaluating
9839 the expression
9840
9841 @smallexample
9842 (setq bouquet (cons 'lily bouquet))
9843 @end smallexample
9844
9845 @need 1500
9846 @noindent
9847 produces:
9848
9849 @c cons-cell-diagram #4
9850 @ifnottex
9851 @sp 1
9852 @smallexample
9853 @group
9854 bouquet flowers
9855 | |
9856 | ___ ___ ___ ___ | ___ ___ ___ ___
9857 --> | | | | | | --> | | | | | |
9858 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9859 | | | |
9860 | | | |
9861 --> lily --> rose --> violet --> buttercup
9862 @end group
9863 @end smallexample
9864 @sp 1
9865 @end ifnottex
9866 @ifset print-postscript-figures
9867 @sp 1
9868 @tex
9869 @center @image{cons-4}
9870 %%%% old method of including an image
9871 % \input /usr/local/lib/tex/inputs/psfig.tex
9872 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9873 % \catcode`\@=0 %
9874 @end tex
9875 @sp 1
9876 @end ifset
9877 @ifclear print-postscript-figures
9878 @iftex
9879 @sp 1
9880 @smallexample
9881 @group
9882 bouquet flowers
9883 | |
9884 | ___ ___ ___ ___ | ___ ___ ___ ___
9885 --> | | | | | | --> | | | | | |
9886 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9887 | | | |
9888 | | | |
9889 --> lily --> rose --> violet --> buttercup
9890 @end group
9891 @end smallexample
9892 @sp 1
9893 @end iftex
9894 @end ifclear
9895
9896 @need 1200
9897 @noindent
9898 However, this does not change the value of the symbol
9899 @code{flowers}, as you can see by evaluating the following,
9900
9901 @smallexample
9902 (eq (cdr (cdr bouquet)) flowers)
9903 @end smallexample
9904
9905 @noindent
9906 which returns @code{t} for true.
9907
9908 Until it is reset, @code{flowers} still has the value
9909 @code{(violet buttercup)}; that is, it has the address of the cons
9910 cell whose first address is of @code{violet}. Also, this does not
9911 alter any of the pre-existing cons cells; they are all still there.
9912
9913 Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9914 of the next cons cell in the series; to get the @sc{car} of a list,
9915 you get the address of the first element of the list; to @code{cons} a
9916 new element on a list, you add a new cons cell to the front of the list.
9917 That is all there is to it! The underlying structure of Lisp is
9918 brilliantly simple!
9919
9920 And what does the last address in a series of cons cells refer to? It
9921 is the address of the empty list, of @code{nil}.
9922
9923 In summary, when a Lisp variable is set to a value, it is provided with
9924 the address of the list to which the variable refers.
9925
9926 @node Symbols as Chest
9927 @section Symbols as a Chest of Drawers
9928 @cindex Symbols as a Chest of Drawers
9929 @cindex Chest of Drawers, metaphor for a symbol
9930 @cindex Drawers, Chest of, metaphor for a symbol
9931
9932 In an earlier section, I suggested that you might imagine a symbol as
9933 being a chest of drawers. The function definition is put in one
9934 drawer, the value in another, and so on. What is put in the drawer
9935 holding the value can be changed without affecting the contents of the
9936 drawer holding the function definition, and vice-verse.
9937
9938 Actually, what is put in each drawer is the address of the value or
9939 function definition. It is as if you found an old chest in the attic,
9940 and in one of its drawers you found a map giving you directions to
9941 where the buried treasure lies.
9942
9943 (In addition to its name, symbol definition, and variable value, a
9944 symbol has a `drawer' for a @dfn{property list} which can be used to
9945 record other information. Property lists are not discussed here; see
9946 @ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9947 Reference Manual}.)
9948
9949 @need 1500
9950 Here is a fanciful representation:
9951
9952 @c chest-of-drawers diagram
9953 @ifnottex
9954 @sp 1
9955 @smallexample
9956 @group
9957 Chest of Drawers Contents of Drawers
9958
9959 __ o0O0o __
9960 / \
9961 ---------------------
9962 | directions to | [map to]
9963 | symbol name | bouquet
9964 | |
9965 +---------------------+
9966 | directions to |
9967 | symbol definition | [none]
9968 | |
9969 +---------------------+
9970 | directions to | [map to]
9971 | variable value | (rose violet buttercup)
9972 | |
9973 +---------------------+
9974 | directions to |
9975 | property list | [not described here]
9976 | |
9977 +---------------------+
9978 |/ \|
9979 @end group
9980 @end smallexample
9981 @sp 1
9982 @end ifnottex
9983 @ifset print-postscript-figures
9984 @sp 1
9985 @tex
9986 @center @image{drawers}
9987 %%%% old method of including an image
9988 % \input /usr/local/lib/tex/inputs/psfig.tex
9989 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9990 % \catcode`\@=0 %
9991 @end tex
9992 @sp 1
9993 @end ifset
9994 @ifclear print-postscript-figures
9995 @iftex
9996 @sp 1
9997 @smallexample
9998 @group
9999 Chest of Drawers Contents of Drawers
10000
10001 __ o0O0o __
10002 / \
10003 ---------------------
10004 | directions to | [map to]
10005 | symbol name | bouquet
10006 | |
10007 +---------------------+
10008 | directions to |
10009 | symbol definition | [none]
10010 | |
10011 +---------------------+
10012 | directions to | [map to]
10013 | variable value | (rose violet buttercup)
10014 | |
10015 +---------------------+
10016 | directions to |
10017 | property list | [not described here]
10018 | |
10019 +---------------------+
10020 |/ \|
10021 @end group
10022 @end smallexample
10023 @sp 1
10024 @end iftex
10025 @end ifclear
10026
10027 @node List Exercise
10028 @section Exercise
10029
10030 Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
10031 more flowers on to this list and set this new list to
10032 @code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
10033 What does the @code{more-flowers} list now contain?
10034
10035 @node Yanking
10036 @chapter Yanking Text Back
10037 @findex yank
10038 @cindex Text retrieval
10039 @cindex Retrieving text
10040 @cindex Pasting text
10041
10042 Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
10043 you can bring it back with a `yank' command. The text that is cut out of
10044 the buffer is put in the kill ring and the yank commands insert the
10045 appropriate contents of the kill ring back into a buffer (not necessarily
10046 the original buffer).
10047
10048 A simple @kbd{C-y} (@code{yank}) command inserts the first item from
10049 the kill ring into the current buffer. If the @kbd{C-y} command is
10050 followed immediately by @kbd{M-y}, the first element is replaced by
10051 the second element. Successive @kbd{M-y} commands replace the second
10052 element with the third, fourth, or fifth element, and so on. When the
10053 last element in the kill ring is reached, it is replaced by the first
10054 element and the cycle is repeated. (Thus the kill ring is called a
10055 `ring' rather than just a `list'. However, the actual data structure
10056 that holds the text is a list.
10057 @xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
10058 list is handled as a ring.)
10059
10060 @menu
10061 * Kill Ring Overview::
10062 * kill-ring-yank-pointer:: The kill ring is a list.
10063 * yank nthcdr Exercises:: The @code{kill-ring-yank-pointer} variable.
10064 @end menu
10065
10066 @node Kill Ring Overview
10067 @section Kill Ring Overview
10068 @cindex Kill ring overview
10069
10070 The kill ring is a list of textual strings. This is what it looks like:
10071
10072 @smallexample
10073 ("some text" "a different piece of text" "yet more text")
10074 @end smallexample
10075
10076 If this were the contents of my kill ring and I pressed @kbd{C-y}, the
10077 string of characters saying @samp{some text} would be inserted in this
10078 buffer where my cursor is located.
10079
10080 The @code{yank} command is also used for duplicating text by copying it.
10081 The copied text is not cut from the buffer, but a copy of it is put on the
10082 kill ring and is inserted by yanking it back.
10083
10084 Three functions are used for bringing text back from the kill ring:
10085 @code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
10086 which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
10087 which is used by the two other functions.
10088
10089 These functions refer to the kill ring through a variable called the
10090 @code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
10091 @code{yank} and @code{yank-pop} functions is:
10092
10093 @smallexample
10094 (insert (car kill-ring-yank-pointer))
10095 @end smallexample
10096
10097 @noindent
10098 (Well, no more. In GNU Emacs 22, the function has been replaced by
10099 @code{insert-for-yank} which calls @code{insert-for-yank-1}
10100 repetitively for each @code{yank-handler} segment. In turn,
10101 @code{insert-for-yank-1} strips text properties from the inserted text
10102 according to @code{yank-excluded-properties}. Otherwise, it is just
10103 like @code{insert}. We will stick with plain @code{insert} since it
10104 is easier to understand.)
10105
10106 To begin to understand how @code{yank} and @code{yank-pop} work, it is
10107 first necessary to look at the @code{kill-ring-yank-pointer} variable.
10108
10109 @node kill-ring-yank-pointer
10110 @section The @code{kill-ring-yank-pointer} Variable
10111
10112 @code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
10113 a variable. It points to something by being bound to the value of what
10114 it points to, like any other Lisp variable.
10115
10116 @need 1000
10117 Thus, if the value of the kill ring is:
10118
10119 @smallexample
10120 ("some text" "a different piece of text" "yet more text")
10121 @end smallexample
10122
10123 @need 1250
10124 @noindent
10125 and the @code{kill-ring-yank-pointer} points to the second clause, the
10126 value of @code{kill-ring-yank-pointer} is:
10127
10128 @smallexample
10129 ("a different piece of text" "yet more text")
10130 @end smallexample
10131
10132 As explained in the previous chapter (@pxref{List Implementation}), the
10133 computer does not keep two different copies of the text being pointed to
10134 by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
10135 words ``a different piece of text'' and ``yet more text'' are not
10136 duplicated. Instead, the two Lisp variables point to the same pieces of
10137 text. Here is a diagram:
10138
10139 @c cons-cell-diagram #5
10140 @ifnottex
10141 @smallexample
10142 @group
10143 kill-ring kill-ring-yank-pointer
10144 | |
10145 | ___ ___ | ___ ___ ___ ___
10146 ---> | | | --> | | | | | |
10147 |___|___|----> |___|___|--> |___|___|--> nil
10148 | | |
10149 | | |
10150 | | --> "yet more text"
10151 | |
10152 | --> "a different piece of text"
10153 |
10154 --> "some text"
10155 @end group
10156 @end smallexample
10157 @sp 1
10158 @end ifnottex
10159 @ifset print-postscript-figures
10160 @sp 1
10161 @tex
10162 @center @image{cons-5}
10163 %%%% old method of including an image
10164 % \input /usr/local/lib/tex/inputs/psfig.tex
10165 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
10166 % \catcode`\@=0 %
10167 @end tex
10168 @sp 1
10169 @end ifset
10170 @ifclear print-postscript-figures
10171 @iftex
10172 @smallexample
10173 @group
10174 kill-ring kill-ring-yank-pointer
10175 | |
10176 | ___ ___ | ___ ___ ___ ___
10177 ---> | | | --> | | | | | |
10178 |___|___|----> |___|___|--> |___|___|--> nil
10179 | | |
10180 | | |
10181 | | --> "yet more text"
10182 | |
10183 | --> "a different piece of text
10184 |
10185 --> "some text"
10186 @end group
10187 @end smallexample
10188 @sp 1
10189 @end iftex
10190 @end ifclear
10191
10192 Both the variable @code{kill-ring} and the variable
10193 @code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
10194 usually described as if it were actually what it is composed of. The
10195 @code{kill-ring} is spoken of as if it were the list rather than that it
10196 points to the list. Conversely, the @code{kill-ring-yank-pointer} is
10197 spoken of as pointing to a list.
10198
10199 These two ways of talking about the same thing sound confusing at first but
10200 make sense on reflection. The kill ring is generally thought of as the
10201 complete structure of data that holds the information of what has recently
10202 been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
10203 on the other hand, serves to indicate---that is, to `point to'---that part
10204 of the kill ring of which the first element (the @sc{car}) will be
10205 inserted.
10206
10207 @ignore
10208 In GNU Emacs 22, the @code{kill-new} function calls
10209
10210 @code{(setq kill-ring-yank-pointer kill-ring)}
10211
10212 (defun rotate-yank-pointer (arg)
10213 "Rotate the yanking point in the kill ring.
10214 With argument, rotate that many kills forward (or backward, if negative)."
10215 (interactive "p")
10216 (current-kill arg))
10217
10218 (defun current-kill (n &optional do-not-move)
10219 "Rotate the yanking point by N places, and then return that kill.
10220 If N is zero, `interprogram-paste-function' is set, and calling it
10221 returns a string, then that string is added to the front of the
10222 kill ring and returned as the latest kill.
10223 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
10224 yanking point; just return the Nth kill forward."
10225 (let ((interprogram-paste (and (= n 0)
10226 interprogram-paste-function
10227 (funcall interprogram-paste-function))))
10228 (if interprogram-paste
10229 (progn
10230 ;; Disable the interprogram cut function when we add the new
10231 ;; text to the kill ring, so Emacs doesn't try to own the
10232 ;; selection, with identical text.
10233 (let ((interprogram-cut-function nil))
10234 (kill-new interprogram-paste))
10235 interprogram-paste)
10236 (or kill-ring (error "Kill ring is empty"))
10237 (let ((ARGth-kill-element
10238 (nthcdr (mod (- n (length kill-ring-yank-pointer))
10239 (length kill-ring))
10240 kill-ring)))
10241 (or do-not-move
10242 (setq kill-ring-yank-pointer ARGth-kill-element))
10243 (car ARGth-kill-element)))))
10244
10245 @end ignore
10246
10247 @need 1500
10248 @node yank nthcdr Exercises
10249 @section Exercises with @code{yank} and @code{nthcdr}
10250
10251 @itemize @bullet
10252 @item
10253 Using @kbd{C-h v} (@code{describe-variable}), look at the value of
10254 your kill ring. Add several items to your kill ring; look at its
10255 value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
10256 around the kill ring. How many items were in your kill ring? Find
10257 the value of @code{kill-ring-max}. Was your kill ring full, or could
10258 you have kept more blocks of text within it?
10259
10260 @item
10261 Using @code{nthcdr} and @code{car}, construct a series of expressions
10262 to return the first, second, third, and fourth elements of a list.
10263 @end itemize
10264
10265 @node Loops & Recursion
10266 @chapter Loops and Recursion
10267 @cindex Loops and recursion
10268 @cindex Recursion and loops
10269 @cindex Repetition (loops)
10270
10271 Emacs Lisp has two primary ways to cause an expression, or a series of
10272 expressions, to be evaluated repeatedly: one uses a @code{while}
10273 loop, and the other uses @dfn{recursion}.
10274
10275 Repetition can be very valuable. For example, to move forward four
10276 sentences, you need only write a program that will move forward one
10277 sentence and then repeat the process four times. Since a computer does
10278 not get bored or tired, such repetitive action does not have the
10279 deleterious effects that excessive or the wrong kinds of repetition can
10280 have on humans.
10281
10282 People mostly write Emacs Lisp functions using @code{while} loops and
10283 their kin; but you can use recursion, which provides a very powerful
10284 way to think about and then to solve problems@footnote{You can write
10285 recursive functions to be frugal or wasteful of mental or computer
10286 resources; as it happens, methods that people find easy---that are
10287 frugal of `mental resources'---sometimes use considerable computer
10288 resources. Emacs was designed to run on machines that we now consider
10289 limited and its default settings are conservative. You may want to
10290 increase the values of @code{max-specpdl-size} and
10291 @code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
10292 15 and 30 times their default value.}.
10293
10294 @menu
10295 * while:: Causing a stretch of code to repeat.
10296 * dolist dotimes::
10297 * Recursion:: Causing a function to call itself.
10298 * Looping exercise::
10299 @end menu
10300
10301 @node while
10302 @section @code{while}
10303 @cindex Loops
10304 @findex while
10305
10306 The @code{while} special form tests whether the value returned by
10307 evaluating its first argument is true or false. This is similar to what
10308 the Lisp interpreter does with an @code{if}; what the interpreter does
10309 next, however, is different.
10310
10311 In a @code{while} expression, if the value returned by evaluating the
10312 first argument is false, the Lisp interpreter skips the rest of the
10313 expression (the @dfn{body} of the expression) and does not evaluate it.
10314 However, if the value is true, the Lisp interpreter evaluates the body
10315 of the expression and then again tests whether the first argument to
10316 @code{while} is true or false. If the value returned by evaluating the
10317 first argument is again true, the Lisp interpreter again evaluates the
10318 body of the expression.
10319
10320 @need 1200
10321 The template for a @code{while} expression looks like this:
10322
10323 @smallexample
10324 @group
10325 (while @var{true-or-false-test}
10326 @var{body}@dots{})
10327 @end group
10328 @end smallexample
10329
10330 @menu
10331 * Looping with while:: Repeat so long as test returns true.
10332 * Loop Example:: A @code{while} loop that uses a list.
10333 * print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
10334 * Incrementing Loop:: A loop with an incrementing counter.
10335 * Incrementing Loop Details::
10336 * Decrementing Loop:: A loop with a decrementing counter.
10337 @end menu
10338
10339 @ifnottex
10340 @node Looping with while
10341 @unnumberedsubsec Looping with @code{while}
10342 @end ifnottex
10343
10344 So long as the true-or-false-test of the @code{while} expression
10345 returns a true value when it is evaluated, the body is repeatedly
10346 evaluated. This process is called a loop since the Lisp interpreter
10347 repeats the same thing again and again, like an airplane doing a loop.
10348 When the result of evaluating the true-or-false-test is false, the
10349 Lisp interpreter does not evaluate the rest of the @code{while}
10350 expression and `exits the loop'.
10351
10352 Clearly, if the value returned by evaluating the first argument to
10353 @code{while} is always true, the body following will be evaluated
10354 again and again @dots{} and again @dots{} forever. Conversely, if the
10355 value returned is never true, the expressions in the body will never
10356 be evaluated. The craft of writing a @code{while} loop consists of
10357 choosing a mechanism such that the true-or-false-test returns true
10358 just the number of times that you want the subsequent expressions to
10359 be evaluated, and then have the test return false.
10360
10361 The value returned by evaluating a @code{while} is the value of the
10362 true-or-false-test. An interesting consequence of this is that a
10363 @code{while} loop that evaluates without error will return @code{nil}
10364 or false regardless of whether it has looped 1 or 100 times or none at
10365 all. A @code{while} expression that evaluates successfully never
10366 returns a true value! What this means is that @code{while} is always
10367 evaluated for its side effects, which is to say, the consequences of
10368 evaluating the expressions within the body of the @code{while} loop.
10369 This makes sense. It is not the mere act of looping that is desired,
10370 but the consequences of what happens when the expressions in the loop
10371 are repeatedly evaluated.
10372
10373 @node Loop Example
10374 @subsection A @code{while} Loop and a List
10375
10376 A common way to control a @code{while} loop is to test whether a list
10377 has any elements. If it does, the loop is repeated; but if it does not,
10378 the repetition is ended. Since this is an important technique, we will
10379 create a short example to illustrate it.
10380
10381 A simple way to test whether a list has elements is to evaluate the
10382 list: if it has no elements, it is an empty list and will return the
10383 empty list, @code{()}, which is a synonym for @code{nil} or false. On
10384 the other hand, a list with elements will return those elements when it
10385 is evaluated. Since Emacs Lisp considers as true any value that is not
10386 @code{nil}, a list that returns elements will test true in a
10387 @code{while} loop.
10388
10389 @need 1200
10390 For example, you can set the variable @code{empty-list} to @code{nil} by
10391 evaluating the following @code{setq} expression:
10392
10393 @smallexample
10394 (setq empty-list ())
10395 @end smallexample
10396
10397 @noindent
10398 After evaluating the @code{setq} expression, you can evaluate the
10399 variable @code{empty-list} in the usual way, by placing the cursor after
10400 the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
10401 echo area:
10402
10403 @smallexample
10404 empty-list
10405 @end smallexample
10406
10407 On the other hand, if you set a variable to be a list with elements, the
10408 list will appear when you evaluate the variable, as you can see by
10409 evaluating the following two expressions:
10410
10411 @smallexample
10412 @group
10413 (setq animals '(gazelle giraffe lion tiger))
10414
10415 animals
10416 @end group
10417 @end smallexample
10418
10419 Thus, to create a @code{while} loop that tests whether there are any
10420 items in the list @code{animals}, the first part of the loop will be
10421 written like this:
10422
10423 @smallexample
10424 @group
10425 (while animals
10426 @dots{}
10427 @end group
10428 @end smallexample
10429
10430 @noindent
10431 When the @code{while} tests its first argument, the variable
10432 @code{animals} is evaluated. It returns a list. So long as the list
10433 has elements, the @code{while} considers the results of the test to be
10434 true; but when the list is empty, it considers the results of the test
10435 to be false.
10436
10437 To prevent the @code{while} loop from running forever, some mechanism
10438 needs to be provided to empty the list eventually. An oft-used
10439 technique is to have one of the subsequent forms in the @code{while}
10440 expression set the value of the list to be the @sc{cdr} of the list.
10441 Each time the @code{cdr} function is evaluated, the list will be made
10442 shorter, until eventually only the empty list will be left. At this
10443 point, the test of the @code{while} loop will return false, and the
10444 arguments to the @code{while} will no longer be evaluated.
10445
10446 For example, the list of animals bound to the variable @code{animals}
10447 can be set to be the @sc{cdr} of the original list with the
10448 following expression:
10449
10450 @smallexample
10451 (setq animals (cdr animals))
10452 @end smallexample
10453
10454 @noindent
10455 If you have evaluated the previous expressions and then evaluate this
10456 expression, you will see @code{(giraffe lion tiger)} appear in the echo
10457 area. If you evaluate the expression again, @code{(lion tiger)} will
10458 appear in the echo area. If you evaluate it again and yet again,
10459 @code{(tiger)} appears and then the empty list, shown by @code{nil}.
10460
10461 A template for a @code{while} loop that uses the @code{cdr} function
10462 repeatedly to cause the true-or-false-test eventually to test false
10463 looks like this:
10464
10465 @smallexample
10466 @group
10467 (while @var{test-whether-list-is-empty}
10468 @var{body}@dots{}
10469 @var{set-list-to-cdr-of-list})
10470 @end group
10471 @end smallexample
10472
10473 This test and use of @code{cdr} can be put together in a function that
10474 goes through a list and prints each element of the list on a line of its
10475 own.
10476
10477 @node print-elements-of-list
10478 @subsection An Example: @code{print-elements-of-list}
10479 @findex print-elements-of-list
10480
10481 The @code{print-elements-of-list} function illustrates a @code{while}
10482 loop with a list.
10483
10484 @cindex @file{*scratch*} buffer
10485 The function requires several lines for its output. If you are
10486 reading this in a recent instance of GNU Emacs,
10487 @c GNU Emacs 21, GNU Emacs 22, or a later version,
10488 you can evaluate the following expression inside of Info, as usual.
10489
10490 If you are using an earlier version of Emacs, you need to copy the
10491 necessary expressions to your @file{*scratch*} buffer and evaluate
10492 them there. This is because the echo area had only one line in the
10493 earlier versions.
10494
10495 You can copy the expressions by marking the beginning of the region
10496 with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
10497 the end of the region and then copying the region using @kbd{M-w}
10498 (@code{kill-ring-save}, which calls @code{copy-region-as-kill} and
10499 then provides visual feedback). In the @file{*scratch*}
10500 buffer, you can yank the expressions back by typing @kbd{C-y}
10501 (@code{yank}).
10502
10503 After you have copied the expressions to the @file{*scratch*} buffer,
10504 evaluate each expression in turn. Be sure to evaluate the last
10505 expression, @code{(print-elements-of-list animals)}, by typing
10506 @kbd{C-u C-x C-e}, that is, by giving an argument to
10507 @code{eval-last-sexp}. This will cause the result of the evaluation
10508 to be printed in the @file{*scratch*} buffer instead of being printed
10509 in the echo area. (Otherwise you will see something like this in your
10510 echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
10511 each @samp{^J} stands for a `newline'.)
10512
10513 @need 1500
10514 In a recent instance of GNU Emacs, you can evaluate these expressions
10515 directly in the Info buffer, and the echo area will grow to show the
10516 results.
10517
10518 @smallexample
10519 @group
10520 (setq animals '(gazelle giraffe lion tiger))
10521
10522 (defun print-elements-of-list (list)
10523 "Print each element of LIST on a line of its own."
10524 (while list
10525 (print (car list))
10526 (setq list (cdr list))))
10527
10528 (print-elements-of-list animals)
10529 @end group
10530 @end smallexample
10531
10532 @need 1200
10533 @noindent
10534 When you evaluate the three expressions in sequence, you will see
10535 this:
10536
10537 @smallexample
10538 @group
10539 gazelle
10540
10541 giraffe
10542
10543 lion
10544
10545 tiger
10546 nil
10547 @end group
10548 @end smallexample
10549
10550 Each element of the list is printed on a line of its own (that is what
10551 the function @code{print} does) and then the value returned by the
10552 function is printed. Since the last expression in the function is the
10553 @code{while} loop, and since @code{while} loops always return
10554 @code{nil}, a @code{nil} is printed after the last element of the list.
10555
10556 @node Incrementing Loop
10557 @subsection A Loop with an Incrementing Counter
10558
10559 A loop is not useful unless it stops when it ought. Besides
10560 controlling a loop with a list, a common way of stopping a loop is to
10561 write the first argument as a test that returns false when the correct
10562 number of repetitions are complete. This means that the loop must
10563 have a counter---an expression that counts how many times the loop
10564 repeats itself.
10565
10566 @ifnottex
10567 @node Incrementing Loop Details
10568 @unnumberedsubsec Details of an Incrementing Loop
10569 @end ifnottex
10570
10571 The test for a loop with an incrementing counter can be an expression
10572 such as @code{(< count desired-number)} which returns @code{t} for
10573 true if the value of @code{count} is less than the
10574 @code{desired-number} of repetitions and @code{nil} for false if the
10575 value of @code{count} is equal to or is greater than the
10576 @code{desired-number}. The expression that increments the count can
10577 be a simple @code{setq} such as @code{(setq count (1+ count))}, where
10578 @code{1+} is a built-in function in Emacs Lisp that adds 1 to its
10579 argument. (The expression @w{@code{(1+ count)}} has the same result
10580 as @w{@code{(+ count 1)}}, but is easier for a human to read.)
10581
10582 @need 1250
10583 The template for a @code{while} loop controlled by an incrementing
10584 counter looks like this:
10585
10586 @smallexample
10587 @group
10588 @var{set-count-to-initial-value}
10589 (while (< count desired-number) ; @r{true-or-false-test}
10590 @var{body}@dots{}
10591 (setq count (1+ count))) ; @r{incrementer}
10592 @end group
10593 @end smallexample
10594
10595 @noindent
10596 Note that you need to set the initial value of @code{count}; usually it
10597 is set to 1.
10598
10599 @menu
10600 * Incrementing Example:: Counting pebbles in a triangle.
10601 * Inc Example parts:: The parts of the function definition.
10602 * Inc Example altogether:: Putting the function definition together.
10603 @end menu
10604
10605 @node Incrementing Example
10606 @unnumberedsubsubsec Example with incrementing counter
10607
10608 Suppose you are playing on the beach and decide to make a triangle of
10609 pebbles, putting one pebble in the first row, two in the second row,
10610 three in the third row and so on, like this:
10611
10612 @sp 1
10613 @c pebble diagram
10614 @ifnottex
10615 @smallexample
10616 @group
10617 *
10618 * *
10619 * * *
10620 * * * *
10621 @end group
10622 @end smallexample
10623 @end ifnottex
10624 @iftex
10625 @smallexample
10626 @group
10627 @bullet{}
10628 @bullet{} @bullet{}
10629 @bullet{} @bullet{} @bullet{}
10630 @bullet{} @bullet{} @bullet{} @bullet{}
10631 @end group
10632 @end smallexample
10633 @end iftex
10634 @sp 1
10635
10636 @noindent
10637 (About 2500 years ago, Pythagoras and others developed the beginnings of
10638 number theory by considering questions such as this.)
10639
10640 Suppose you want to know how many pebbles you will need to make a
10641 triangle with 7 rows?
10642
10643 Clearly, what you need to do is add up the numbers from 1 to 7. There
10644 are two ways to do this; start with the smallest number, one, and add up
10645 the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
10646 number and add the list going down: 7, 6, 5, 4 and so on. Because both
10647 mechanisms illustrate common ways of writing @code{while} loops, we will
10648 create two examples, one counting up and the other counting down. In
10649 this first example, we will start with 1 and add 2, 3, 4 and so on.
10650
10651 If you are just adding up a short list of numbers, the easiest way to do
10652 it is to add up all the numbers at once. However, if you do not know
10653 ahead of time how many numbers your list will have, or if you want to be
10654 prepared for a very long list, then you need to design your addition so
10655 that what you do is repeat a simple process many times instead of doing
10656 a more complex process once.
10657
10658 For example, instead of adding up all the pebbles all at once, what you
10659 can do is add the number of pebbles in the first row, 1, to the number
10660 in the second row, 2, and then add the total of those two rows to the
10661 third row, 3. Then you can add the number in the fourth row, 4, to the
10662 total of the first three rows; and so on.
10663
10664 The critical characteristic of the process is that each repetitive
10665 action is simple. In this case, at each step we add only two numbers,
10666 the number of pebbles in the row and the total already found. This
10667 process of adding two numbers is repeated again and again until the last
10668 row has been added to the total of all the preceding rows. In a more
10669 complex loop the repetitive action might not be so simple, but it will
10670 be simpler than doing everything all at once.
10671
10672 @node Inc Example parts
10673 @unnumberedsubsubsec The parts of the function definition
10674
10675 The preceding analysis gives us the bones of our function definition:
10676 first, we will need a variable that we can call @code{total} that will
10677 be the total number of pebbles. This will be the value returned by
10678 the function.
10679
10680 Second, we know that the function will require an argument: this
10681 argument will be the total number of rows in the triangle. It can be
10682 called @code{number-of-rows}.
10683
10684 Finally, we need a variable to use as a counter. We could call this
10685 variable @code{counter}, but a better name is @code{row-number}. That
10686 is because what the counter does in this function is count rows, and a
10687 program should be written to be as understandable as possible.
10688
10689 When the Lisp interpreter first starts evaluating the expressions in the
10690 function, the value of @code{total} should be set to zero, since we have
10691 not added anything to it. Then the function should add the number of
10692 pebbles in the first row to the total, and then add the number of
10693 pebbles in the second to the total, and then add the number of
10694 pebbles in the third row to the total, and so on, until there are no
10695 more rows left to add.
10696
10697 Both @code{total} and @code{row-number} are used only inside the
10698 function, so they can be declared as local variables with @code{let}
10699 and given initial values. Clearly, the initial value for @code{total}
10700 should be 0. The initial value of @code{row-number} should be 1,
10701 since we start with the first row. This means that the @code{let}
10702 statement will look like this:
10703
10704 @smallexample
10705 @group
10706 (let ((total 0)
10707 (row-number 1))
10708 @var{body}@dots{})
10709 @end group
10710 @end smallexample
10711
10712 After the internal variables are declared and bound to their initial
10713 values, we can begin the @code{while} loop. The expression that serves
10714 as the test should return a value of @code{t} for true so long as the
10715 @code{row-number} is less than or equal to the @code{number-of-rows}.
10716 (If the expression tests true only so long as the row number is less
10717 than the number of rows in the triangle, the last row will never be
10718 added to the total; hence the row number has to be either less than or
10719 equal to the number of rows.)
10720
10721 @need 1500
10722 @findex <= @r{(less than or equal)}
10723 Lisp provides the @code{<=} function that returns true if the value of
10724 its first argument is less than or equal to the value of its second
10725 argument and false otherwise. So the expression that the @code{while}
10726 will evaluate as its test should look like this:
10727
10728 @smallexample
10729 (<= row-number number-of-rows)
10730 @end smallexample
10731
10732 The total number of pebbles can be found by repeatedly adding the number
10733 of pebbles in a row to the total already found. Since the number of
10734 pebbles in the row is equal to the row number, the total can be found by
10735 adding the row number to the total. (Clearly, in a more complex
10736 situation, the number of pebbles in the row might be related to the row
10737 number in a more complicated way; if this were the case, the row number
10738 would be replaced by the appropriate expression.)
10739
10740 @smallexample
10741 (setq total (+ total row-number))
10742 @end smallexample
10743
10744 @noindent
10745 What this does is set the new value of @code{total} to be equal to the
10746 sum of adding the number of pebbles in the row to the previous total.
10747
10748 After setting the value of @code{total}, the conditions need to be
10749 established for the next repetition of the loop, if there is one. This
10750 is done by incrementing the value of the @code{row-number} variable,
10751 which serves as a counter. After the @code{row-number} variable has
10752 been incremented, the true-or-false-test at the beginning of the
10753 @code{while} loop tests whether its value is still less than or equal to
10754 the value of the @code{number-of-rows} and if it is, adds the new value
10755 of the @code{row-number} variable to the @code{total} of the previous
10756 repetition of the loop.
10757
10758 @need 1200
10759 The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10760 @code{row-number} variable can be incremented with this expression:
10761
10762 @smallexample
10763 (setq row-number (1+ row-number))
10764 @end smallexample
10765
10766 @node Inc Example altogether
10767 @unnumberedsubsubsec Putting the function definition together
10768
10769 We have created the parts for the function definition; now we need to
10770 put them together.
10771
10772 @need 800
10773 First, the contents of the @code{while} expression:
10774
10775 @smallexample
10776 @group
10777 (while (<= row-number number-of-rows) ; @r{true-or-false-test}
10778 (setq total (+ total row-number))
10779 (setq row-number (1+ row-number))) ; @r{incrementer}
10780 @end group
10781 @end smallexample
10782
10783 Along with the @code{let} expression varlist, this very nearly
10784 completes the body of the function definition. However, it requires
10785 one final element, the need for which is somewhat subtle.
10786
10787 The final touch is to place the variable @code{total} on a line by
10788 itself after the @code{while} expression. Otherwise, the value returned
10789 by the whole function is the value of the last expression that is
10790 evaluated in the body of the @code{let}, and this is the value
10791 returned by the @code{while}, which is always @code{nil}.
10792
10793 This may not be evident at first sight. It almost looks as if the
10794 incrementing expression is the last expression of the whole function.
10795 But that expression is part of the body of the @code{while}; it is the
10796 last element of the list that starts with the symbol @code{while}.
10797 Moreover, the whole of the @code{while} loop is a list within the body
10798 of the @code{let}.
10799
10800 @need 1250
10801 In outline, the function will look like this:
10802
10803 @smallexample
10804 @group
10805 (defun @var{name-of-function} (@var{argument-list})
10806 "@var{documentation}@dots{}"
10807 (let (@var{varlist})
10808 (while (@var{true-or-false-test})
10809 @var{body-of-while}@dots{} )
10810 @dots{} )) ; @r{Need final expression here.}
10811 @end group
10812 @end smallexample
10813
10814 The result of evaluating the @code{let} is what is going to be returned
10815 by the @code{defun} since the @code{let} is not embedded within any
10816 containing list, except for the @code{defun} as a whole. However, if
10817 the @code{while} is the last element of the @code{let} expression, the
10818 function will always return @code{nil}. This is not what we want!
10819 Instead, what we want is the value of the variable @code{total}. This
10820 is returned by simply placing the symbol as the last element of the list
10821 starting with @code{let}. It gets evaluated after the preceding
10822 elements of the list are evaluated, which means it gets evaluated after
10823 it has been assigned the correct value for the total.
10824
10825 It may be easier to see this by printing the list starting with
10826 @code{let} all on one line. This format makes it evident that the
10827 @var{varlist} and @code{while} expressions are the second and third
10828 elements of the list starting with @code{let}, and the @code{total} is
10829 the last element:
10830
10831 @smallexample
10832 @group
10833 (let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10834 @end group
10835 @end smallexample
10836
10837 @need 1200
10838 Putting everything together, the @code{triangle} function definition
10839 looks like this:
10840
10841 @smallexample
10842 @group
10843 (defun triangle (number-of-rows) ; @r{Version with}
10844 ; @r{ incrementing counter.}
10845 "Add up the number of pebbles in a triangle.
10846 The first row has one pebble, the second row two pebbles,
10847 the third row three pebbles, and so on.
10848 The argument is NUMBER-OF-ROWS."
10849 @end group
10850 @group
10851 (let ((total 0)
10852 (row-number 1))
10853 (while (<= row-number number-of-rows)
10854 (setq total (+ total row-number))
10855 (setq row-number (1+ row-number)))
10856 total))
10857 @end group
10858 @end smallexample
10859
10860 @need 1200
10861 After you have installed @code{triangle} by evaluating the function, you
10862 can try it out. Here are two examples:
10863
10864 @smallexample
10865 @group
10866 (triangle 4)
10867
10868 (triangle 7)
10869 @end group
10870 @end smallexample
10871
10872 @noindent
10873 The sum of the first four numbers is 10 and the sum of the first seven
10874 numbers is 28.
10875
10876 @node Decrementing Loop
10877 @subsection Loop with a Decrementing Counter
10878
10879 Another common way to write a @code{while} loop is to write the test
10880 so that it determines whether a counter is greater than zero. So long
10881 as the counter is greater than zero, the loop is repeated. But when
10882 the counter is equal to or less than zero, the loop is stopped. For
10883 this to work, the counter has to start out greater than zero and then
10884 be made smaller and smaller by a form that is evaluated
10885 repeatedly.
10886
10887 The test will be an expression such as @code{(> counter 0)} which
10888 returns @code{t} for true if the value of @code{counter} is greater
10889 than zero, and @code{nil} for false if the value of @code{counter} is
10890 equal to or less than zero. The expression that makes the number
10891 smaller and smaller can be a simple @code{setq} such as @code{(setq
10892 counter (1- counter))}, where @code{1-} is a built-in function in
10893 Emacs Lisp that subtracts 1 from its argument.
10894
10895 @need 1250
10896 The template for a decrementing @code{while} loop looks like this:
10897
10898 @smallexample
10899 @group
10900 (while (> counter 0) ; @r{true-or-false-test}
10901 @var{body}@dots{}
10902 (setq counter (1- counter))) ; @r{decrementer}
10903 @end group
10904 @end smallexample
10905
10906 @menu
10907 * Decrementing Example:: More pebbles on the beach.
10908 * Dec Example parts:: The parts of the function definition.
10909 * Dec Example altogether:: Putting the function definition together.
10910 @end menu
10911
10912 @node Decrementing Example
10913 @unnumberedsubsubsec Example with decrementing counter
10914
10915 To illustrate a loop with a decrementing counter, we will rewrite the
10916 @code{triangle} function so the counter decreases to zero.
10917
10918 This is the reverse of the earlier version of the function. In this
10919 case, to find out how many pebbles are needed to make a triangle with
10920 3 rows, add the number of pebbles in the third row, 3, to the number
10921 in the preceding row, 2, and then add the total of those two rows to
10922 the row that precedes them, which is 1.
10923
10924 Likewise, to find the number of pebbles in a triangle with 7 rows, add
10925 the number of pebbles in the seventh row, 7, to the number in the
10926 preceding row, which is 6, and then add the total of those two rows to
10927 the row that precedes them, which is 5, and so on. As in the previous
10928 example, each addition only involves adding two numbers, the total of
10929 the rows already added up and the number of pebbles in the row that is
10930 being added to the total. This process of adding two numbers is
10931 repeated again and again until there are no more pebbles to add.
10932
10933 We know how many pebbles to start with: the number of pebbles in the
10934 last row is equal to the number of rows. If the triangle has seven
10935 rows, the number of pebbles in the last row is 7. Likewise, we know how
10936 many pebbles are in the preceding row: it is one less than the number in
10937 the row.
10938
10939 @node Dec Example parts
10940 @unnumberedsubsubsec The parts of the function definition
10941
10942 We start with three variables: the total number of rows in the
10943 triangle; the number of pebbles in a row; and the total number of
10944 pebbles, which is what we want to calculate. These variables can be
10945 named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10946 @code{total}, respectively.
10947
10948 Both @code{total} and @code{number-of-pebbles-in-row} are used only
10949 inside the function and are declared with @code{let}. The initial
10950 value of @code{total} should, of course, be zero. However, the
10951 initial value of @code{number-of-pebbles-in-row} should be equal to
10952 the number of rows in the triangle, since the addition will start with
10953 the longest row.
10954
10955 @need 1250
10956 This means that the beginning of the @code{let} expression will look
10957 like this:
10958
10959 @smallexample
10960 @group
10961 (let ((total 0)
10962 (number-of-pebbles-in-row number-of-rows))
10963 @var{body}@dots{})
10964 @end group
10965 @end smallexample
10966
10967 The total number of pebbles can be found by repeatedly adding the number
10968 of pebbles in a row to the total already found, that is, by repeatedly
10969 evaluating the following expression:
10970
10971 @smallexample
10972 (setq total (+ total number-of-pebbles-in-row))
10973 @end smallexample
10974
10975 @noindent
10976 After the @code{number-of-pebbles-in-row} is added to the @code{total},
10977 the @code{number-of-pebbles-in-row} should be decremented by one, since
10978 the next time the loop repeats, the preceding row will be
10979 added to the total.
10980
10981 The number of pebbles in a preceding row is one less than the number of
10982 pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10983 used to compute the number of pebbles in the preceding row. This can be
10984 done with the following expression:
10985
10986 @smallexample
10987 @group
10988 (setq number-of-pebbles-in-row
10989 (1- number-of-pebbles-in-row))
10990 @end group
10991 @end smallexample
10992
10993 Finally, we know that the @code{while} loop should stop making repeated
10994 additions when there are no pebbles in a row. So the test for
10995 the @code{while} loop is simply:
10996
10997 @smallexample
10998 (while (> number-of-pebbles-in-row 0)
10999 @end smallexample
11000
11001 @node Dec Example altogether
11002 @unnumberedsubsubsec Putting the function definition together
11003
11004 We can put these expressions together to create a function definition
11005 that works. However, on examination, we find that one of the local
11006 variables is unneeded!
11007
11008 @need 1250
11009 The function definition looks like this:
11010
11011 @smallexample
11012 @group
11013 ;;; @r{First subtractive version.}
11014 (defun triangle (number-of-rows)
11015 "Add up the number of pebbles in a triangle."
11016 (let ((total 0)
11017 (number-of-pebbles-in-row number-of-rows))
11018 (while (> number-of-pebbles-in-row 0)
11019 (setq total (+ total number-of-pebbles-in-row))
11020 (setq number-of-pebbles-in-row
11021 (1- number-of-pebbles-in-row)))
11022 total))
11023 @end group
11024 @end smallexample
11025
11026 As written, this function works.
11027
11028 However, we do not need @code{number-of-pebbles-in-row}.
11029
11030 @cindex Argument as local variable
11031 When the @code{triangle} function is evaluated, the symbol
11032 @code{number-of-rows} will be bound to a number, giving it an initial
11033 value. That number can be changed in the body of the function as if
11034 it were a local variable, without any fear that such a change will
11035 effect the value of the variable outside of the function. This is a
11036 very useful characteristic of Lisp; it means that the variable
11037 @code{number-of-rows} can be used anywhere in the function where
11038 @code{number-of-pebbles-in-row} is used.
11039
11040 @need 800
11041 Here is a second version of the function written a bit more cleanly:
11042
11043 @smallexample
11044 @group
11045 (defun triangle (number) ; @r{Second version.}
11046 "Return sum of numbers 1 through NUMBER inclusive."
11047 (let ((total 0))
11048 (while (> number 0)
11049 (setq total (+ total number))
11050 (setq number (1- number)))
11051 total))
11052 @end group
11053 @end smallexample
11054
11055 In brief, a properly written @code{while} loop will consist of three parts:
11056
11057 @enumerate
11058 @item
11059 A test that will return false after the loop has repeated itself the
11060 correct number of times.
11061
11062 @item
11063 An expression the evaluation of which will return the value desired
11064 after being repeatedly evaluated.
11065
11066 @item
11067 An expression to change the value passed to the true-or-false-test so
11068 that the test returns false after the loop has repeated itself the right
11069 number of times.
11070 @end enumerate
11071
11072 @node dolist dotimes
11073 @section Save your time: @code{dolist} and @code{dotimes}
11074
11075 In addition to @code{while}, both @code{dolist} and @code{dotimes}
11076 provide for looping. Sometimes these are quicker to write than the
11077 equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
11078 Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
11079
11080 @code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
11081 list': @code{dolist} automatically shortens the list each time it
11082 loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
11083 each shorter version of the list to the first of its arguments.
11084
11085 @code{dotimes} loops a specific number of times: you specify the number.
11086
11087 @menu
11088 * dolist::
11089 * dotimes::
11090 @end menu
11091
11092 @node dolist
11093 @unnumberedsubsec The @code{dolist} Macro
11094 @findex dolist
11095
11096 Suppose, for example, you want to reverse a list, so that
11097 ``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
11098
11099 @need 1250
11100 In practice, you would use the @code{reverse} function, like this:
11101
11102 @smallexample
11103 @group
11104 (setq animals '(gazelle giraffe lion tiger))
11105
11106 (reverse animals)
11107 @end group
11108 @end smallexample
11109
11110 @need 800
11111 @noindent
11112 Here is how you could reverse the list using a @code{while} loop:
11113
11114 @smallexample
11115 @group
11116 (setq animals '(gazelle giraffe lion tiger))
11117
11118 (defun reverse-list-with-while (list)
11119 "Using while, reverse the order of LIST."
11120 (let (value) ; make sure list starts empty
11121 (while list
11122 (setq value (cons (car list) value))
11123 (setq list (cdr list)))
11124 value))
11125
11126 (reverse-list-with-while animals)
11127 @end group
11128 @end smallexample
11129
11130 @need 800
11131 @noindent
11132 And here is how you could use the @code{dolist} macro:
11133
11134 @smallexample
11135 @group
11136 (setq animals '(gazelle giraffe lion tiger))
11137
11138 (defun reverse-list-with-dolist (list)
11139 "Using dolist, reverse the order of LIST."
11140 (let (value) ; make sure list starts empty
11141 (dolist (element list value)
11142 (setq value (cons element value)))))
11143
11144 (reverse-list-with-dolist animals)
11145 @end group
11146 @end smallexample
11147
11148 @need 1250
11149 @noindent
11150 In Info, you can place your cursor after the closing parenthesis of
11151 each expression and type @kbd{C-x C-e}; in each case, you should see
11152
11153 @smallexample
11154 (tiger lion giraffe gazelle)
11155 @end smallexample
11156
11157 @noindent
11158 in the echo area.
11159
11160 For this example, the existing @code{reverse} function is obviously best.
11161 The @code{while} loop is just like our first example (@pxref{Loop
11162 Example, , A @code{while} Loop and a List}). The @code{while} first
11163 checks whether the list has elements; if so, it constructs a new list
11164 by adding the first element of the list to the existing list (which in
11165 the first iteration of the loop is @code{nil}). Since the second
11166 element is prepended in front of the first element, and the third
11167 element is prepended in front of the second element, the list is reversed.
11168
11169 In the expression using a @code{while} loop,
11170 the @w{@code{(setq list (cdr list))}}
11171 expression shortens the list, so the @code{while} loop eventually
11172 stops. In addition, it provides the @code{cons} expression with a new
11173 first element by creating a new and shorter list at each repetition of
11174 the loop.
11175
11176 The @code{dolist} expression does very much the same as the
11177 @code{while} expression, except that the @code{dolist} macro does some
11178 of the work you have to do when writing a @code{while} expression.
11179
11180 Like a @code{while} loop, a @code{dolist} loops. What is different is
11181 that it automatically shortens the list each time it loops---it
11182 `@sc{cdr}s down the list' on its own---and it automatically binds
11183 the @sc{car} of each shorter version of the list to the first of its
11184 arguments.
11185
11186 In the example, the @sc{car} of each shorter version of the list is
11187 referred to using the symbol @samp{element}, the list itself is called
11188 @samp{list}, and the value returned is called @samp{value}. The
11189 remainder of the @code{dolist} expression is the body.
11190
11191 The @code{dolist} expression binds the @sc{car} of each shorter
11192 version of the list to @code{element} and then evaluates the body of
11193 the expression; and repeats the loop. The result is returned in
11194 @code{value}.
11195
11196 @node dotimes
11197 @unnumberedsubsec The @code{dotimes} Macro
11198 @findex dotimes
11199
11200 The @code{dotimes} macro is similar to @code{dolist}, except that it
11201 loops a specific number of times.
11202
11203 The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
11204 and so forth each time around the loop, and the value of the third
11205 argument is returned. You need to provide the value of the second
11206 argument, which is how many times the macro loops.
11207
11208 @need 1250
11209 For example, the following binds the numbers from 0 up to, but not
11210 including, the number 3 to the first argument, @var{number}, and then
11211 constructs a list of the three numbers. (The first number is 0, the
11212 second number is 1, and the third number is 2; this makes a total of
11213 three numbers in all, starting with zero as the first number.)
11214
11215 @smallexample
11216 @group
11217 (let (value) ; otherwise a value is a void variable
11218 (dotimes (number 3 value)
11219 (setq value (cons number value))))
11220
11221 @result{} (2 1 0)
11222 @end group
11223 @end smallexample
11224
11225 @noindent
11226 @code{dotimes} returns @code{value}, so the way to use
11227 @code{dotimes} is to operate on some expression @var{number} number of
11228 times and then return the result, either as a list or an atom.
11229
11230 @need 1250
11231 Here is an example of a @code{defun} that uses @code{dotimes} to add
11232 up the number of pebbles in a triangle.
11233
11234 @smallexample
11235 @group
11236 (defun triangle-using-dotimes (number-of-rows)
11237 "Using dotimes, add up the number of pebbles in a triangle."
11238 (let ((total 0)) ; otherwise a total is a void variable
11239 (dotimes (number number-of-rows total)
11240 (setq total (+ total (1+ number))))))
11241
11242 (triangle-using-dotimes 4)
11243 @end group
11244 @end smallexample
11245
11246 @node Recursion
11247 @section Recursion
11248 @cindex Recursion
11249
11250 A recursive function contains code that tells the Lisp interpreter to
11251 call a program that runs exactly like itself, but with slightly
11252 different arguments. The code runs exactly the same because it has
11253 the same name. However, even though the program has the same name, it
11254 is not the same entity. It is different. In the jargon, it is a
11255 different `instance'.
11256
11257 Eventually, if the program is written correctly, the `slightly
11258 different arguments' will become sufficiently different from the first
11259 arguments that the final instance will stop.
11260
11261 @menu
11262 * Building Robots:: Same model, different serial number ...
11263 * Recursive Definition Parts:: Walk until you stop ...
11264 * Recursion with list:: Using a list as the test whether to recurse.
11265 * Recursive triangle function::
11266 * Recursion with cond::
11267 * Recursive Patterns:: Often used templates.
11268 * No Deferment:: Don't store up work ...
11269 * No deferment solution::
11270 @end menu
11271
11272 @node Building Robots
11273 @subsection Building Robots: Extending the Metaphor
11274 @cindex Building robots
11275 @cindex Robots, building
11276
11277 It is sometimes helpful to think of a running program as a robot that
11278 does a job. In doing its job, a recursive function calls on a second
11279 robot to help it. The second robot is identical to the first in every
11280 way, except that the second robot helps the first and has been
11281 passed different arguments than the first.
11282
11283 In a recursive function, the second robot may call a third; and the
11284 third may call a fourth, and so on. Each of these is a different
11285 entity; but all are clones.
11286
11287 Since each robot has slightly different instructions---the arguments
11288 will differ from one robot to the next---the last robot should know
11289 when to stop.
11290
11291 Let's expand on the metaphor in which a computer program is a robot.
11292
11293 A function definition provides the blueprints for a robot. When you
11294 install a function definition, that is, when you evaluate a
11295 @code{defun} special form, you install the necessary equipment to
11296 build robots. It is as if you were in a factory, setting up an
11297 assembly line. Robots with the same name are built according to the
11298 same blueprints. So they have, as it were, the same `model number',
11299 but a different `serial number'.
11300
11301 We often say that a recursive function `calls itself'. What we mean
11302 is that the instructions in a recursive function cause the Lisp
11303 interpreter to run a different function that has the same name and
11304 does the same job as the first, but with different arguments.
11305
11306 It is important that the arguments differ from one instance to the
11307 next; otherwise, the process will never stop.
11308
11309 @node Recursive Definition Parts
11310 @subsection The Parts of a Recursive Definition
11311 @cindex Parts of a Recursive Definition
11312 @cindex Recursive Definition Parts
11313
11314 A recursive function typically contains a conditional expression which
11315 has three parts:
11316
11317 @enumerate
11318 @item
11319 A true-or-false-test that determines whether the function is called
11320 again, here called the @dfn{do-again-test}.
11321
11322 @item
11323 The name of the function. When this name is called, a new instance of
11324 the function---a new robot, as it were---is created and told what to do.
11325
11326 @item
11327 An expression that returns a different value each time the function is
11328 called, here called the @dfn{next-step-expression}. Consequently, the
11329 argument (or arguments) passed to the new instance of the function
11330 will be different from that passed to the previous instance. This
11331 causes the conditional expression, the @dfn{do-again-test}, to test
11332 false after the correct number of repetitions.
11333 @end enumerate
11334
11335 Recursive functions can be much simpler than any other kind of
11336 function. Indeed, when people first start to use them, they often look
11337 so mysteriously simple as to be incomprehensible. Like riding a
11338 bicycle, reading a recursive function definition takes a certain knack
11339 which is hard at first but then seems simple.
11340
11341 @need 1200
11342 There are several different common recursive patterns. A very simple
11343 pattern looks like this:
11344
11345 @smallexample
11346 @group
11347 (defun @var{name-of-recursive-function} (@var{argument-list})
11348 "@var{documentation}@dots{}"
11349 (if @var{do-again-test}
11350 @var{body}@dots{}
11351 (@var{name-of-recursive-function}
11352 @var{next-step-expression})))
11353 @end group
11354 @end smallexample
11355
11356 Each time a recursive function is evaluated, a new instance of it is
11357 created and told what to do. The arguments tell the instance what to do.
11358
11359 An argument is bound to the value of the next-step-expression. Each
11360 instance runs with a different value of the next-step-expression.
11361
11362 The value in the next-step-expression is used in the do-again-test.
11363
11364 The value returned by the next-step-expression is passed to the new
11365 instance of the function, which evaluates it (or some
11366 transmogrification of it) to determine whether to continue or stop.
11367 The next-step-expression is designed so that the do-again-test returns
11368 false when the function should no longer be repeated.
11369
11370 The do-again-test is sometimes called the @dfn{stop condition},
11371 since it stops the repetitions when it tests false.
11372
11373 @node Recursion with list
11374 @subsection Recursion with a List
11375
11376 The example of a @code{while} loop that printed the elements of a list
11377 of numbers can be written recursively. Here is the code, including
11378 an expression to set the value of the variable @code{animals} to a list.
11379
11380 If you are reading this in Info in Emacs, you can evaluate this
11381 expression directly in Info. Otherwise, you must copy the example
11382 to the @file{*scratch*} buffer and evaluate each expression there.
11383 Use @kbd{C-u C-x C-e} to evaluate the
11384 @code{(print-elements-recursively animals)} expression so that the
11385 results are printed in the buffer; otherwise the Lisp interpreter will
11386 try to squeeze the results into the one line of the echo area.
11387
11388 Also, place your cursor immediately after the last closing parenthesis
11389 of the @code{print-elements-recursively} function, before the comment.
11390 Otherwise, the Lisp interpreter will try to evaluate the comment.
11391
11392 @findex print-elements-recursively
11393 @smallexample
11394 @group
11395 (setq animals '(gazelle giraffe lion tiger))
11396
11397 (defun print-elements-recursively (list)
11398 "Print each element of LIST on a line of its own.
11399 Uses recursion."
11400 (when list ; @r{do-again-test}
11401 (print (car list)) ; @r{body}
11402 (print-elements-recursively ; @r{recursive call}
11403 (cdr list)))) ; @r{next-step-expression}
11404
11405 (print-elements-recursively animals)
11406 @end group
11407 @end smallexample
11408
11409 The @code{print-elements-recursively} function first tests whether
11410 there is any content in the list; if there is, the function prints the
11411 first element of the list, the @sc{car} of the list. Then the
11412 function `invokes itself', but gives itself as its argument, not the
11413 whole list, but the second and subsequent elements of the list, the
11414 @sc{cdr} of the list.
11415
11416 Put another way, if the list is not empty, the function invokes
11417 another instance of code that is similar to the initial code, but is a
11418 different thread of execution, with different arguments than the first
11419 instance.
11420
11421 Put in yet another way, if the list is not empty, the first robot
11422 assembles a second robot and tells it what to do; the second robot is
11423 a different individual from the first, but is the same model.
11424
11425 When the second evaluation occurs, the @code{when} expression is
11426 evaluated and if true, prints the first element of the list it
11427 receives as its argument (which is the second element of the original
11428 list). Then the function `calls itself' with the @sc{cdr} of the list
11429 it is invoked with, which (the second time around) is the @sc{cdr} of
11430 the @sc{cdr} of the original list.
11431
11432 Note that although we say that the function `calls itself', what we
11433 mean is that the Lisp interpreter assembles and instructs a new
11434 instance of the program. The new instance is a clone of the first,
11435 but is a separate individual.
11436
11437 Each time the function `invokes itself', it invokes itself on a
11438 shorter version of the original list. It creates a new instance that
11439 works on a shorter list.
11440
11441 Eventually, the function invokes itself on an empty list. It creates
11442 a new instance whose argument is @code{nil}. The conditional expression
11443 tests the value of @code{list}. Since the value of @code{list} is
11444 @code{nil}, the @code{when} expression tests false so the then-part is
11445 not evaluated. The function as a whole then returns @code{nil}.
11446
11447 @need 1200
11448 When you evaluate the expression @code{(print-elements-recursively
11449 animals)} in the @file{*scratch*} buffer, you see this result:
11450
11451 @smallexample
11452 @group
11453 gazelle
11454
11455 giraffe
11456
11457 lion
11458
11459 tiger
11460 nil
11461 @end group
11462 @end smallexample
11463
11464 @need 2000
11465 @node Recursive triangle function
11466 @subsection Recursion in Place of a Counter
11467 @findex triangle-recursively
11468
11469 @need 1200
11470 The @code{triangle} function described in a previous section can also
11471 be written recursively. It looks like this:
11472
11473 @smallexample
11474 @group
11475 (defun triangle-recursively (number)
11476 "Return the sum of the numbers 1 through NUMBER inclusive.
11477 Uses recursion."
11478 (if (= number 1) ; @r{do-again-test}
11479 1 ; @r{then-part}
11480 (+ number ; @r{else-part}
11481 (triangle-recursively ; @r{recursive call}
11482 (1- number))))) ; @r{next-step-expression}
11483
11484 (triangle-recursively 7)
11485 @end group
11486 @end smallexample
11487
11488 @noindent
11489 You can install this function by evaluating it and then try it by
11490 evaluating @code{(triangle-recursively 7)}. (Remember to put your
11491 cursor immediately after the last parenthesis of the function
11492 definition, before the comment.) The function evaluates to 28.
11493
11494 To understand how this function works, let's consider what happens in the
11495 various cases when the function is passed 1, 2, 3, or 4 as the value of
11496 its argument.
11497
11498 @menu
11499 * Recursive Example arg of 1 or 2::
11500 * Recursive Example arg of 3 or 4::
11501 @end menu
11502
11503 @ifnottex
11504 @node Recursive Example arg of 1 or 2
11505 @unnumberedsubsubsec An argument of 1 or 2
11506 @end ifnottex
11507
11508 First, what happens if the value of the argument is 1?
11509
11510 The function has an @code{if} expression after the documentation
11511 string. It tests whether the value of @code{number} is equal to 1; if
11512 so, Emacs evaluates the then-part of the @code{if} expression, which
11513 returns the number 1 as the value of the function. (A triangle with
11514 one row has one pebble in it.)
11515
11516 Suppose, however, that the value of the argument is 2. In this case,
11517 Emacs evaluates the else-part of the @code{if} expression.
11518
11519 @need 1200
11520 The else-part consists of an addition, the recursive call to
11521 @code{triangle-recursively} and a decrementing action; and it looks like
11522 this:
11523
11524 @smallexample
11525 (+ number (triangle-recursively (1- number)))
11526 @end smallexample
11527
11528 When Emacs evaluates this expression, the innermost expression is
11529 evaluated first; then the other parts in sequence. Here are the steps
11530 in detail:
11531
11532 @table @i
11533 @item Step 1 @w{ } Evaluate the innermost expression.
11534
11535 The innermost expression is @code{(1- number)} so Emacs decrements the
11536 value of @code{number} from 2 to 1.
11537
11538 @item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
11539
11540 The Lisp interpreter creates an individual instance of
11541 @code{triangle-recursively}. It does not matter that this function is
11542 contained within itself. Emacs passes the result Step 1 as the
11543 argument used by this instance of the @code{triangle-recursively}
11544 function
11545
11546 In this case, Emacs evaluates @code{triangle-recursively} with an
11547 argument of 1. This means that this evaluation of
11548 @code{triangle-recursively} returns 1.
11549
11550 @item Step 3 @w{ } Evaluate the value of @code{number}.
11551
11552 The variable @code{number} is the second element of the list that
11553 starts with @code{+}; its value is 2.
11554
11555 @item Step 4 @w{ } Evaluate the @code{+} expression.
11556
11557 The @code{+} expression receives two arguments, the first
11558 from the evaluation of @code{number} (Step 3) and the second from the
11559 evaluation of @code{triangle-recursively} (Step 2).
11560
11561 The result of the addition is the sum of 2 plus 1, and the number 3 is
11562 returned, which is correct. A triangle with two rows has three
11563 pebbles in it.
11564 @end table
11565
11566 @node Recursive Example arg of 3 or 4
11567 @unnumberedsubsubsec An argument of 3 or 4
11568
11569 Suppose that @code{triangle-recursively} is called with an argument of
11570 3.
11571
11572 @table @i
11573 @item Step 1 @w{ } Evaluate the do-again-test.
11574
11575 The @code{if} expression is evaluated first. This is the do-again
11576 test and returns false, so the else-part of the @code{if} expression
11577 is evaluated. (Note that in this example, the do-again-test causes
11578 the function to call itself when it tests false, not when it tests
11579 true.)
11580
11581 @item Step 2 @w{ } Evaluate the innermost expression of the else-part.
11582
11583 The innermost expression of the else-part is evaluated, which decrements
11584 3 to 2. This is the next-step-expression.
11585
11586 @item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
11587
11588 The number 2 is passed to the @code{triangle-recursively} function.
11589
11590 We already know what happens when Emacs evaluates @code{triangle-recursively} with
11591 an argument of 2. After going through the sequence of actions described
11592 earlier, it returns a value of 3. So that is what will happen here.
11593
11594 @item Step 4 @w{ } Evaluate the addition.
11595
11596 3 will be passed as an argument to the addition and will be added to the
11597 number with which the function was called, which is 3.
11598 @end table
11599
11600 @noindent
11601 The value returned by the function as a whole will be 6.
11602
11603 Now that we know what will happen when @code{triangle-recursively} is
11604 called with an argument of 3, it is evident what will happen if it is
11605 called with an argument of 4:
11606
11607 @quotation
11608 @need 800
11609 In the recursive call, the evaluation of
11610
11611 @smallexample
11612 (triangle-recursively (1- 4))
11613 @end smallexample
11614
11615 @need 800
11616 @noindent
11617 will return the value of evaluating
11618
11619 @smallexample
11620 (triangle-recursively 3)
11621 @end smallexample
11622
11623 @noindent
11624 which is 6 and this value will be added to 4 by the addition in the
11625 third line.
11626 @end quotation
11627
11628 @noindent
11629 The value returned by the function as a whole will be 10.
11630
11631 Each time @code{triangle-recursively} is evaluated, it evaluates a
11632 version of itself---a different instance of itself---with a smaller
11633 argument, until the argument is small enough so that it does not
11634 evaluate itself.
11635
11636 Note that this particular design for a recursive function
11637 requires that operations be deferred.
11638
11639 Before @code{(triangle-recursively 7)} can calculate its answer, it
11640 must call @code{(triangle-recursively 6)}; and before
11641 @code{(triangle-recursively 6)} can calculate its answer, it must call
11642 @code{(triangle-recursively 5)}; and so on. That is to say, the
11643 calculation that @code{(triangle-recursively 7)} makes must be
11644 deferred until @code{(triangle-recursively 6)} makes its calculation;
11645 and @code{(triangle-recursively 6)} must defer until
11646 @code{(triangle-recursively 5)} completes; and so on.
11647
11648 If each of these instances of @code{triangle-recursively} are thought
11649 of as different robots, the first robot must wait for the second to
11650 complete its job, which must wait until the third completes, and so
11651 on.
11652
11653 There is a way around this kind of waiting, which we will discuss in
11654 @ref{No Deferment, , Recursion without Deferments}.
11655
11656 @node Recursion with cond
11657 @subsection Recursion Example Using @code{cond}
11658 @findex cond
11659
11660 The version of @code{triangle-recursively} described earlier is written
11661 with the @code{if} special form. It can also be written using another
11662 special form called @code{cond}. The name of the special form
11663 @code{cond} is an abbreviation of the word @samp{conditional}.
11664
11665 Although the @code{cond} special form is not used as often in the
11666 Emacs Lisp sources as @code{if}, it is used often enough to justify
11667 explaining it.
11668
11669 @need 800
11670 The template for a @code{cond} expression looks like this:
11671
11672 @smallexample
11673 @group
11674 (cond
11675 @var{body}@dots{})
11676 @end group
11677 @end smallexample
11678
11679 @noindent
11680 where the @var{body} is a series of lists.
11681
11682 @need 800
11683 Written out more fully, the template looks like this:
11684
11685 @smallexample
11686 @group
11687 (cond
11688 (@var{first-true-or-false-test} @var{first-consequent})
11689 (@var{second-true-or-false-test} @var{second-consequent})
11690 (@var{third-true-or-false-test} @var{third-consequent})
11691 @dots{})
11692 @end group
11693 @end smallexample
11694
11695 When the Lisp interpreter evaluates the @code{cond} expression, it
11696 evaluates the first element (the @sc{car} or true-or-false-test) of
11697 the first expression in a series of expressions within the body of the
11698 @code{cond}.
11699
11700 If the true-or-false-test returns @code{nil} the rest of that
11701 expression, the consequent, is skipped and the true-or-false-test of the
11702 next expression is evaluated. When an expression is found whose
11703 true-or-false-test returns a value that is not @code{nil}, the
11704 consequent of that expression is evaluated. The consequent can be one
11705 or more expressions. If the consequent consists of more than one
11706 expression, the expressions are evaluated in sequence and the value of
11707 the last one is returned. If the expression does not have a consequent,
11708 the value of the true-or-false-test is returned.
11709
11710 If none of the true-or-false-tests test true, the @code{cond} expression
11711 returns @code{nil}.
11712
11713 @need 1250
11714 Written using @code{cond}, the @code{triangle} function looks like this:
11715
11716 @smallexample
11717 @group
11718 (defun triangle-using-cond (number)
11719 (cond ((<= number 0) 0)
11720 ((= number 1) 1)
11721 ((> number 1)
11722 (+ number (triangle-using-cond (1- number))))))
11723 @end group
11724 @end smallexample
11725
11726 @noindent
11727 In this example, the @code{cond} returns 0 if the number is less than or
11728 equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11729 number (triangle-using-cond (1- number)))} if the number is greater than
11730 1.
11731
11732 @node Recursive Patterns
11733 @subsection Recursive Patterns
11734 @cindex Recursive Patterns
11735
11736 Here are three common recursive patterns. Each involves a list.
11737 Recursion does not need to involve lists, but Lisp is designed for lists
11738 and this provides a sense of its primal capabilities.
11739
11740 @menu
11741 * Every::
11742 * Accumulate::
11743 * Keep::
11744 @end menu
11745
11746 @node Every
11747 @unnumberedsubsubsec Recursive Pattern: @emph{every}
11748 @cindex Every, type of recursive pattern
11749 @cindex Recursive pattern: every
11750
11751 In the @code{every} recursive pattern, an action is performed on every
11752 element of a list.
11753
11754 @need 1500
11755 The basic pattern is:
11756
11757 @itemize @bullet
11758 @item
11759 If a list be empty, return @code{nil}.
11760 @item
11761 Else, act on the beginning of the list (the @sc{car} of the list)
11762 @itemize @minus
11763 @item
11764 through a recursive call by the function on the rest (the
11765 @sc{cdr}) of the list,
11766 @item
11767 and, optionally, combine the acted-on element, using @code{cons},
11768 with the results of acting on the rest.
11769 @end itemize
11770 @end itemize
11771
11772 @need 1500
11773 Here is example:
11774
11775 @smallexample
11776 @group
11777 (defun square-each (numbers-list)
11778 "Square each of a NUMBERS LIST, recursively."
11779 (if (not numbers-list) ; do-again-test
11780 nil
11781 (cons
11782 (* (car numbers-list) (car numbers-list))
11783 (square-each (cdr numbers-list))))) ; next-step-expression
11784 @end group
11785
11786 @group
11787 (square-each '(1 2 3))
11788 @result{} (1 4 9)
11789 @end group
11790 @end smallexample
11791
11792 @need 1200
11793 @noindent
11794 If @code{numbers-list} is empty, do nothing. But if it has content,
11795 construct a list combining the square of the first number in the list
11796 with the result of the recursive call.
11797
11798 (The example follows the pattern exactly: @code{nil} is returned if
11799 the numbers' list is empty. In practice, you would write the
11800 conditional so it carries out the action when the numbers' list is not
11801 empty.)
11802
11803 The @code{print-elements-recursively} function (@pxref{Recursion with
11804 list, , Recursion with a List}) is another example of an @code{every}
11805 pattern, except in this case, rather than bring the results together
11806 using @code{cons}, we print each element of output.
11807
11808 @need 1250
11809 The @code{print-elements-recursively} function looks like this:
11810
11811 @smallexample
11812 @group
11813 (setq animals '(gazelle giraffe lion tiger))
11814 @end group
11815
11816 @group
11817 (defun print-elements-recursively (list)
11818 "Print each element of LIST on a line of its own.
11819 Uses recursion."
11820 (when list ; @r{do-again-test}
11821 (print (car list)) ; @r{body}
11822 (print-elements-recursively ; @r{recursive call}
11823 (cdr list)))) ; @r{next-step-expression}
11824
11825 (print-elements-recursively animals)
11826 @end group
11827 @end smallexample
11828
11829 @need 1500
11830 The pattern for @code{print-elements-recursively} is:
11831
11832 @itemize @bullet
11833 @item
11834 When the list is empty, do nothing.
11835 @item
11836 But when the list has at least one element,
11837 @itemize @minus
11838 @item
11839 act on the beginning of the list (the @sc{car} of the list),
11840 @item
11841 and make a recursive call on the rest (the @sc{cdr}) of the list.
11842 @end itemize
11843 @end itemize
11844
11845 @node Accumulate
11846 @unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11847 @cindex Accumulate, type of recursive pattern
11848 @cindex Recursive pattern: accumulate
11849
11850 Another recursive pattern is called the @code{accumulate} pattern. In
11851 the @code{accumulate} recursive pattern, an action is performed on
11852 every element of a list and the result of that action is accumulated
11853 with the results of performing the action on the other elements.
11854
11855 This is very like the `every' pattern using @code{cons}, except that
11856 @code{cons} is not used, but some other combiner.
11857
11858 @need 1500
11859 The pattern is:
11860
11861 @itemize @bullet
11862 @item
11863 If a list be empty, return zero or some other constant.
11864 @item
11865 Else, act on the beginning of the list (the @sc{car} of the list),
11866 @itemize @minus
11867 @item
11868 and combine that acted-on element, using @code{+} or
11869 some other combining function, with
11870 @item
11871 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11872 @end itemize
11873 @end itemize
11874
11875 @need 1500
11876 Here is an example:
11877
11878 @smallexample
11879 @group
11880 (defun add-elements (numbers-list)
11881 "Add the elements of NUMBERS-LIST together."
11882 (if (not numbers-list)
11883 0
11884 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11885 @end group
11886
11887 @group
11888 (add-elements '(1 2 3 4))
11889 @result{} 10
11890 @end group
11891 @end smallexample
11892
11893 @xref{Files List, , Making a List of Files}, for an example of the
11894 accumulate pattern.
11895
11896 @node Keep
11897 @unnumberedsubsubsec Recursive Pattern: @emph{keep}
11898 @cindex Keep, type of recursive pattern
11899 @cindex Recursive pattern: keep
11900
11901 A third recursive pattern is called the @code{keep} pattern.
11902 In the @code{keep} recursive pattern, each element of a list is tested;
11903 the element is acted on and the results are kept only if the element
11904 meets a criterion.
11905
11906 Again, this is very like the `every' pattern, except the element is
11907 skipped unless it meets a criterion.
11908
11909 @need 1500
11910 The pattern has three parts:
11911
11912 @itemize @bullet
11913 @item
11914 If a list be empty, return @code{nil}.
11915 @item
11916 Else, if the beginning of the list (the @sc{car} of the list) passes
11917 a test
11918 @itemize @minus
11919 @item
11920 act on that element and combine it, using @code{cons} with
11921 @item
11922 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11923 @end itemize
11924 @item
11925 Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11926 the test
11927 @itemize @minus
11928 @item
11929 skip on that element,
11930 @item
11931 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11932 @end itemize
11933 @end itemize
11934
11935 @need 1500
11936 Here is an example that uses @code{cond}:
11937
11938 @smallexample
11939 @group
11940 (defun keep-three-letter-words (word-list)
11941 "Keep three letter words in WORD-LIST."
11942 (cond
11943 ;; First do-again-test: stop-condition
11944 ((not word-list) nil)
11945
11946 ;; Second do-again-test: when to act
11947 ((eq 3 (length (symbol-name (car word-list))))
11948 ;; combine acted-on element with recursive call on shorter list
11949 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11950
11951 ;; Third do-again-test: when to skip element;
11952 ;; recursively call shorter list with next-step expression
11953 (t (keep-three-letter-words (cdr word-list)))))
11954 @end group
11955
11956 @group
11957 (keep-three-letter-words '(one two three four five six))
11958 @result{} (one two six)
11959 @end group
11960 @end smallexample
11961
11962 It goes without saying that you need not use @code{nil} as the test for
11963 when to stop; and you can, of course, combine these patterns.
11964
11965 @node No Deferment
11966 @subsection Recursion without Deferments
11967 @cindex Deferment in recursion
11968 @cindex Recursion without Deferments
11969
11970 Let's consider again what happens with the @code{triangle-recursively}
11971 function. We will find that the intermediate calculations are
11972 deferred until all can be done.
11973
11974 @need 800
11975 Here is the function definition:
11976
11977 @smallexample
11978 @group
11979 (defun triangle-recursively (number)
11980 "Return the sum of the numbers 1 through NUMBER inclusive.
11981 Uses recursion."
11982 (if (= number 1) ; @r{do-again-test}
11983 1 ; @r{then-part}
11984 (+ number ; @r{else-part}
11985 (triangle-recursively ; @r{recursive call}
11986 (1- number))))) ; @r{next-step-expression}
11987 @end group
11988 @end smallexample
11989
11990 What happens when we call this function with a argument of 7?
11991
11992 The first instance of the @code{triangle-recursively} function adds
11993 the number 7 to the value returned by a second instance of
11994 @code{triangle-recursively}, an instance that has been passed an
11995 argument of 6. That is to say, the first calculation is:
11996
11997 @smallexample
11998 (+ 7 (triangle-recursively 6))
11999 @end smallexample
12000
12001 @noindent
12002 The first instance of @code{triangle-recursively}---you may want to
12003 think of it as a little robot---cannot complete its job. It must hand
12004 off the calculation for @code{(triangle-recursively 6)} to a second
12005 instance of the program, to a second robot. This second individual is
12006 completely different from the first one; it is, in the jargon, a
12007 `different instantiation'. Or, put another way, it is a different
12008 robot. It is the same model as the first; it calculates triangle
12009 numbers recursively; but it has a different serial number.
12010
12011 And what does @code{(triangle-recursively 6)} return? It returns the
12012 number 6 added to the value returned by evaluating
12013 @code{triangle-recursively} with an argument of 5. Using the robot
12014 metaphor, it asks yet another robot to help it.
12015
12016 @need 800
12017 Now the total is:
12018
12019 @smallexample
12020 (+ 7 6 (triangle-recursively 5))
12021 @end smallexample
12022
12023 @need 800
12024 And what happens next?
12025
12026 @smallexample
12027 (+ 7 6 5 (triangle-recursively 4))
12028 @end smallexample
12029
12030 Each time @code{triangle-recursively} is called, except for the last
12031 time, it creates another instance of the program---another robot---and
12032 asks it to make a calculation.
12033
12034 @need 800
12035 Eventually, the full addition is set up and performed:
12036
12037 @smallexample
12038 (+ 7 6 5 4 3 2 1)
12039 @end smallexample
12040
12041 This design for the function defers the calculation of the first step
12042 until the second can be done, and defers that until the third can be
12043 done, and so on. Each deferment means the computer must remember what
12044 is being waited on. This is not a problem when there are only a few
12045 steps, as in this example. But it can be a problem when there are
12046 more steps.
12047
12048 @node No deferment solution
12049 @subsection No Deferment Solution
12050 @cindex No deferment solution
12051 @cindex Defermentless solution
12052 @cindex Solution without deferment
12053
12054 The solution to the problem of deferred operations is to write in a
12055 manner that does not defer operations@footnote{The phrase @dfn{tail
12056 recursive} is used to describe such a process, one that uses
12057 `constant space'.}. This requires
12058 writing to a different pattern, often one that involves writing two
12059 function definitions, an `initialization' function and a `helper'
12060 function.
12061
12062 The `initialization' function sets up the job; the `helper' function
12063 does the work.
12064
12065 @need 1200
12066 Here are the two function definitions for adding up numbers. They are
12067 so simple, I find them hard to understand.
12068
12069 @smallexample
12070 @group
12071 (defun triangle-initialization (number)
12072 "Return the sum of the numbers 1 through NUMBER inclusive.
12073 This is the `initialization' component of a two function
12074 duo that uses recursion."
12075 (triangle-recursive-helper 0 0 number))
12076 @end group
12077 @end smallexample
12078
12079 @smallexample
12080 @group
12081 (defun triangle-recursive-helper (sum counter number)
12082 "Return SUM, using COUNTER, through NUMBER inclusive.
12083 This is the `helper' component of a two function duo
12084 that uses recursion."
12085 (if (> counter number)
12086 sum
12087 (triangle-recursive-helper (+ sum counter) ; @r{sum}
12088 (1+ counter) ; @r{counter}
12089 number))) ; @r{number}
12090 @end group
12091 @end smallexample
12092
12093 @need 1250
12094 Install both function definitions by evaluating them, then call
12095 @code{triangle-initialization} with 2 rows:
12096
12097 @smallexample
12098 @group
12099 (triangle-initialization 2)
12100 @result{} 3
12101 @end group
12102 @end smallexample
12103
12104 The `initialization' function calls the first instance of the `helper'
12105 function with three arguments: zero, zero, and a number which is the
12106 number of rows in the triangle.
12107
12108 The first two arguments passed to the `helper' function are
12109 initialization values. These values are changed when
12110 @code{triangle-recursive-helper} invokes new instances.@footnote{The
12111 jargon is mildly confusing: @code{triangle-recursive-helper} uses a
12112 process that is iterative in a procedure that is recursive. The
12113 process is called iterative because the computer need only record the
12114 three values, @code{sum}, @code{counter}, and @code{number}; the
12115 procedure is recursive because the function `calls itself'. On the
12116 other hand, both the process and the procedure used by
12117 @code{triangle-recursively} are called recursive. The word
12118 `recursive' has different meanings in the two contexts.}
12119
12120 Let's see what happens when we have a triangle that has one row. (This
12121 triangle will have one pebble in it!)
12122
12123 @need 1200
12124 @code{triangle-initialization} will call its helper with
12125 the arguments @w{@code{0 0 1}}. That function will run the conditional
12126 test whether @code{(> counter number)}:
12127
12128 @smallexample
12129 (> 0 1)
12130 @end smallexample
12131
12132 @need 1200
12133 @noindent
12134 and find that the result is false, so it will invoke
12135 the else-part of the @code{if} clause:
12136
12137 @smallexample
12138 @group
12139 (triangle-recursive-helper
12140 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12141 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12142 number) ; @r{number stays the same}
12143 @end group
12144 @end smallexample
12145
12146 @need 800
12147 @noindent
12148 which will first compute:
12149
12150 @smallexample
12151 @group
12152 (triangle-recursive-helper (+ 0 0) ; @r{sum}
12153 (1+ 0) ; @r{counter}
12154 1) ; @r{number}
12155 @exdent which is:
12156
12157 (triangle-recursive-helper 0 1 1)
12158 @end group
12159 @end smallexample
12160
12161 Again, @code{(> counter number)} will be false, so again, the Lisp
12162 interpreter will evaluate @code{triangle-recursive-helper}, creating a
12163 new instance with new arguments.
12164
12165 @need 800
12166 This new instance will be;
12167
12168 @smallexample
12169 @group
12170 (triangle-recursive-helper
12171 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12172 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12173 number) ; @r{number stays the same}
12174
12175 @exdent which is:
12176
12177 (triangle-recursive-helper 1 2 1)
12178 @end group
12179 @end smallexample
12180
12181 In this case, the @code{(> counter number)} test will be true! So the
12182 instance will return the value of the sum, which will be 1, as
12183 expected.
12184
12185 Now, let's pass @code{triangle-initialization} an argument
12186 of 2, to find out how many pebbles there are in a triangle with two rows.
12187
12188 That function calls @code{(triangle-recursive-helper 0 0 2)}.
12189
12190 @need 800
12191 In stages, the instances called will be:
12192
12193 @smallexample
12194 @group
12195 @r{sum counter number}
12196 (triangle-recursive-helper 0 1 2)
12197
12198 (triangle-recursive-helper 1 2 2)
12199
12200 (triangle-recursive-helper 3 3 2)
12201 @end group
12202 @end smallexample
12203
12204 When the last instance is called, the @code{(> counter number)} test
12205 will be true, so the instance will return the value of @code{sum},
12206 which will be 3.
12207
12208 This kind of pattern helps when you are writing functions that can use
12209 many resources in a computer.
12210
12211 @need 1500
12212 @node Looping exercise
12213 @section Looping Exercise
12214
12215 @itemize @bullet
12216 @item
12217 Write a function similar to @code{triangle} in which each row has a
12218 value which is the square of the row number. Use a @code{while} loop.
12219
12220 @item
12221 Write a function similar to @code{triangle} that multiplies instead of
12222 adds the values.
12223
12224 @item
12225 Rewrite these two functions recursively. Rewrite these functions
12226 using @code{cond}.
12227
12228 @c comma in printed title causes problem in Info cross reference
12229 @item
12230 Write a function for Texinfo mode that creates an index entry at the
12231 beginning of a paragraph for every @samp{@@dfn} within the paragraph.
12232 (In a Texinfo file, @samp{@@dfn} marks a definition. This book is
12233 written in Texinfo.)
12234
12235 Many of the functions you will need are described in two of the
12236 previous chapters, @ref{Cutting & Storing Text, , Cutting and Storing
12237 Text}, and @ref{Yanking, , Yanking Text Back}. If you use
12238 @code{forward-paragraph} to put the index entry at the beginning of
12239 the paragraph, you will have to use @w{@kbd{C-h f}}
12240 (@code{describe-function}) to find out how to make the command go
12241 backwards.
12242
12243 For more information, see
12244 @ifinfo
12245 @ref{Indicating, , Indicating Definitions, texinfo}.
12246 @end ifinfo
12247 @ifhtml
12248 @ref{Indicating, , Indicating, texinfo, Texinfo Manual}, which goes to
12249 a Texinfo manual in the current directory. Or, if you are on the
12250 Internet, see
12251 @uref{http://www.gnu.org/software/texinfo/manual/texinfo/}
12252 @end ifhtml
12253 @iftex
12254 ``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
12255 Documentation Format}.
12256 @end iftex
12257 @end itemize
12258
12259 @node Regexp Search
12260 @chapter Regular Expression Searches
12261 @cindex Searches, illustrating
12262 @cindex Regular expression searches
12263 @cindex Patterns, searching for
12264 @cindex Motion by sentence and paragraph
12265 @cindex Sentences, movement by
12266 @cindex Paragraphs, movement by
12267
12268 Regular expression searches are used extensively in GNU Emacs. The
12269 two functions, @code{forward-sentence} and @code{forward-paragraph},
12270 illustrate these searches well. They use regular expressions to find
12271 where to move point. The phrase `regular expression' is often written
12272 as `regexp'.
12273
12274 Regular expression searches are described in @ref{Regexp Search, ,
12275 Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
12276 @ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
12277 Manual}. In writing this chapter, I am presuming that you have at
12278 least a mild acquaintance with them. The major point to remember is
12279 that regular expressions permit you to search for patterns as well as
12280 for literal strings of characters. For example, the code in
12281 @code{forward-sentence} searches for the pattern of possible
12282 characters that could mark the end of a sentence, and moves point to
12283 that spot.
12284
12285 Before looking at the code for the @code{forward-sentence} function, it
12286 is worth considering what the pattern that marks the end of a sentence
12287 must be. The pattern is discussed in the next section; following that
12288 is a description of the regular expression search function,
12289 @code{re-search-forward}. The @code{forward-sentence} function
12290 is described in the section following. Finally, the
12291 @code{forward-paragraph} function is described in the last section of
12292 this chapter. @code{forward-paragraph} is a complex function that
12293 introduces several new features.
12294
12295 @menu
12296 * sentence-end:: The regular expression for @code{sentence-end}.
12297 * re-search-forward:: Very similar to @code{search-forward}.
12298 * forward-sentence:: A straightforward example of regexp search.
12299 * forward-paragraph:: A somewhat complex example.
12300 * etags:: How to create your own @file{TAGS} table.
12301 * Regexp Review::
12302 * re-search Exercises::
12303 @end menu
12304
12305 @node sentence-end
12306 @section The Regular Expression for @code{sentence-end}
12307 @findex sentence-end
12308
12309 The symbol @code{sentence-end} is bound to the pattern that marks the
12310 end of a sentence. What should this regular expression be?
12311
12312 Clearly, a sentence may be ended by a period, a question mark, or an
12313 exclamation mark. Indeed, in English, only clauses that end with one
12314 of those three characters should be considered the end of a sentence.
12315 This means that the pattern should include the character set:
12316
12317 @smallexample
12318 [.?!]
12319 @end smallexample
12320
12321 However, we do not want @code{forward-sentence} merely to jump to a
12322 period, a question mark, or an exclamation mark, because such a character
12323 might be used in the middle of a sentence. A period, for example, is
12324 used after abbreviations. So other information is needed.
12325
12326 According to convention, you type two spaces after every sentence, but
12327 only one space after a period, a question mark, or an exclamation mark in
12328 the body of a sentence. So a period, a question mark, or an exclamation
12329 mark followed by two spaces is a good indicator of an end of sentence.
12330 However, in a file, the two spaces may instead be a tab or the end of a
12331 line. This means that the regular expression should include these three
12332 items as alternatives.
12333
12334 @need 800
12335 This group of alternatives will look like this:
12336
12337 @smallexample
12338 @group
12339 \\($\\| \\| \\)
12340 ^ ^^
12341 TAB SPC
12342 @end group
12343 @end smallexample
12344
12345 @noindent
12346 Here, @samp{$} indicates the end of the line, and I have pointed out
12347 where the tab and two spaces are inserted in the expression. Both are
12348 inserted by putting the actual characters into the expression.
12349
12350 Two backslashes, @samp{\\}, are required before the parentheses and
12351 vertical bars: the first backslash quotes the following backslash in
12352 Emacs; and the second indicates that the following character, the
12353 parenthesis or the vertical bar, is special.
12354
12355 @need 1000
12356 Also, a sentence may be followed by one or more carriage returns, like
12357 this:
12358
12359 @smallexample
12360 @group
12361 [
12362 ]*
12363 @end group
12364 @end smallexample
12365
12366 @noindent
12367 Like tabs and spaces, a carriage return is inserted into a regular
12368 expression by inserting it literally. The asterisk indicates that the
12369 @key{RET} is repeated zero or more times.
12370
12371 But a sentence end does not consist only of a period, a question mark or
12372 an exclamation mark followed by appropriate space: a closing quotation
12373 mark or a closing brace of some kind may precede the space. Indeed more
12374 than one such mark or brace may precede the space. These require a
12375 expression that looks like this:
12376
12377 @smallexample
12378 []\"')@}]*
12379 @end smallexample
12380
12381 In this expression, the first @samp{]} is the first character in the
12382 expression; the second character is @samp{"}, which is preceded by a
12383 @samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
12384 three characters are @samp{'}, @samp{)}, and @samp{@}}.
12385
12386 All this suggests what the regular expression pattern for matching the
12387 end of a sentence should be; and, indeed, if we evaluate
12388 @code{sentence-end} we find that it returns the following value:
12389
12390 @smallexample
12391 @group
12392 sentence-end
12393 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
12394 ]*"
12395 @end group
12396 @end smallexample
12397
12398 @noindent
12399 (Well, not in GNU Emacs 22; that is because of an effort to make the
12400 process simpler and to handle more glyphs and languages. When the
12401 value of @code{sentence-end} is @code{nil}, then use the value defined
12402 by the function @code{sentence-end}. (Here is a use of the difference
12403 between a value and a function in Emacs Lisp.) The function returns a
12404 value constructed from the variables @code{sentence-end-base},
12405 @code{sentence-end-double-space}, @code{sentence-end-without-period},
12406 and @code{sentence-end-without-space}. The critical variable is
12407 @code{sentence-end-base}; its global value is similar to the one
12408 described above but it also contains two additional quotation marks.
12409 These have differing degrees of curliness. The
12410 @code{sentence-end-without-period} variable, when true, tells Emacs
12411 that a sentence may end without a period, such as text in Thai.)
12412
12413 @ignore
12414 @noindent
12415 (Note that here the @key{TAB}, two spaces, and @key{RET} are shown
12416 literally in the pattern.)
12417
12418 This regular expression can be deciphered as follows:
12419
12420 @table @code
12421 @item [.?!]
12422 The first part of the pattern is the three characters, a period, a question
12423 mark and an exclamation mark, within square brackets. The pattern must
12424 begin with one or other of these characters.
12425
12426 @item []\"')@}]*
12427 The second part of the pattern is the group of closing braces and
12428 quotation marks, which can appear zero or more times. These may follow
12429 the period, question mark or exclamation mark. In a regular expression,
12430 the backslash, @samp{\}, followed by the double quotation mark,
12431 @samp{"}, indicates the class of string-quote characters. Usually, the
12432 double quotation mark is the only character in this class. The
12433 asterisk, @samp{*}, indicates that the items in the previous group (the
12434 group surrounded by square brackets, @samp{[]}) may be repeated zero or
12435 more times.
12436
12437 @item \\($\\| \\| \\)
12438 The third part of the pattern is one or other of: either the end of a
12439 line, or two blank spaces, or a tab. The double back-slashes are used
12440 to prevent Emacs from reading the parentheses and vertical bars as part
12441 of the search pattern; the parentheses are used to mark the group and
12442 the vertical bars are used to indicated that the patterns to either side
12443 of them are alternatives. The dollar sign is used to indicate the end
12444 of a line and both the two spaces and the tab are each inserted as is to
12445 indicate what they are.
12446
12447 @item [@key{RET}]*
12448 Finally, the last part of the pattern indicates that the end of the line
12449 or the whitespace following the period, question mark or exclamation
12450 mark may, but need not, be followed by one or more carriage returns. In
12451 the pattern, the carriage return is inserted as an actual carriage
12452 return between square brackets but here it is shown as @key{RET}.
12453 @end table
12454 @end ignore
12455
12456 @node re-search-forward
12457 @section The @code{re-search-forward} Function
12458 @findex re-search-forward
12459
12460 The @code{re-search-forward} function is very like the
12461 @code{search-forward} function. (@xref{search-forward, , The
12462 @code{search-forward} Function}.)
12463
12464 @code{re-search-forward} searches for a regular expression. If the
12465 search is successful, it leaves point immediately after the last
12466 character in the target. If the search is backwards, it leaves point
12467 just before the first character in the target. You may tell
12468 @code{re-search-forward} to return @code{t} for true. (Moving point
12469 is therefore a `side effect'.)
12470
12471 Like @code{search-forward}, the @code{re-search-forward} function takes
12472 four arguments:
12473
12474 @enumerate
12475 @item
12476 The first argument is the regular expression that the function searches
12477 for. The regular expression will be a string between quotation marks.
12478
12479 @item
12480 The optional second argument limits how far the function will search; it is a
12481 bound, which is specified as a position in the buffer.
12482
12483 @item
12484 The optional third argument specifies how the function responds to
12485 failure: @code{nil} as the third argument causes the function to
12486 signal an error (and print a message) when the search fails; any other
12487 value causes it to return @code{nil} if the search fails and @code{t}
12488 if the search succeeds.
12489
12490 @item
12491 The optional fourth argument is the repeat count. A negative repeat
12492 count causes @code{re-search-forward} to search backwards.
12493 @end enumerate
12494
12495 @need 800
12496 The template for @code{re-search-forward} looks like this:
12497
12498 @smallexample
12499 @group
12500 (re-search-forward "@var{regular-expression}"
12501 @var{limit-of-search}
12502 @var{what-to-do-if-search-fails}
12503 @var{repeat-count})
12504 @end group
12505 @end smallexample
12506
12507 The second, third, and fourth arguments are optional. However, if you
12508 want to pass a value to either or both of the last two arguments, you
12509 must also pass a value to all the preceding arguments. Otherwise, the
12510 Lisp interpreter will mistake which argument you are passing the value
12511 to.
12512
12513 @need 1200
12514 In the @code{forward-sentence} function, the regular expression will be
12515 the value of the variable @code{sentence-end}. In simple form, that is:
12516
12517 @smallexample
12518 @group
12519 "[.?!][]\"')@}]*\\($\\| \\| \\)[
12520 ]*"
12521 @end group
12522 @end smallexample
12523
12524 @noindent
12525 The limit of the search will be the end of the paragraph (since a
12526 sentence cannot go beyond a paragraph). If the search fails, the
12527 function will return @code{nil}; and the repeat count will be provided
12528 by the argument to the @code{forward-sentence} function.
12529
12530 @node forward-sentence
12531 @section @code{forward-sentence}
12532 @findex forward-sentence
12533
12534 The command to move the cursor forward a sentence is a straightforward
12535 illustration of how to use regular expression searches in Emacs Lisp.
12536 Indeed, the function looks longer and more complicated than it is; this
12537 is because the function is designed to go backwards as well as forwards;
12538 and, optionally, over more than one sentence. The function is usually
12539 bound to the key command @kbd{M-e}.
12540
12541 @menu
12542 * Complete forward-sentence::
12543 * fwd-sentence while loops:: Two @code{while} loops.
12544 * fwd-sentence re-search:: A regular expression search.
12545 @end menu
12546
12547 @ifnottex
12548 @node Complete forward-sentence
12549 @unnumberedsubsec Complete @code{forward-sentence} function definition
12550 @end ifnottex
12551
12552 @need 1250
12553 Here is the code for @code{forward-sentence}:
12554
12555 @c in GNU Emacs 22
12556 @smallexample
12557 @group
12558 (defun forward-sentence (&optional arg)
12559 "Move forward to next `sentence-end'. With argument, repeat.
12560 With negative argument, move backward repeatedly to `sentence-beginning'.
12561
12562 The variable `sentence-end' is a regular expression that matches ends of
12563 sentences. Also, every paragraph boundary terminates sentences as well."
12564 @end group
12565 @group
12566 (interactive "p")
12567 (or arg (setq arg 1))
12568 (let ((opoint (point))
12569 (sentence-end (sentence-end)))
12570 (while (< arg 0)
12571 (let ((pos (point))
12572 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12573 (if (and (re-search-backward sentence-end par-beg t)
12574 (or (< (match-end 0) pos)
12575 (re-search-backward sentence-end par-beg t)))
12576 (goto-char (match-end 0))
12577 (goto-char par-beg)))
12578 (setq arg (1+ arg)))
12579 @end group
12580 @group
12581 (while (> arg 0)
12582 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12583 (if (re-search-forward sentence-end par-end t)
12584 (skip-chars-backward " \t\n")
12585 (goto-char par-end)))
12586 (setq arg (1- arg)))
12587 (constrain-to-field nil opoint t)))
12588 @end group
12589 @end smallexample
12590
12591 @ignore
12592 GNU Emacs 21
12593 @smallexample
12594 @group
12595 (defun forward-sentence (&optional arg)
12596 "Move forward to next sentence-end. With argument, repeat.
12597 With negative argument, move backward repeatedly to sentence-beginning.
12598 Sentence ends are identified by the value of sentence-end
12599 treated as a regular expression. Also, every paragraph boundary
12600 terminates sentences as well."
12601 @end group
12602 @group
12603 (interactive "p")
12604 (or arg (setq arg 1))
12605 (while (< arg 0)
12606 (let ((par-beg
12607 (save-excursion (start-of-paragraph-text) (point))))
12608 (if (re-search-backward
12609 (concat sentence-end "[^ \t\n]") par-beg t)
12610 (goto-char (1- (match-end 0)))
12611 (goto-char par-beg)))
12612 (setq arg (1+ arg)))
12613 (while (> arg 0)
12614 (let ((par-end
12615 (save-excursion (end-of-paragraph-text) (point))))
12616 (if (re-search-forward sentence-end par-end t)
12617 (skip-chars-backward " \t\n")
12618 (goto-char par-end)))
12619 (setq arg (1- arg))))
12620 @end group
12621 @end smallexample
12622 @end ignore
12623
12624 The function looks long at first sight and it is best to look at its
12625 skeleton first, and then its muscle. The way to see the skeleton is to
12626 look at the expressions that start in the left-most columns:
12627
12628 @smallexample
12629 @group
12630 (defun forward-sentence (&optional arg)
12631 "@var{documentation}@dots{}"
12632 (interactive "p")
12633 (or arg (setq arg 1))
12634 (let ((opoint (point)) (sentence-end (sentence-end)))
12635 (while (< arg 0)
12636 (let ((pos (point))
12637 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12638 @var{rest-of-body-of-while-loop-when-going-backwards}
12639 (while (> arg 0)
12640 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12641 @var{rest-of-body-of-while-loop-when-going-forwards}
12642 @var{handle-forms-and-equivalent}
12643 @end group
12644 @end smallexample
12645
12646 This looks much simpler! The function definition consists of
12647 documentation, an @code{interactive} expression, an @code{or}
12648 expression, a @code{let} expression, and @code{while} loops.
12649
12650 Let's look at each of these parts in turn.
12651
12652 We note that the documentation is thorough and understandable.
12653
12654 The function has an @code{interactive "p"} declaration. This means
12655 that the processed prefix argument, if any, is passed to the
12656 function as its argument. (This will be a number.) If the function
12657 is not passed an argument (it is optional) then the argument
12658 @code{arg} will be bound to 1.
12659
12660 When @code{forward-sentence} is called non-interactively without an
12661 argument, @code{arg} is bound to @code{nil}. The @code{or} expression
12662 handles this. What it does is either leave the value of @code{arg} as
12663 it is, but only if @code{arg} is bound to a value; or it sets the
12664 value of @code{arg} to 1, in the case when @code{arg} is bound to
12665 @code{nil}.
12666
12667 Next is a @code{let}. That specifies the values of two local
12668 variables, @code{point} and @code{sentence-end}. The local value of
12669 point, from before the search, is used in the
12670 @code{constrain-to-field} function which handles forms and
12671 equivalents. The @code{sentence-end} variable is set by the
12672 @code{sentence-end} function.
12673
12674 @node fwd-sentence while loops
12675 @unnumberedsubsec The @code{while} loops
12676
12677 Two @code{while} loops follow. The first @code{while} has a
12678 true-or-false-test that tests true if the prefix argument for
12679 @code{forward-sentence} is a negative number. This is for going
12680 backwards. The body of this loop is similar to the body of the second
12681 @code{while} clause, but it is not exactly the same. We will skip
12682 this @code{while} loop and concentrate on the second @code{while}
12683 loop.
12684
12685 @need 1500
12686 The second @code{while} loop is for moving point forward. Its skeleton
12687 looks like this:
12688
12689 @smallexample
12690 @group
12691 (while (> arg 0) ; @r{true-or-false-test}
12692 (let @var{varlist}
12693 (if (@var{true-or-false-test})
12694 @var{then-part}
12695 @var{else-part}
12696 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
12697 @end group
12698 @end smallexample
12699
12700 The @code{while} loop is of the decrementing kind.
12701 (@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
12702 has a true-or-false-test that tests true so long as the counter (in
12703 this case, the variable @code{arg}) is greater than zero; and it has a
12704 decrementer that subtracts 1 from the value of the counter every time
12705 the loop repeats.
12706
12707 If no prefix argument is given to @code{forward-sentence}, which is
12708 the most common way the command is used, this @code{while} loop will
12709 run once, since the value of @code{arg} will be 1.
12710
12711 The body of the @code{while} loop consists of a @code{let} expression,
12712 which creates and binds a local variable, and has, as its body, an
12713 @code{if} expression.
12714
12715 @need 1250
12716 The body of the @code{while} loop looks like this:
12717
12718 @smallexample
12719 @group
12720 (let ((par-end
12721 (save-excursion (end-of-paragraph-text) (point))))
12722 (if (re-search-forward sentence-end par-end t)
12723 (skip-chars-backward " \t\n")
12724 (goto-char par-end)))
12725 @end group
12726 @end smallexample
12727
12728 The @code{let} expression creates and binds the local variable
12729 @code{par-end}. As we shall see, this local variable is designed to
12730 provide a bound or limit to the regular expression search. If the
12731 search fails to find a proper sentence ending in the paragraph, it will
12732 stop on reaching the end of the paragraph.
12733
12734 But first, let us examine how @code{par-end} is bound to the value of
12735 the end of the paragraph. What happens is that the @code{let} sets the
12736 value of @code{par-end} to the value returned when the Lisp interpreter
12737 evaluates the expression
12738
12739 @smallexample
12740 @group
12741 (save-excursion (end-of-paragraph-text) (point))
12742 @end group
12743 @end smallexample
12744
12745 @noindent
12746 In this expression, @code{(end-of-paragraph-text)} moves point to the
12747 end of the paragraph, @code{(point)} returns the value of point, and then
12748 @code{save-excursion} restores point to its original position. Thus,
12749 the @code{let} binds @code{par-end} to the value returned by the
12750 @code{save-excursion} expression, which is the position of the end of
12751 the paragraph. (The @code{end-of-paragraph-text} function uses
12752 @code{forward-paragraph}, which we will discuss shortly.)
12753
12754 @need 1200
12755 Emacs next evaluates the body of the @code{let}, which is an @code{if}
12756 expression that looks like this:
12757
12758 @smallexample
12759 @group
12760 (if (re-search-forward sentence-end par-end t) ; @r{if-part}
12761 (skip-chars-backward " \t\n") ; @r{then-part}
12762 (goto-char par-end))) ; @r{else-part}
12763 @end group
12764 @end smallexample
12765
12766 The @code{if} tests whether its first argument is true and if so,
12767 evaluates its then-part; otherwise, the Emacs Lisp interpreter
12768 evaluates the else-part. The true-or-false-test of the @code{if}
12769 expression is the regular expression search.
12770
12771 It may seem odd to have what looks like the `real work' of
12772 the @code{forward-sentence} function buried here, but this is a common
12773 way this kind of operation is carried out in Lisp.
12774
12775 @node fwd-sentence re-search
12776 @unnumberedsubsec The regular expression search
12777
12778 The @code{re-search-forward} function searches for the end of the
12779 sentence, that is, for the pattern defined by the @code{sentence-end}
12780 regular expression. If the pattern is found---if the end of the sentence is
12781 found---then the @code{re-search-forward} function does two things:
12782
12783 @enumerate
12784 @item
12785 The @code{re-search-forward} function carries out a side effect, which
12786 is to move point to the end of the occurrence found.
12787
12788 @item
12789 The @code{re-search-forward} function returns a value of true. This is
12790 the value received by the @code{if}, and means that the search was
12791 successful.
12792 @end enumerate
12793
12794 @noindent
12795 The side effect, the movement of point, is completed before the
12796 @code{if} function is handed the value returned by the successful
12797 conclusion of the search.
12798
12799 When the @code{if} function receives the value of true from a successful
12800 call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12801 which is the expression @code{(skip-chars-backward " \t\n")}. This
12802 expression moves backwards over any blank spaces, tabs or carriage
12803 returns until a printed character is found and then leaves point after
12804 the character. Since point has already been moved to the end of the
12805 pattern that marks the end of the sentence, this action leaves point
12806 right after the closing printed character of the sentence, which is
12807 usually a period.
12808
12809 On the other hand, if the @code{re-search-forward} function fails to
12810 find a pattern marking the end of the sentence, the function returns
12811 false. The false then causes the @code{if} to evaluate its third
12812 argument, which is @code{(goto-char par-end)}: it moves point to the
12813 end of the paragraph.
12814
12815 (And if the text is in a form or equivalent, and point may not move
12816 fully, then the @code{constrain-to-field} function comes into play.)
12817
12818 Regular expression searches are exceptionally useful and the pattern
12819 illustrated by @code{re-search-forward}, in which the search is the
12820 test of an @code{if} expression, is handy. You will see or write code
12821 incorporating this pattern often.
12822
12823 @node forward-paragraph
12824 @section @code{forward-paragraph}: a Goldmine of Functions
12825 @findex forward-paragraph
12826
12827 @ignore
12828 @c in GNU Emacs 22
12829 (defun forward-paragraph (&optional arg)
12830 "Move forward to end of paragraph.
12831 With argument ARG, do it ARG times;
12832 a negative argument ARG = -N means move backward N paragraphs.
12833
12834 A line which `paragraph-start' matches either separates paragraphs
12835 \(if `paragraph-separate' matches it also) or is the first line of a paragraph.
12836 A paragraph end is the beginning of a line which is not part of the paragraph
12837 to which the end of the previous line belongs, or the end of the buffer.
12838 Returns the count of paragraphs left to move."
12839 (interactive "p")
12840 (or arg (setq arg 1))
12841 (let* ((opoint (point))
12842 (fill-prefix-regexp
12843 (and fill-prefix (not (equal fill-prefix ""))
12844 (not paragraph-ignore-fill-prefix)
12845 (regexp-quote fill-prefix)))
12846 ;; Remove ^ from paragraph-start and paragraph-sep if they are there.
12847 ;; These regexps shouldn't be anchored, because we look for them
12848 ;; starting at the left-margin. This allows paragraph commands to
12849 ;; work normally with indented text.
12850 ;; This hack will not find problem cases like "whatever\\|^something".
12851 (parstart (if (and (not (equal "" paragraph-start))
12852 (equal ?^ (aref paragraph-start 0)))
12853 (substring paragraph-start 1)
12854 paragraph-start))
12855 (parsep (if (and (not (equal "" paragraph-separate))
12856 (equal ?^ (aref paragraph-separate 0)))
12857 (substring paragraph-separate 1)
12858 paragraph-separate))
12859 (parsep
12860 (if fill-prefix-regexp
12861 (concat parsep "\\|"
12862 fill-prefix-regexp "[ \t]*$")
12863 parsep))
12864 ;; This is used for searching.
12865 (sp-parstart (concat "^[ \t]*\\(?:" parstart "\\|" parsep "\\)"))
12866 start found-start)
12867 (while (and (< arg 0) (not (bobp)))
12868 (if (and (not (looking-at parsep))
12869 (re-search-backward "^\n" (max (1- (point)) (point-min)) t)
12870 (looking-at parsep))
12871 (setq arg (1+ arg))
12872 (setq start (point))
12873 ;; Move back over paragraph-separating lines.
12874 (forward-char -1) (beginning-of-line)
12875 (while (and (not (bobp))
12876 (progn (move-to-left-margin)
12877 (looking-at parsep)))
12878 (forward-line -1))
12879 (if (bobp)
12880 nil
12881 (setq arg (1+ arg))
12882 ;; Go to end of the previous (non-separating) line.
12883 (end-of-line)
12884 ;; Search back for line that starts or separates paragraphs.
12885 (if (if fill-prefix-regexp
12886 ;; There is a fill prefix; it overrides parstart.
12887 (let (multiple-lines)
12888 (while (and (progn (beginning-of-line) (not (bobp)))
12889 (progn (move-to-left-margin)
12890 (not (looking-at parsep)))
12891 (looking-at fill-prefix-regexp))
12892 (unless (= (point) start)
12893 (setq multiple-lines t))
12894 (forward-line -1))
12895 (move-to-left-margin)
12896 ;; This deleted code caused a long hanging-indent line
12897 ;; not to be filled together with the following lines.
12898 ;; ;; Don't move back over a line before the paragraph
12899 ;; ;; which doesn't start with fill-prefix
12900 ;; ;; unless that is the only line we've moved over.
12901 ;; (and (not (looking-at fill-prefix-regexp))
12902 ;; multiple-lines
12903 ;; (forward-line 1))
12904 (not (bobp)))
12905 (while (and (re-search-backward sp-parstart nil 1)
12906 (setq found-start t)
12907 ;; Found a candidate, but need to check if it is a
12908 ;; REAL parstart.
12909 (progn (setq start (point))
12910 (move-to-left-margin)
12911 (not (looking-at parsep)))
12912 (not (and (looking-at parstart)
12913 (or (not use-hard-newlines)
12914 (bobp)
12915 (get-text-property
12916 (1- start) 'hard)))))
12917 (setq found-start nil)
12918 (goto-char start))
12919 found-start)
12920 ;; Found one.
12921 (progn
12922 ;; Move forward over paragraph separators.
12923 ;; We know this cannot reach the place we started
12924 ;; because we know we moved back over a non-separator.
12925 (while (and (not (eobp))
12926 (progn (move-to-left-margin)
12927 (looking-at parsep)))
12928 (forward-line 1))
12929 ;; If line before paragraph is just margin, back up to there.
12930 (end-of-line 0)
12931 (if (> (current-column) (current-left-margin))
12932 (forward-char 1)
12933 (skip-chars-backward " \t")
12934 (if (not (bolp))
12935 (forward-line 1))))
12936 ;; No starter or separator line => use buffer beg.
12937 (goto-char (point-min))))))
12938
12939 (while (and (> arg 0) (not (eobp)))
12940 ;; Move forward over separator lines...
12941 (while (and (not (eobp))
12942 (progn (move-to-left-margin) (not (eobp)))
12943 (looking-at parsep))
12944 (forward-line 1))
12945 (unless (eobp) (setq arg (1- arg)))
12946 ;; ... and one more line.
12947 (forward-line 1)
12948 (if fill-prefix-regexp
12949 ;; There is a fill prefix; it overrides parstart.
12950 (while (and (not (eobp))
12951 (progn (move-to-left-margin) (not (eobp)))
12952 (not (looking-at parsep))
12953 (looking-at fill-prefix-regexp))
12954 (forward-line 1))
12955 (while (and (re-search-forward sp-parstart nil 1)
12956 (progn (setq start (match-beginning 0))
12957 (goto-char start)
12958 (not (eobp)))
12959 (progn (move-to-left-margin)
12960 (not (looking-at parsep)))
12961 (or (not (looking-at parstart))
12962 (and use-hard-newlines
12963 (not (get-text-property (1- start) 'hard)))))
12964 (forward-char 1))
12965 (if (< (point) (point-max))
12966 (goto-char start))))
12967 (constrain-to-field nil opoint t)
12968 ;; Return the number of steps that could not be done.
12969 arg))
12970 @end ignore
12971
12972 The @code{forward-paragraph} function moves point forward to the end
12973 of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12974 number of functions that are important in themselves, including
12975 @code{let*}, @code{match-beginning}, and @code{looking-at}.
12976
12977 The function definition for @code{forward-paragraph} is considerably
12978 longer than the function definition for @code{forward-sentence}
12979 because it works with a paragraph, each line of which may begin with a
12980 fill prefix.
12981
12982 A fill prefix consists of a string of characters that are repeated at
12983 the beginning of each line. For example, in Lisp code, it is a
12984 convention to start each line of a paragraph-long comment with
12985 @samp{;;; }. In Text mode, four blank spaces make up another common
12986 fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
12987 emacs, The GNU Emacs Manual}, for more information about fill
12988 prefixes.)
12989
12990 The existence of a fill prefix means that in addition to being able to
12991 find the end of a paragraph whose lines begin on the left-most
12992 column, the @code{forward-paragraph} function must be able to find the
12993 end of a paragraph when all or many of the lines in the buffer begin
12994 with the fill prefix.
12995
12996 Moreover, it is sometimes practical to ignore a fill prefix that
12997 exists, especially when blank lines separate paragraphs.
12998 This is an added complication.
12999
13000 @menu
13001 * forward-paragraph in brief:: Key parts of the function definition.
13002 * fwd-para let:: The @code{let*} expression.
13003 * fwd-para while:: The forward motion @code{while} loop.
13004 @end menu
13005
13006 @ifnottex
13007 @node forward-paragraph in brief
13008 @unnumberedsubsec Shortened @code{forward-paragraph} function definition
13009 @end ifnottex
13010
13011 Rather than print all of the @code{forward-paragraph} function, we
13012 will only print parts of it. Read without preparation, the function
13013 can be daunting!
13014
13015 @need 800
13016 In outline, the function looks like this:
13017
13018 @smallexample
13019 @group
13020 (defun forward-paragraph (&optional arg)
13021 "@var{documentation}@dots{}"
13022 (interactive "p")
13023 (or arg (setq arg 1))
13024 (let*
13025 @var{varlist}
13026 (while (and (< arg 0) (not (bobp))) ; @r{backward-moving-code}
13027 @dots{}
13028 (while (and (> arg 0) (not (eobp))) ; @r{forward-moving-code}
13029 @dots{}
13030 @end group
13031 @end smallexample
13032
13033 The first parts of the function are routine: the function's argument
13034 list consists of one optional argument. Documentation follows.
13035
13036 The lower case @samp{p} in the @code{interactive} declaration means
13037 that the processed prefix argument, if any, is passed to the function.
13038 This will be a number, and is the repeat count of how many paragraphs
13039 point will move. The @code{or} expression in the next line handles
13040 the common case when no argument is passed to the function, which occurs
13041 if the function is called from other code rather than interactively.
13042 This case was described earlier. (@xref{forward-sentence, The
13043 @code{forward-sentence} function}.) Now we reach the end of the
13044 familiar part of this function.
13045
13046 @node fwd-para let
13047 @unnumberedsubsec The @code{let*} expression
13048
13049 The next line of the @code{forward-paragraph} function begins a
13050 @code{let*} expression. This is a different than @code{let}. The
13051 symbol is @code{let*} not @code{let}.
13052
13053 The @code{let*} special form is like @code{let} except that Emacs sets
13054 each variable in sequence, one after another, and variables in the
13055 latter part of the varlist can make use of the values to which Emacs
13056 set variables in the earlier part of the varlist.
13057
13058 @ignore
13059 ( refappend save-excursion, , code save-excursion in code append-to-buffer .)
13060 @end ignore
13061
13062 (@ref{append save-excursion, , @code{save-excursion} in @code{append-to-buffer}}.)
13063
13064 In the @code{let*} expression in this function, Emacs binds a total of
13065 seven variables: @code{opoint}, @code{fill-prefix-regexp},
13066 @code{parstart}, @code{parsep}, @code{sp-parstart}, @code{start}, and
13067 @code{found-start}.
13068
13069 The variable @code{parsep} appears twice, first, to remove instances
13070 of @samp{^}, and second, to handle fill prefixes.
13071
13072 The variable @code{opoint} is just the value of @code{point}. As you
13073 can guess, it is used in a @code{constrain-to-field} expression, just
13074 as in @code{forward-sentence}.
13075
13076 The variable @code{fill-prefix-regexp} is set to the value returned by
13077 evaluating the following list:
13078
13079 @smallexample
13080 @group
13081 (and fill-prefix
13082 (not (equal fill-prefix ""))
13083 (not paragraph-ignore-fill-prefix)
13084 (regexp-quote fill-prefix))
13085 @end group
13086 @end smallexample
13087
13088 @noindent
13089 This is an expression whose first element is the @code{and} special form.
13090
13091 As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
13092 function}), the @code{and} special form evaluates each of its
13093 arguments until one of the arguments returns a value of @code{nil}, in
13094 which case the @code{and} expression returns @code{nil}; however, if
13095 none of the arguments returns a value of @code{nil}, the value
13096 resulting from evaluating the last argument is returned. (Since such
13097 a value is not @code{nil}, it is considered true in Lisp.) In other
13098 words, an @code{and} expression returns a true value only if all its
13099 arguments are true.
13100 @findex and
13101
13102 In this case, the variable @code{fill-prefix-regexp} is bound to a
13103 non-@code{nil} value only if the following four expressions produce a
13104 true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
13105 @code{fill-prefix-regexp} is bound to @code{nil}.
13106
13107 @table @code
13108 @item fill-prefix
13109 When this variable is evaluated, the value of the fill prefix, if any,
13110 is returned. If there is no fill prefix, this variable returns
13111 @code{nil}.
13112
13113 @item (not (equal fill-prefix "")
13114 This expression checks whether an existing fill prefix is an empty
13115 string, that is, a string with no characters in it. An empty string is
13116 not a useful fill prefix.
13117
13118 @item (not paragraph-ignore-fill-prefix)
13119 This expression returns @code{nil} if the variable
13120 @code{paragraph-ignore-fill-prefix} has been turned on by being set to a
13121 true value such as @code{t}.
13122
13123 @item (regexp-quote fill-prefix)
13124 This is the last argument to the @code{and} special form. If all the
13125 arguments to the @code{and} are true, the value resulting from
13126 evaluating this expression will be returned by the @code{and} expression
13127 and bound to the variable @code{fill-prefix-regexp},
13128 @end table
13129
13130 @findex regexp-quote
13131 @noindent
13132 The result of evaluating this @code{and} expression successfully is that
13133 @code{fill-prefix-regexp} will be bound to the value of
13134 @code{fill-prefix} as modified by the @code{regexp-quote} function.
13135 What @code{regexp-quote} does is read a string and return a regular
13136 expression that will exactly match the string and match nothing else.
13137 This means that @code{fill-prefix-regexp} will be set to a value that
13138 will exactly match the fill prefix if the fill prefix exists.
13139 Otherwise, the variable will be set to @code{nil}.
13140
13141 The next two local variables in the @code{let*} expression are
13142 designed to remove instances of @samp{^} from @code{parstart} and
13143 @code{parsep}, the local variables which indicate the paragraph start
13144 and the paragraph separator. The next expression sets @code{parsep}
13145 again. That is to handle fill prefixes.
13146
13147 This is the setting that requires the definition call @code{let*}
13148 rather than @code{let}. The true-or-false-test for the @code{if}
13149 depends on whether the variable @code{fill-prefix-regexp} evaluates to
13150 @code{nil} or some other value.
13151
13152 If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
13153 the else-part of the @code{if} expression and binds @code{parsep} to
13154 its local value. (@code{parsep} is a regular expression that matches
13155 what separates paragraphs.)
13156
13157 But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
13158 the then-part of the @code{if} expression and binds @code{parsep} to a
13159 regular expression that includes the @code{fill-prefix-regexp} as part
13160 of the pattern.
13161
13162 Specifically, @code{parsep} is set to the original value of the
13163 paragraph separate regular expression concatenated with an alternative
13164 expression that consists of the @code{fill-prefix-regexp} followed by
13165 optional whitespace to the end of the line. The whitespace is defined
13166 by @w{@code{"[ \t]*$"}}.) The @samp{\\|} defines this portion of the
13167 regexp as an alternative to @code{parsep}.
13168
13169 According to a comment in the code, the next local variable,
13170 @code{sp-parstart}, is used for searching, and then the final two,
13171 @code{start} and @code{found-start}, are set to @code{nil}.
13172
13173 Now we get into the body of the @code{let*}. The first part of the body
13174 of the @code{let*} deals with the case when the function is given a
13175 negative argument and is therefore moving backwards. We will skip this
13176 section.
13177
13178 @node fwd-para while
13179 @unnumberedsubsec The forward motion @code{while} loop
13180
13181 The second part of the body of the @code{let*} deals with forward
13182 motion. It is a @code{while} loop that repeats itself so long as the
13183 value of @code{arg} is greater than zero. In the most common use of
13184 the function, the value of the argument is 1, so the body of the
13185 @code{while} loop is evaluated exactly once, and the cursor moves
13186 forward one paragraph.
13187
13188 @ignore
13189 (while (and (> arg 0) (not (eobp)))
13190
13191 ;; Move forward over separator lines...
13192 (while (and (not (eobp))
13193 (progn (move-to-left-margin) (not (eobp)))
13194 (looking-at parsep))
13195 (forward-line 1))
13196 (unless (eobp) (setq arg (1- arg)))
13197 ;; ... and one more line.
13198 (forward-line 1)
13199
13200 (if fill-prefix-regexp
13201 ;; There is a fill prefix; it overrides parstart.
13202 (while (and (not (eobp))
13203 (progn (move-to-left-margin) (not (eobp)))
13204 (not (looking-at parsep))
13205 (looking-at fill-prefix-regexp))
13206 (forward-line 1))
13207
13208 (while (and (re-search-forward sp-parstart nil 1)
13209 (progn (setq start (match-beginning 0))
13210 (goto-char start)
13211 (not (eobp)))
13212 (progn (move-to-left-margin)
13213 (not (looking-at parsep)))
13214 (or (not (looking-at parstart))
13215 (and use-hard-newlines
13216 (not (get-text-property (1- start) 'hard)))))
13217 (forward-char 1))
13218
13219 (if (< (point) (point-max))
13220 (goto-char start))))
13221 @end ignore
13222
13223 This part handles three situations: when point is between paragraphs,
13224 when there is a fill prefix and when there is no fill prefix.
13225
13226 @need 800
13227 The @code{while} loop looks like this:
13228
13229 @smallexample
13230 @group
13231 ;; @r{going forwards and not at the end of the buffer}
13232 (while (and (> arg 0) (not (eobp)))
13233
13234 ;; @r{between paragraphs}
13235 ;; Move forward over separator lines...
13236 (while (and (not (eobp))
13237 (progn (move-to-left-margin) (not (eobp)))
13238 (looking-at parsep))
13239 (forward-line 1))
13240 ;; @r{This decrements the loop}
13241 (unless (eobp) (setq arg (1- arg)))
13242 ;; ... and one more line.
13243 (forward-line 1)
13244 @end group
13245
13246 @group
13247 (if fill-prefix-regexp
13248 ;; There is a fill prefix; it overrides parstart;
13249 ;; we go forward line by line
13250 (while (and (not (eobp))
13251 (progn (move-to-left-margin) (not (eobp)))
13252 (not (looking-at parsep))
13253 (looking-at fill-prefix-regexp))
13254 (forward-line 1))
13255 @end group
13256
13257 @group
13258 ;; There is no fill prefix;
13259 ;; we go forward character by character
13260 (while (and (re-search-forward sp-parstart nil 1)
13261 (progn (setq start (match-beginning 0))
13262 (goto-char start)
13263 (not (eobp)))
13264 (progn (move-to-left-margin)
13265 (not (looking-at parsep)))
13266 (or (not (looking-at parstart))
13267 (and use-hard-newlines
13268 (not (get-text-property (1- start) 'hard)))))
13269 (forward-char 1))
13270 @end group
13271
13272 @group
13273 ;; and if there is no fill prefix and if we are not at the end,
13274 ;; go to whatever was found in the regular expression search
13275 ;; for sp-parstart
13276 (if (< (point) (point-max))
13277 (goto-char start))))
13278 @end group
13279 @end smallexample
13280
13281 @findex eobp
13282 We can see that this is a decrementing counter @code{while} loop,
13283 using the expression @code{(setq arg (1- arg))} as the decrementer.
13284 That expression is not far from the @code{while}, but is hidden in
13285 another Lisp macro, an @code{unless} macro. Unless we are at the end
13286 of the buffer---that is what the @code{eobp} function determines; it
13287 is an abbreviation of @samp{End Of Buffer P}---we decrease the value
13288 of @code{arg} by one.
13289
13290 (If we are at the end of the buffer, we cannot go forward any more and
13291 the next loop of the @code{while} expression will test false since the
13292 test is an @code{and} with @code{(not (eobp))}. The @code{not}
13293 function means exactly as you expect; it is another name for
13294 @code{null}, a function that returns true when its argument is false.)
13295
13296 Interestingly, the loop count is not decremented until we leave the
13297 space between paragraphs, unless we come to the end of buffer or stop
13298 seeing the local value of the paragraph separator.
13299
13300 That second @code{while} also has a @code{(move-to-left-margin)}
13301 expression. The function is self-explanatory. It is inside a
13302 @code{progn} expression and not the last element of its body, so it is
13303 only invoked for its side effect, which is to move point to the left
13304 margin of the current line.
13305
13306 @findex looking-at
13307 The @code{looking-at} function is also self-explanatory; it returns
13308 true if the text after point matches the regular expression given as
13309 its argument.
13310
13311 The rest of the body of the loop looks difficult at first, but makes
13312 sense as you come to understand it.
13313
13314 @need 800
13315 First consider what happens if there is a fill prefix:
13316
13317 @smallexample
13318 @group
13319 (if fill-prefix-regexp
13320 ;; There is a fill prefix; it overrides parstart;
13321 ;; we go forward line by line
13322 (while (and (not (eobp))
13323 (progn (move-to-left-margin) (not (eobp)))
13324 (not (looking-at parsep))
13325 (looking-at fill-prefix-regexp))
13326 (forward-line 1))
13327 @end group
13328 @end smallexample
13329
13330 @noindent
13331 This expression moves point forward line by line so long
13332 as four conditions are true:
13333
13334 @enumerate
13335 @item
13336 Point is not at the end of the buffer.
13337
13338 @item
13339 We can move to the left margin of the text and are
13340 not at the end of the buffer.
13341
13342 @item
13343 The text following point does not separate paragraphs.
13344
13345 @item
13346 The pattern following point is the fill prefix regular expression.
13347 @end enumerate
13348
13349 The last condition may be puzzling, until you remember that point was
13350 moved to the beginning of the line early in the @code{forward-paragraph}
13351 function. This means that if the text has a fill prefix, the
13352 @code{looking-at} function will see it.
13353
13354 @need 1250
13355 Consider what happens when there is no fill prefix.
13356
13357 @smallexample
13358 @group
13359 (while (and (re-search-forward sp-parstart nil 1)
13360 (progn (setq start (match-beginning 0))
13361 (goto-char start)
13362 (not (eobp)))
13363 (progn (move-to-left-margin)
13364 (not (looking-at parsep)))
13365 (or (not (looking-at parstart))
13366 (and use-hard-newlines
13367 (not (get-text-property (1- start) 'hard)))))
13368 (forward-char 1))
13369 @end group
13370 @end smallexample
13371
13372 @noindent
13373 This @code{while} loop has us searching forward for
13374 @code{sp-parstart}, which is the combination of possible whitespace
13375 with a the local value of the start of a paragraph or of a paragraph
13376 separator. (The latter two are within an expression starting
13377 @code{\(?:} so that they are not referenced by the
13378 @code{match-beginning} function.)
13379
13380 @need 800
13381 The two expressions,
13382
13383 @smallexample
13384 @group
13385 (setq start (match-beginning 0))
13386 (goto-char start)
13387 @end group
13388 @end smallexample
13389
13390 @noindent
13391 mean go to the start of the text matched by the regular expression
13392 search.
13393
13394 The @code{(match-beginning 0)} expression is new. It returns a number
13395 specifying the location of the start of the text that was matched by
13396 the last search.
13397
13398 The @code{match-beginning} function is used here because of a
13399 characteristic of a forward search: a successful forward search,
13400 regardless of whether it is a plain search or a regular expression
13401 search, moves point to the end of the text that is found. In this
13402 case, a successful search moves point to the end of the pattern for
13403 @code{sp-parstart}.
13404
13405 However, we want to put point at the end of the current paragraph, not
13406 somewhere else. Indeed, since the search possibly includes the
13407 paragraph separator, point may end up at the beginning of the next one
13408 unless we use an expression that includes @code{match-beginning}.
13409
13410 @findex match-beginning
13411 When given an argument of 0, @code{match-beginning} returns the
13412 position that is the start of the text matched by the most recent
13413 search. In this case, the most recent search looks for
13414 @code{sp-parstart}. The @code{(match-beginning 0)} expression returns
13415 the beginning position of that pattern, rather than the end position
13416 of that pattern.
13417
13418 (Incidentally, when passed a positive number as an argument, the
13419 @code{match-beginning} function returns the location of point at that
13420 parenthesized expression in the last search unless that parenthesized
13421 expression begins with @code{\(?:}. I don't know why @code{\(?:}
13422 appears here since the argument is 0.)
13423
13424 @need 1250
13425 The last expression when there is no fill prefix is
13426
13427 @smallexample
13428 @group
13429 (if (< (point) (point-max))
13430 (goto-char start))))
13431 @end group
13432 @end smallexample
13433
13434 @noindent
13435 This says that if there is no fill prefix and if we are not at the
13436 end, point should move to the beginning of whatever was found by the
13437 regular expression search for @code{sp-parstart}.
13438
13439 The full definition for the @code{forward-paragraph} function not only
13440 includes code for going forwards, but also code for going backwards.
13441
13442 If you are reading this inside of GNU Emacs and you want to see the
13443 whole function, you can type @kbd{C-h f} (@code{describe-function})
13444 and the name of the function. This gives you the function
13445 documentation and the name of the library containing the function's
13446 source. Place point over the name of the library and press the RET
13447 key; you will be taken directly to the source. (Be sure to install
13448 your sources! Without them, you are like a person who tries to drive
13449 a car with his eyes shut!)
13450
13451 @node etags
13452 @section Create Your Own @file{TAGS} File
13453 @findex etags
13454 @cindex @file{TAGS} file, create own
13455
13456 Besides @kbd{C-h f} (@code{describe-function}), another way to see the
13457 source of a function is to type @kbd{M-.} (@code{find-tag}) and the
13458 name of the function when prompted for it. This is a good habit to
13459 get into. The @kbd{M-.} (@code{find-tag}) command takes you directly
13460 to the source for a function, variable, or node. The function depends
13461 on tags tables to tell it where to go.
13462
13463 If the @code{find-tag} function first asks you for the name of a
13464 @file{TAGS} table, give it the name of a @file{TAGS} file such as
13465 @file{/usr/local/src/emacs/src/TAGS}. (The exact path to your
13466 @file{TAGS} file depends on how your copy of Emacs was installed. I
13467 just told you the location that provides both my C and my Emacs Lisp
13468 sources.)
13469
13470 You can also create your own @file{TAGS} file for directories that
13471 lack one.
13472
13473 You often need to build and install tags tables yourself. They are
13474 not built automatically. A tags table is called a @file{TAGS} file;
13475 the name is in upper case letters.
13476
13477 You can create a @file{TAGS} file by calling the @code{etags} program
13478 that comes as a part of the Emacs distribution. Usually, @code{etags}
13479 is compiled and installed when Emacs is built. (@code{etags} is not
13480 an Emacs Lisp function or a part of Emacs; it is a C program.)
13481
13482 @need 1250
13483 To create a @file{TAGS} file, first switch to the directory in which
13484 you want to create the file. In Emacs you can do this with the
13485 @kbd{M-x cd} command, or by visiting a file in the directory, or by
13486 listing the directory with @kbd{C-x d} (@code{dired}). Then run the
13487 compile command, with @w{@code{etags *.el}} as the command to execute
13488
13489 @smallexample
13490 M-x compile RET etags *.el RET
13491 @end smallexample
13492
13493 @noindent
13494 to create a @file{TAGS} file for Emacs Lisp.
13495
13496 For example, if you have a large number of files in your
13497 @file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
13498 of which I load 12---you can create a @file{TAGS} file for the Emacs
13499 Lisp files in that directory.
13500
13501 @need 1250
13502 The @code{etags} program takes all the usual shell `wildcards'. For
13503 example, if you have two directories for which you want a single
13504 @file{TAGS} file, type @w{@code{etags *.el ../elisp/*.el}}, where
13505 @file{../elisp/} is the second directory:
13506
13507 @smallexample
13508 M-x compile RET etags *.el ../elisp/*.el RET
13509 @end smallexample
13510
13511 @need 1250
13512 Type
13513
13514 @smallexample
13515 M-x compile RET etags --help RET
13516 @end smallexample
13517
13518 @noindent
13519 to see a list of the options accepted by @code{etags} as well as a
13520 list of supported languages.
13521
13522 The @code{etags} program handles more than 20 languages, including
13523 Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, HTML, Java,
13524 LaTeX, Pascal, Perl, PostScript, Python, TeX, Texinfo, makefiles, and
13525 most assemblers. The program has no switches for specifying the
13526 language; it recognizes the language in an input file according to its
13527 file name and contents.
13528
13529 @file{etags} is very helpful when you are writing code yourself and
13530 want to refer back to functions you have already written. Just run
13531 @code{etags} again at intervals as you write new functions, so they
13532 become part of the @file{TAGS} file.
13533
13534 If you think an appropriate @file{TAGS} file already exists for what
13535 you want, but do not know where it is, you can use the @code{locate}
13536 program to attempt to find it.
13537
13538 Type @w{@kbd{M-x locate @key{RET} TAGS @key{RET}}} and Emacs will list
13539 for you the full path names of all your @file{TAGS} files. On my
13540 system, this command lists 34 @file{TAGS} files. On the other hand, a
13541 `plain vanilla' system I recently installed did not contain any
13542 @file{TAGS} files.
13543
13544 If the tags table you want has been created, you can use the @code{M-x
13545 visit-tags-table} command to specify it. Otherwise, you will need to
13546 create the tag table yourself and then use @code{M-x
13547 visit-tags-table}.
13548
13549 @subsubheading Building Tags in the Emacs sources
13550 @cindex Building Tags in the Emacs sources
13551 @cindex Tags in the Emacs sources
13552 @findex make tags
13553
13554 The GNU Emacs sources come with a @file{Makefile} that contains a
13555 sophisticated @code{etags} command that creates, collects, and merges
13556 tags tables from all over the Emacs sources and puts the information
13557 into one @file{TAGS} file in the @file{src/} directory. (The
13558 @file{src/} directory is below the top level of your Emacs directory.)
13559
13560 @need 1250
13561 To build this @file{TAGS} file, go to the top level of your Emacs
13562 source directory and run the compile command @code{make tags}:
13563
13564 @smallexample
13565 M-x compile RET make tags RET
13566 @end smallexample
13567
13568 @noindent
13569 (The @code{make tags} command works well with the GNU Emacs sources,
13570 as well as with some other source packages.)
13571
13572 For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
13573 Manual}.
13574
13575 @node Regexp Review
13576 @section Review
13577
13578 Here is a brief summary of some recently introduced functions.
13579
13580 @table @code
13581 @item while
13582 Repeatedly evaluate the body of the expression so long as the first
13583 element of the body tests true. Then return @code{nil}. (The
13584 expression is evaluated only for its side effects.)
13585
13586 @need 1250
13587 For example:
13588
13589 @smallexample
13590 @group
13591 (let ((foo 2))
13592 (while (> foo 0)
13593 (insert (format "foo is %d.\n" foo))
13594 (setq foo (1- foo))))
13595
13596 @result{} foo is 2.
13597 foo is 1.
13598 nil
13599 @end group
13600 @end smallexample
13601
13602 @noindent
13603 (The @code{insert} function inserts its arguments at point; the
13604 @code{format} function returns a string formatted from its arguments
13605 the way @code{message} formats its arguments; @code{\n} produces a new
13606 line.)
13607
13608 @item re-search-forward
13609 Search for a pattern, and if the pattern is found, move point to rest
13610 just after it.
13611
13612 @noindent
13613 Takes four arguments, like @code{search-forward}:
13614
13615 @enumerate
13616 @item
13617 A regular expression that specifies the pattern to search for.
13618 (Remember to put quotation marks around this argument!)
13619
13620 @item
13621 Optionally, the limit of the search.
13622
13623 @item
13624 Optionally, what to do if the search fails, return @code{nil} or an
13625 error message.
13626
13627 @item
13628 Optionally, how many times to repeat the search; if negative, the
13629 search goes backwards.
13630 @end enumerate
13631
13632 @item let*
13633 Bind some variables locally to particular values,
13634 and then evaluate the remaining arguments, returning the value of the
13635 last one. While binding the local variables, use the local values of
13636 variables bound earlier, if any.
13637
13638 @need 1250
13639 For example:
13640
13641 @smallexample
13642 @group
13643 (let* ((foo 7)
13644 (bar (* 3 foo)))
13645 (message "`bar' is %d." bar))
13646 @result{} `bar' is 21.
13647 @end group
13648 @end smallexample
13649
13650 @item match-beginning
13651 Return the position of the start of the text found by the last regular
13652 expression search.
13653
13654 @item looking-at
13655 Return @code{t} for true if the text after point matches the argument,
13656 which should be a regular expression.
13657
13658 @item eobp
13659 Return @code{t} for true if point is at the end of the accessible part
13660 of a buffer. The end of the accessible part is the end of the buffer
13661 if the buffer is not narrowed; it is the end of the narrowed part if
13662 the buffer is narrowed.
13663 @end table
13664
13665 @need 1500
13666 @node re-search Exercises
13667 @section Exercises with @code{re-search-forward}
13668
13669 @itemize @bullet
13670 @item
13671 Write a function to search for a regular expression that matches two
13672 or more blank lines in sequence.
13673
13674 @item
13675 Write a function to search for duplicated words, such as `the the'.
13676 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
13677 Manual}, for information on how to write a regexp (a regular
13678 expression) to match a string that is composed of two identical
13679 halves. You can devise several regexps; some are better than others.
13680 The function I use is described in an appendix, along with several
13681 regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
13682 @end itemize
13683
13684 @node Counting Words
13685 @chapter Counting: Repetition and Regexps
13686 @cindex Repetition for word counting
13687 @cindex Regular expressions for word counting
13688
13689 Repetition and regular expression searches are powerful tools that you
13690 often use when you write code in Emacs Lisp. This chapter illustrates
13691 the use of regular expression searches through the construction of
13692 word count commands using @code{while} loops and recursion.
13693
13694 @menu
13695 * Why Count Words::
13696 * @value{COUNT-WORDS}:: Use a regexp, but find a problem.
13697 * recursive-count-words:: Start with case of no words in region.
13698 * Counting Exercise::
13699 @end menu
13700
13701 @ifnottex
13702 @node Why Count Words
13703 @unnumberedsec Counting words
13704 @end ifnottex
13705
13706 The standard Emacs distribution contains functions for counting the
13707 number of lines and words within a region.
13708
13709 Certain types of writing ask you to count words. Thus, if you write
13710 an essay, you may be limited to 800 words; if you write a novel, you
13711 may discipline yourself to write 1000 words a day. It seems odd, but
13712 for a long time, Emacs lacked a word count command. Perhaps people used
13713 Emacs mostly for code or types of documentation that did not require
13714 word counts; or perhaps they restricted themselves to the operating
13715 system word count command, @code{wc}. Alternatively, people may have
13716 followed the publishers' convention and computed a word count by
13717 dividing the number of characters in a document by five.
13718
13719 There are many ways to implement a command to count words. Here are
13720 some examples, which you may wish to compare with the standard Emacs
13721 command, @code{count-words-region}.
13722
13723 @node @value{COUNT-WORDS}
13724 @section The @code{@value{COUNT-WORDS}} Function
13725 @findex @value{COUNT-WORDS}
13726
13727 A word count command could count words in a line, paragraph, region,
13728 or buffer. What should the command cover? You could design the
13729 command to count the number of words in a complete buffer. However,
13730 the Emacs tradition encourages flexibility---you may want to count
13731 words in just a section, rather than all of a buffer. So it makes
13732 more sense to design the command to count the number of words in a
13733 region. Once you have a command to count words in a region, you can,
13734 if you wish, count words in a whole buffer by marking it with
13735 @w{@kbd{C-x h}} (@code{mark-whole-buffer}).
13736
13737 Clearly, counting words is a repetitive act: starting from the
13738 beginning of the region, you count the first word, then the second
13739 word, then the third word, and so on, until you reach the end of the
13740 region. This means that word counting is ideally suited to recursion
13741 or to a @code{while} loop.
13742
13743 @menu
13744 * Design @value{COUNT-WORDS}:: The definition using a @code{while} loop.
13745 * Whitespace Bug:: The Whitespace Bug in @code{@value{COUNT-WORDS}}.
13746 @end menu
13747
13748 @ifnottex
13749 @node Design @value{COUNT-WORDS}
13750 @unnumberedsubsec Designing @code{@value{COUNT-WORDS}}
13751 @end ifnottex
13752
13753 First, we will implement the word count command with a @code{while}
13754 loop, then with recursion. The command will, of course, be
13755 interactive.
13756
13757 @need 800
13758 The template for an interactive function definition is, as always:
13759
13760 @smallexample
13761 @group
13762 (defun @var{name-of-function} (@var{argument-list})
13763 "@var{documentation}@dots{}"
13764 (@var{interactive-expression}@dots{})
13765 @var{body}@dots{})
13766 @end group
13767 @end smallexample
13768
13769 What we need to do is fill in the slots.
13770
13771 The name of the function should be self-explanatory and similar to the
13772 existing @code{count-lines-region} name. This makes the name easier
13773 to remember. @code{count-words-region} is the obvious choice. Since
13774 that name is now used for the standard Emacs command to count words, we
13775 will name our implementation @code{@value{COUNT-WORDS}}.
13776
13777 The function counts words within a region. This means that the
13778 argument list must contain symbols that are bound to the two
13779 positions, the beginning and end of the region. These two positions
13780 can be called @samp{beginning} and @samp{end} respectively. The first
13781 line of the documentation should be a single sentence, since that is
13782 all that is printed as documentation by a command such as
13783 @code{apropos}. The interactive expression will be of the form
13784 @samp{(interactive "r")}, since that will cause Emacs to pass the
13785 beginning and end of the region to the function's argument list. All
13786 this is routine.
13787
13788 The body of the function needs to be written to do three tasks:
13789 first, to set up conditions under which the @code{while} loop can
13790 count words, second, to run the @code{while} loop, and third, to send
13791 a message to the user.
13792
13793 When a user calls @code{@value{COUNT-WORDS}}, point may be at the
13794 beginning or the end of the region. However, the counting process
13795 must start at the beginning of the region. This means we will want
13796 to put point there if it is not already there. Executing
13797 @code{(goto-char beginning)} ensures this. Of course, we will want to
13798 return point to its expected position when the function finishes its
13799 work. For this reason, the body must be enclosed in a
13800 @code{save-excursion} expression.
13801
13802 The central part of the body of the function consists of a
13803 @code{while} loop in which one expression jumps point forward word by
13804 word, and another expression counts those jumps. The true-or-false-test
13805 of the @code{while} loop should test true so long as point should jump
13806 forward, and false when point is at the end of the region.
13807
13808 We could use @code{(forward-word 1)} as the expression for moving point
13809 forward word by word, but it is easier to see what Emacs identifies as a
13810 `word' if we use a regular expression search.
13811
13812 A regular expression search that finds the pattern for which it is
13813 searching leaves point after the last character matched. This means
13814 that a succession of successful word searches will move point forward
13815 word by word.
13816
13817 As a practical matter, we want the regular expression search to jump
13818 over whitespace and punctuation between words as well as over the
13819 words themselves. A regexp that refuses to jump over interword
13820 whitespace would never jump more than one word! This means that
13821 the regexp should include the whitespace and punctuation that follows
13822 a word, if any, as well as the word itself. (A word may end a buffer
13823 and not have any following whitespace or punctuation, so that part of
13824 the regexp must be optional.)
13825
13826 Thus, what we want for the regexp is a pattern defining one or more
13827 word constituent characters followed, optionally, by one or more
13828 characters that are not word constituents. The regular expression for
13829 this is:
13830
13831 @smallexample
13832 \w+\W*
13833 @end smallexample
13834
13835 @noindent
13836 The buffer's syntax table determines which characters are and are not
13837 word constituents. For more information about syntax,
13838 @pxref{Syntax Tables, , Syntax Tables, elisp, The GNU Emacs Lisp
13839 Reference Manual}.
13840
13841 @need 800
13842 The search expression looks like this:
13843
13844 @smallexample
13845 (re-search-forward "\\w+\\W*")
13846 @end smallexample
13847
13848 @noindent
13849 (Note that paired backslashes precede the @samp{w} and @samp{W}. A
13850 single backslash has special meaning to the Emacs Lisp interpreter.
13851 It indicates that the following character is interpreted differently
13852 than usual. For example, the two characters, @samp{\n}, stand for
13853 @samp{newline}, rather than for a backslash followed by @samp{n}. Two
13854 backslashes in a row stand for an ordinary, `unspecial' backslash, so
13855 Emacs Lisp interpreter ends of seeing a single backslash followed by a
13856 letter. So it discovers the letter is special.)
13857
13858 We need a counter to count how many words there are; this variable
13859 must first be set to 0 and then incremented each time Emacs goes
13860 around the @code{while} loop. The incrementing expression is simply:
13861
13862 @smallexample
13863 (setq count (1+ count))
13864 @end smallexample
13865
13866 Finally, we want to tell the user how many words there are in the
13867 region. The @code{message} function is intended for presenting this
13868 kind of information to the user. The message has to be phrased so
13869 that it reads properly regardless of how many words there are in the
13870 region: we don't want to say that ``there are 1 words in the region''.
13871 The conflict between singular and plural is ungrammatical. We can
13872 solve this problem by using a conditional expression that evaluates
13873 different messages depending on the number of words in the region.
13874 There are three possibilities: no words in the region, one word in the
13875 region, and more than one word. This means that the @code{cond}
13876 special form is appropriate.
13877
13878 @need 1500
13879 All this leads to the following function definition:
13880
13881 @smallexample
13882 @group
13883 ;;; @r{First version; has bugs!}
13884 (defun @value{COUNT-WORDS} (beginning end)
13885 "Print number of words in the region.
13886 Words are defined as at least one word-constituent
13887 character followed by at least one character that
13888 is not a word-constituent. The buffer's syntax
13889 table determines which characters these are."
13890 (interactive "r")
13891 (message "Counting words in region ... ")
13892 @end group
13893
13894 @group
13895 ;;; @r{1. Set up appropriate conditions.}
13896 (save-excursion
13897 (goto-char beginning)
13898 (let ((count 0))
13899 @end group
13900
13901 @group
13902 ;;; @r{2. Run the} while @r{loop.}
13903 (while (< (point) end)
13904 (re-search-forward "\\w+\\W*")
13905 (setq count (1+ count)))
13906 @end group
13907
13908 @group
13909 ;;; @r{3. Send a message to the user.}
13910 (cond ((zerop count)
13911 (message
13912 "The region does NOT have any words."))
13913 ((= 1 count)
13914 (message
13915 "The region has 1 word."))
13916 (t
13917 (message
13918 "The region has %d words." count))))))
13919 @end group
13920 @end smallexample
13921
13922 @noindent
13923 As written, the function works, but not in all circumstances.
13924
13925 @node Whitespace Bug
13926 @subsection The Whitespace Bug in @code{@value{COUNT-WORDS}}
13927
13928 The @code{@value{COUNT-WORDS}} command described in the preceding
13929 section has two bugs, or rather, one bug with two manifestations.
13930 First, if you mark a region containing only whitespace in the middle
13931 of some text, the @code{@value{COUNT-WORDS}} command tells you that the
13932 region contains one word! Second, if you mark a region containing
13933 only whitespace at the end of the buffer or the accessible portion of
13934 a narrowed buffer, the command displays an error message that looks
13935 like this:
13936
13937 @smallexample
13938 Search failed: "\\w+\\W*"
13939 @end smallexample
13940
13941 If you are reading this in Info in GNU Emacs, you can test for these
13942 bugs yourself.
13943
13944 First, evaluate the function in the usual manner to install it.
13945 @ifinfo
13946 Here is a copy of the definition. Place your cursor after the closing
13947 parenthesis and type @kbd{C-x C-e} to install it.
13948
13949 @smallexample
13950 @group
13951 ;; @r{First version; has bugs!}
13952 (defun @value{COUNT-WORDS} (beginning end)
13953 "Print number of words in the region.
13954 Words are defined as at least one word-constituent character followed
13955 by at least one character that is not a word-constituent. The buffer's
13956 syntax table determines which characters these are."
13957 @end group
13958 @group
13959 (interactive "r")
13960 (message "Counting words in region ... ")
13961 @end group
13962
13963 @group
13964 ;;; @r{1. Set up appropriate conditions.}
13965 (save-excursion
13966 (goto-char beginning)
13967 (let ((count 0))
13968 @end group
13969
13970 @group
13971 ;;; @r{2. Run the} while @r{loop.}
13972 (while (< (point) end)
13973 (re-search-forward "\\w+\\W*")
13974 (setq count (1+ count)))
13975 @end group
13976
13977 @group
13978 ;;; @r{3. Send a message to the user.}
13979 (cond ((zerop count)
13980 (message "The region does NOT have any words."))
13981 ((= 1 count) (message "The region has 1 word."))
13982 (t (message "The region has %d words." count))))))
13983 @end group
13984 @end smallexample
13985 @end ifinfo
13986
13987 @need 1000
13988 If you wish, you can also install this keybinding by evaluating it:
13989
13990 @smallexample
13991 (global-set-key "\C-c=" '@value{COUNT-WORDS})
13992 @end smallexample
13993
13994 To conduct the first test, set mark and point to the beginning and end
13995 of the following line and then type @kbd{C-c =} (or @kbd{M-x
13996 @value{COUNT-WORDS}} if you have not bound @kbd{C-c =}):
13997
13998 @smallexample
13999 one two three
14000 @end smallexample
14001
14002 @noindent
14003 Emacs will tell you, correctly, that the region has three words.
14004
14005 Repeat the test, but place mark at the beginning of the line and place
14006 point just @emph{before} the word @samp{one}. Again type the command
14007 @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}). Emacs should tell you
14008 that the region has no words, since it is composed only of the
14009 whitespace at the beginning of the line. But instead Emacs tells you
14010 that the region has one word!
14011
14012 For the third test, copy the sample line to the end of the
14013 @file{*scratch*} buffer and then type several spaces at the end of the
14014 line. Place mark right after the word @samp{three} and point at the
14015 end of line. (The end of the line will be the end of the buffer.)
14016 Type @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}) as you did before.
14017 Again, Emacs should tell you that the region has no words, since it is
14018 composed only of the whitespace at the end of the line. Instead,
14019 Emacs displays an error message saying @samp{Search failed}.
14020
14021 The two bugs stem from the same problem.
14022
14023 Consider the first manifestation of the bug, in which the command
14024 tells you that the whitespace at the beginning of the line contains
14025 one word. What happens is this: The @code{M-x @value{COUNT-WORDS}}
14026 command moves point to the beginning of the region. The @code{while}
14027 tests whether the value of point is smaller than the value of
14028 @code{end}, which it is. Consequently, the regular expression search
14029 looks for and finds the first word. It leaves point after the word.
14030 @code{count} is set to one. The @code{while} loop repeats; but this
14031 time the value of point is larger than the value of @code{end}, the
14032 loop is exited; and the function displays a message saying the number
14033 of words in the region is one. In brief, the regular expression
14034 search looks for and finds the word even though it is outside
14035 the marked region.
14036
14037 In the second manifestation of the bug, the region is whitespace at
14038 the end of the buffer. Emacs says @samp{Search failed}. What happens
14039 is that the true-or-false-test in the @code{while} loop tests true, so
14040 the search expression is executed. But since there are no more words
14041 in the buffer, the search fails.
14042
14043 In both manifestations of the bug, the search extends or attempts to
14044 extend outside of the region.
14045
14046 The solution is to limit the search to the region---this is a fairly
14047 simple action, but as you may have come to expect, it is not quite as
14048 simple as you might think.
14049
14050 As we have seen, the @code{re-search-forward} function takes a search
14051 pattern as its first argument. But in addition to this first,
14052 mandatory argument, it accepts three optional arguments. The optional
14053 second argument bounds the search. The optional third argument, if
14054 @code{t}, causes the function to return @code{nil} rather than signal
14055 an error if the search fails. The optional fourth argument is a
14056 repeat count. (In Emacs, you can see a function's documentation by
14057 typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
14058
14059 In the @code{@value{COUNT-WORDS}} definition, the value of the end of
14060 the region is held by the variable @code{end} which is passed as an
14061 argument to the function. Thus, we can add @code{end} as an argument
14062 to the regular expression search expression:
14063
14064 @smallexample
14065 (re-search-forward "\\w+\\W*" end)
14066 @end smallexample
14067
14068 However, if you make only this change to the @code{@value{COUNT-WORDS}}
14069 definition and then test the new version of the definition on a
14070 stretch of whitespace, you will receive an error message saying
14071 @samp{Search failed}.
14072
14073 What happens is this: the search is limited to the region, and fails
14074 as you expect because there are no word-constituent characters in the
14075 region. Since it fails, we receive an error message. But we do not
14076 want to receive an error message in this case; we want to receive the
14077 message that "The region does NOT have any words."
14078
14079 The solution to this problem is to provide @code{re-search-forward}
14080 with a third argument of @code{t}, which causes the function to return
14081 @code{nil} rather than signal an error if the search fails.
14082
14083 However, if you make this change and try it, you will see the message
14084 ``Counting words in region ... '' and @dots{} you will keep on seeing
14085 that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
14086
14087 Here is what happens: the search is limited to the region, as before,
14088 and it fails because there are no word-constituent characters in the
14089 region, as expected. Consequently, the @code{re-search-forward}
14090 expression returns @code{nil}. It does nothing else. In particular,
14091 it does not move point, which it does as a side effect if it finds the
14092 search target. After the @code{re-search-forward} expression returns
14093 @code{nil}, the next expression in the @code{while} loop is evaluated.
14094 This expression increments the count. Then the loop repeats. The
14095 true-or-false-test tests true because the value of point is still less
14096 than the value of end, since the @code{re-search-forward} expression
14097 did not move point. @dots{} and the cycle repeats @dots{}
14098
14099 The @code{@value{COUNT-WORDS}} definition requires yet another
14100 modification, to cause the true-or-false-test of the @code{while} loop
14101 to test false if the search fails. Put another way, there are two
14102 conditions that must be satisfied in the true-or-false-test before the
14103 word count variable is incremented: point must still be within the
14104 region and the search expression must have found a word to count.
14105
14106 Since both the first condition and the second condition must be true
14107 together, the two expressions, the region test and the search
14108 expression, can be joined with an @code{and} special form and embedded in
14109 the @code{while} loop as the true-or-false-test, like this:
14110
14111 @smallexample
14112 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
14113 @end smallexample
14114
14115 @c colon in printed section title causes problem in Info cross reference
14116 @c also trouble with an overfull hbox
14117 @iftex
14118 @noindent
14119 (For information about @code{and}, see
14120 @ref{kill-new function, , The @code{kill-new} function}.)
14121 @end iftex
14122 @ifinfo
14123 @noindent
14124 (@xref{kill-new function, , The @code{kill-new} function}, for
14125 information about @code{and}.)
14126 @end ifinfo
14127
14128 The @code{re-search-forward} expression returns @code{t} if the search
14129 succeeds and as a side effect moves point. Consequently, as words are
14130 found, point is moved through the region. When the search expression
14131 fails to find another word, or when point reaches the end of the
14132 region, the true-or-false-test tests false, the @code{while} loop
14133 exits, and the @code{@value{COUNT-WORDS}} function displays one or
14134 other of its messages.
14135
14136 After incorporating these final changes, the @code{@value{COUNT-WORDS}}
14137 works without bugs (or at least, without bugs that I have found!).
14138 Here is what it looks like:
14139
14140 @smallexample
14141 @group
14142 ;;; @r{Final version:} @code{while}
14143 (defun @value{COUNT-WORDS} (beginning end)
14144 "Print number of words in the region."
14145 (interactive "r")
14146 (message "Counting words in region ... ")
14147 @end group
14148
14149 @group
14150 ;;; @r{1. Set up appropriate conditions.}
14151 (save-excursion
14152 (let ((count 0))
14153 (goto-char beginning)
14154 @end group
14155
14156 @group
14157 ;;; @r{2. Run the} while @r{loop.}
14158 (while (and (< (point) end)
14159 (re-search-forward "\\w+\\W*" end t))
14160 (setq count (1+ count)))
14161 @end group
14162
14163 @group
14164 ;;; @r{3. Send a message to the user.}
14165 (cond ((zerop count)
14166 (message
14167 "The region does NOT have any words."))
14168 ((= 1 count)
14169 (message
14170 "The region has 1 word."))
14171 (t
14172 (message
14173 "The region has %d words." count))))))
14174 @end group
14175 @end smallexample
14176
14177 @node recursive-count-words
14178 @section Count Words Recursively
14179 @cindex Count words recursively
14180 @cindex Recursively counting words
14181 @cindex Words, counted recursively
14182
14183 You can write the function for counting words recursively as well as
14184 with a @code{while} loop. Let's see how this is done.
14185
14186 First, we need to recognize that the @code{@value{COUNT-WORDS}}
14187 function has three jobs: it sets up the appropriate conditions for
14188 counting to occur; it counts the words in the region; and it sends a
14189 message to the user telling how many words there are.
14190
14191 If we write a single recursive function to do everything, we will
14192 receive a message for every recursive call. If the region contains 13
14193 words, we will receive thirteen messages, one right after the other.
14194 We don't want this! Instead, we must write two functions to do the
14195 job, one of which (the recursive function) will be used inside of the
14196 other. One function will set up the conditions and display the
14197 message; the other will return the word count.
14198
14199 Let us start with the function that causes the message to be displayed.
14200 We can continue to call this @code{@value{COUNT-WORDS}}.
14201
14202 This is the function that the user will call. It will be interactive.
14203 Indeed, it will be similar to our previous versions of this
14204 function, except that it will call @code{recursive-count-words} to
14205 determine how many words are in the region.
14206
14207 @need 1250
14208 We can readily construct a template for this function, based on our
14209 previous versions:
14210
14211 @smallexample
14212 @group
14213 ;; @r{Recursive version; uses regular expression search}
14214 (defun @value{COUNT-WORDS} (beginning end)
14215 "@var{documentation}@dots{}"
14216 (@var{interactive-expression}@dots{})
14217 @end group
14218 @group
14219
14220 ;;; @r{1. Set up appropriate conditions.}
14221 (@var{explanatory message})
14222 (@var{set-up functions}@dots{}
14223 @end group
14224 @group
14225
14226 ;;; @r{2. Count the words.}
14227 @var{recursive call}
14228 @end group
14229 @group
14230
14231 ;;; @r{3. Send a message to the user.}
14232 @var{message providing word count}))
14233 @end group
14234 @end smallexample
14235
14236 The definition looks straightforward, except that somehow the count
14237 returned by the recursive call must be passed to the message
14238 displaying the word count. A little thought suggests that this can be
14239 done by making use of a @code{let} expression: we can bind a variable
14240 in the varlist of a @code{let} expression to the number of words in
14241 the region, as returned by the recursive call; and then the
14242 @code{cond} expression, using binding, can display the value to the
14243 user.
14244
14245 Often, one thinks of the binding within a @code{let} expression as
14246 somehow secondary to the `primary' work of a function. But in this
14247 case, what you might consider the `primary' job of the function,
14248 counting words, is done within the @code{let} expression.
14249
14250 @need 1250
14251 Using @code{let}, the function definition looks like this:
14252
14253 @smallexample
14254 @group
14255 (defun @value{COUNT-WORDS} (beginning end)
14256 "Print number of words in the region."
14257 (interactive "r")
14258 @end group
14259
14260 @group
14261 ;;; @r{1. Set up appropriate conditions.}
14262 (message "Counting words in region ... ")
14263 (save-excursion
14264 (goto-char beginning)
14265 @end group
14266
14267 @group
14268 ;;; @r{2. Count the words.}
14269 (let ((count (recursive-count-words end)))
14270 @end group
14271
14272 @group
14273 ;;; @r{3. Send a message to the user.}
14274 (cond ((zerop count)
14275 (message
14276 "The region does NOT have any words."))
14277 ((= 1 count)
14278 (message
14279 "The region has 1 word."))
14280 (t
14281 (message
14282 "The region has %d words." count))))))
14283 @end group
14284 @end smallexample
14285
14286 Next, we need to write the recursive counting function.
14287
14288 A recursive function has at least three parts: the `do-again-test', the
14289 `next-step-expression', and the recursive call.
14290
14291 The do-again-test determines whether the function will or will not be
14292 called again. Since we are counting words in a region and can use a
14293 function that moves point forward for every word, the do-again-test
14294 can check whether point is still within the region. The do-again-test
14295 should find the value of point and determine whether point is before,
14296 at, or after the value of the end of the region. We can use the
14297 @code{point} function to locate point. Clearly, we must pass the
14298 value of the end of the region to the recursive counting function as an
14299 argument.
14300
14301 In addition, the do-again-test should also test whether the search finds a
14302 word. If it does not, the function should not call itself again.
14303
14304 The next-step-expression changes a value so that when the recursive
14305 function is supposed to stop calling itself, it stops. More
14306 precisely, the next-step-expression changes a value so that at the
14307 right time, the do-again-test stops the recursive function from
14308 calling itself again. In this case, the next-step-expression can be
14309 the expression that moves point forward, word by word.
14310
14311 The third part of a recursive function is the recursive call.
14312
14313 Somewhere, also, we also need a part that does the `work' of the
14314 function, a part that does the counting. A vital part!
14315
14316 @need 1250
14317 But already, we have an outline of the recursive counting function:
14318
14319 @smallexample
14320 @group
14321 (defun recursive-count-words (region-end)
14322 "@var{documentation}@dots{}"
14323 @var{do-again-test}
14324 @var{next-step-expression}
14325 @var{recursive call})
14326 @end group
14327 @end smallexample
14328
14329 Now we need to fill in the slots. Let's start with the simplest cases
14330 first: if point is at or beyond the end of the region, there cannot
14331 be any words in the region, so the function should return zero.
14332 Likewise, if the search fails, there are no words to count, so the
14333 function should return zero.
14334
14335 On the other hand, if point is within the region and the search
14336 succeeds, the function should call itself again.
14337
14338 @need 800
14339 Thus, the do-again-test should look like this:
14340
14341 @smallexample
14342 @group
14343 (and (< (point) region-end)
14344 (re-search-forward "\\w+\\W*" region-end t))
14345 @end group
14346 @end smallexample
14347
14348 Note that the search expression is part of the do-again-test---the
14349 function returns @code{t} if its search succeeds and @code{nil} if it
14350 fails. (@xref{Whitespace Bug, , The Whitespace Bug in
14351 @code{@value{COUNT-WORDS}}}, for an explanation of how
14352 @code{re-search-forward} works.)
14353
14354 The do-again-test is the true-or-false test of an @code{if} clause.
14355 Clearly, if the do-again-test succeeds, the then-part of the @code{if}
14356 clause should call the function again; but if it fails, the else-part
14357 should return zero since either point is outside the region or the
14358 search failed because there were no words to find.
14359
14360 But before considering the recursive call, we need to consider the
14361 next-step-expression. What is it? Interestingly, it is the search
14362 part of the do-again-test.
14363
14364 In addition to returning @code{t} or @code{nil} for the
14365 do-again-test, @code{re-search-forward} moves point forward as a side
14366 effect of a successful search. This is the action that changes the
14367 value of point so that the recursive function stops calling itself
14368 when point completes its movement through the region. Consequently,
14369 the @code{re-search-forward} expression is the next-step-expression.
14370
14371 @need 1200
14372 In outline, then, the body of the @code{recursive-count-words}
14373 function looks like this:
14374
14375 @smallexample
14376 @group
14377 (if @var{do-again-test-and-next-step-combined}
14378 ;; @r{then}
14379 @var{recursive-call-returning-count}
14380 ;; @r{else}
14381 @var{return-zero})
14382 @end group
14383 @end smallexample
14384
14385 How to incorporate the mechanism that counts?
14386
14387 If you are not used to writing recursive functions, a question like
14388 this can be troublesome. But it can and should be approached
14389 systematically.
14390
14391 We know that the counting mechanism should be associated in some way
14392 with the recursive call. Indeed, since the next-step-expression moves
14393 point forward by one word, and since a recursive call is made for
14394 each word, the counting mechanism must be an expression that adds one
14395 to the value returned by a call to @code{recursive-count-words}.
14396
14397 @need 800
14398 Consider several cases:
14399
14400 @itemize @bullet
14401 @item
14402 If there are two words in the region, the function should return
14403 a value resulting from adding one to the value returned when it counts
14404 the first word, plus the number returned when it counts the remaining
14405 words in the region, which in this case is one.
14406
14407 @item
14408 If there is one word in the region, the function should return
14409 a value resulting from adding one to the value returned when it counts
14410 that word, plus the number returned when it counts the remaining
14411 words in the region, which in this case is zero.
14412
14413 @item
14414 If there are no words in the region, the function should return zero.
14415 @end itemize
14416
14417 From the sketch we can see that the else-part of the @code{if} returns
14418 zero for the case of no words. This means that the then-part of the
14419 @code{if} must return a value resulting from adding one to the value
14420 returned from a count of the remaining words.
14421
14422 @need 1200
14423 The expression will look like this, where @code{1+} is a function that
14424 adds one to its argument.
14425
14426 @smallexample
14427 (1+ (recursive-count-words region-end))
14428 @end smallexample
14429
14430 @need 1200
14431 The whole @code{recursive-count-words} function will then look like
14432 this:
14433
14434 @smallexample
14435 @group
14436 (defun recursive-count-words (region-end)
14437 "@var{documentation}@dots{}"
14438
14439 ;;; @r{1. do-again-test}
14440 (if (and (< (point) region-end)
14441 (re-search-forward "\\w+\\W*" region-end t))
14442 @end group
14443
14444 @group
14445 ;;; @r{2. then-part: the recursive call}
14446 (1+ (recursive-count-words region-end))
14447
14448 ;;; @r{3. else-part}
14449 0))
14450 @end group
14451 @end smallexample
14452
14453 @need 1250
14454 Let's examine how this works:
14455
14456 If there are no words in the region, the else part of the @code{if}
14457 expression is evaluated and consequently the function returns zero.
14458
14459 If there is one word in the region, the value of point is less than
14460 the value of @code{region-end} and the search succeeds. In this case,
14461 the true-or-false-test of the @code{if} expression tests true, and the
14462 then-part of the @code{if} expression is evaluated. The counting
14463 expression is evaluated. This expression returns a value (which will
14464 be the value returned by the whole function) that is the sum of one
14465 added to the value returned by a recursive call.
14466
14467 Meanwhile, the next-step-expression has caused point to jump over the
14468 first (and in this case only) word in the region. This means that
14469 when @code{(recursive-count-words region-end)} is evaluated a second
14470 time, as a result of the recursive call, the value of point will be
14471 equal to or greater than the value of region end. So this time,
14472 @code{recursive-count-words} will return zero. The zero will be added
14473 to one, and the original evaluation of @code{recursive-count-words}
14474 will return one plus zero, which is one, which is the correct amount.
14475
14476 Clearly, if there are two words in the region, the first call to
14477 @code{recursive-count-words} returns one added to the value returned
14478 by calling @code{recursive-count-words} on a region containing the
14479 remaining word---that is, it adds one to one, producing two, which is
14480 the correct amount.
14481
14482 Similarly, if there are three words in the region, the first call to
14483 @code{recursive-count-words} returns one added to the value returned
14484 by calling @code{recursive-count-words} on a region containing the
14485 remaining two words---and so on and so on.
14486
14487 @need 1250
14488 @noindent
14489 With full documentation the two functions look like this:
14490
14491 @need 1250
14492 @noindent
14493 The recursive function:
14494
14495 @findex recursive-count-words
14496 @smallexample
14497 @group
14498 (defun recursive-count-words (region-end)
14499 "Number of words between point and REGION-END."
14500 @end group
14501
14502 @group
14503 ;;; @r{1. do-again-test}
14504 (if (and (< (point) region-end)
14505 (re-search-forward "\\w+\\W*" region-end t))
14506 @end group
14507
14508 @group
14509 ;;; @r{2. then-part: the recursive call}
14510 (1+ (recursive-count-words region-end))
14511
14512 ;;; @r{3. else-part}
14513 0))
14514 @end group
14515 @end smallexample
14516
14517 @need 800
14518 @noindent
14519 The wrapper:
14520
14521 @smallexample
14522 @group
14523 ;;; @r{Recursive version}
14524 (defun @value{COUNT-WORDS} (beginning end)
14525 "Print number of words in the region.
14526 @end group
14527
14528 @group
14529 Words are defined as at least one word-constituent
14530 character followed by at least one character that is
14531 not a word-constituent. The buffer's syntax table
14532 determines which characters these are."
14533 @end group
14534 @group
14535 (interactive "r")
14536 (message "Counting words in region ... ")
14537 (save-excursion
14538 (goto-char beginning)
14539 (let ((count (recursive-count-words end)))
14540 @end group
14541 @group
14542 (cond ((zerop count)
14543 (message
14544 "The region does NOT have any words."))
14545 @end group
14546 @group
14547 ((= 1 count)
14548 (message "The region has 1 word."))
14549 (t
14550 (message
14551 "The region has %d words." count))))))
14552 @end group
14553 @end smallexample
14554
14555 @node Counting Exercise
14556 @section Exercise: Counting Punctuation
14557
14558 Using a @code{while} loop, write a function to count the number of
14559 punctuation marks in a region---period, comma, semicolon, colon,
14560 exclamation mark, and question mark. Do the same using recursion.
14561
14562 @node Words in a defun
14563 @chapter Counting Words in a @code{defun}
14564 @cindex Counting words in a @code{defun}
14565 @cindex Word counting in a @code{defun}
14566
14567 Our next project is to count the number of words in a function
14568 definition. Clearly, this can be done using some variant of
14569 @code{@value{COUNT-WORDS}}. @xref{Counting Words, , Counting Words:
14570 Repetition and Regexps}. If we are just going to count the words in
14571 one definition, it is easy enough to mark the definition with the
14572 @kbd{C-M-h} (@code{mark-defun}) command, and then call
14573 @code{@value{COUNT-WORDS}}.
14574
14575 However, I am more ambitious: I want to count the words and symbols in
14576 every definition in the Emacs sources and then print a graph that
14577 shows how many functions there are of each length: how many contain 40
14578 to 49 words or symbols, how many contain 50 to 59 words or symbols,
14579 and so on. I have often been curious how long a typical function is,
14580 and this will tell.
14581
14582 @menu
14583 * Divide and Conquer::
14584 * Words and Symbols:: What to count?
14585 * Syntax:: What constitutes a word or symbol?
14586 * count-words-in-defun:: Very like @code{@value{COUNT-WORDS}}.
14587 * Several defuns:: Counting several defuns in a file.
14588 * Find a File:: Do you want to look at a file?
14589 * lengths-list-file:: A list of the lengths of many definitions.
14590 * Several files:: Counting in definitions in different files.
14591 * Several files recursively:: Recursively counting in different files.
14592 * Prepare the data:: Prepare the data for display in a graph.
14593 @end menu
14594
14595 @ifnottex
14596 @node Divide and Conquer
14597 @unnumberedsec Divide and Conquer
14598 @end ifnottex
14599
14600 Described in one phrase, the histogram project is daunting; but
14601 divided into numerous small steps, each of which we can take one at a
14602 time, the project becomes less fearsome. Let us consider what the
14603 steps must be:
14604
14605 @itemize @bullet
14606 @item
14607 First, write a function to count the words in one definition. This
14608 includes the problem of handling symbols as well as words.
14609
14610 @item
14611 Second, write a function to list the numbers of words in each function
14612 in a file. This function can use the @code{count-words-in-defun}
14613 function.
14614
14615 @item
14616 Third, write a function to list the numbers of words in each function
14617 in each of several files. This entails automatically finding the
14618 various files, switching to them, and counting the words in the
14619 definitions within them.
14620
14621 @item
14622 Fourth, write a function to convert the list of numbers that we
14623 created in step three to a form that will be suitable for printing as
14624 a graph.
14625
14626 @item
14627 Fifth, write a function to print the results as a graph.
14628 @end itemize
14629
14630 This is quite a project! But if we take each step slowly, it will not
14631 be difficult.
14632
14633 @node Words and Symbols
14634 @section What to Count?
14635 @cindex Words and symbols in defun
14636
14637 When we first start thinking about how to count the words in a
14638 function definition, the first question is (or ought to be) what are
14639 we going to count? When we speak of `words' with respect to a Lisp
14640 function definition, we are actually speaking, in large part, of
14641 `symbols'. For example, the following @code{multiply-by-seven}
14642 function contains the five symbols @code{defun},
14643 @code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
14644 addition, in the documentation string, it contains the four words
14645 @samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
14646 symbol @samp{number} is repeated, so the definition contains a total
14647 of ten words and symbols.
14648
14649 @smallexample
14650 @group
14651 (defun multiply-by-seven (number)
14652 "Multiply NUMBER by seven."
14653 (* 7 number))
14654 @end group
14655 @end smallexample
14656
14657 @noindent
14658 However, if we mark the @code{multiply-by-seven} definition with
14659 @kbd{C-M-h} (@code{mark-defun}), and then call
14660 @code{@value{COUNT-WORDS}} on it, we will find that
14661 @code{@value{COUNT-WORDS}} claims the definition has eleven words, not
14662 ten! Something is wrong!
14663
14664 The problem is twofold: @code{@value{COUNT-WORDS}} does not count the
14665 @samp{*} as a word, and it counts the single symbol,
14666 @code{multiply-by-seven}, as containing three words. The hyphens are
14667 treated as if they were interword spaces rather than intraword
14668 connectors: @samp{multiply-by-seven} is counted as if it were written
14669 @samp{multiply by seven}.
14670
14671 The cause of this confusion is the regular expression search within
14672 the @code{@value{COUNT-WORDS}} definition that moves point forward word
14673 by word. In the canonical version of @code{@value{COUNT-WORDS}}, the
14674 regexp is:
14675
14676 @smallexample
14677 "\\w+\\W*"
14678 @end smallexample
14679
14680 @noindent
14681 This regular expression is a pattern defining one or more word
14682 constituent characters possibly followed by one or more characters
14683 that are not word constituents. What is meant by `word constituent
14684 characters' brings us to the issue of syntax, which is worth a section
14685 of its own.
14686
14687 @node Syntax
14688 @section What Constitutes a Word or Symbol?
14689 @cindex Syntax categories and tables
14690
14691 Emacs treats different characters as belonging to different
14692 @dfn{syntax categories}. For example, the regular expression,
14693 @samp{\\w+}, is a pattern specifying one or more @emph{word
14694 constituent} characters. Word constituent characters are members of
14695 one syntax category. Other syntax categories include the class of
14696 punctuation characters, such as the period and the comma, and the
14697 class of whitespace characters, such as the blank space and the tab
14698 character. (For more information, @pxref{Syntax Tables, , Syntax
14699 Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
14700
14701 Syntax tables specify which characters belong to which categories.
14702 Usually, a hyphen is not specified as a `word constituent character'.
14703 Instead, it is specified as being in the `class of characters that are
14704 part of symbol names but not words.' This means that the
14705 @code{@value{COUNT-WORDS}} function treats it in the same way it treats
14706 an interword white space, which is why @code{@value{COUNT-WORDS}}
14707 counts @samp{multiply-by-seven} as three words.
14708
14709 There are two ways to cause Emacs to count @samp{multiply-by-seven} as
14710 one symbol: modify the syntax table or modify the regular expression.
14711
14712 We could redefine a hyphen as a word constituent character by
14713 modifying the syntax table that Emacs keeps for each mode. This
14714 action would serve our purpose, except that a hyphen is merely the
14715 most common character within symbols that is not typically a word
14716 constituent character; there are others, too.
14717
14718 Alternatively, we can redefine the regexp used in the
14719 @code{@value{COUNT-WORDS}} definition so as to include symbols. This
14720 procedure has the merit of clarity, but the task is a little tricky.
14721
14722 @need 1200
14723 The first part is simple enough: the pattern must match ``at least one
14724 character that is a word or symbol constituent''. Thus:
14725
14726 @smallexample
14727 "\\(\\w\\|\\s_\\)+"
14728 @end smallexample
14729
14730 @noindent
14731 The @samp{\\(} is the first part of the grouping construct that
14732 includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
14733 by the @samp{\\|}. The @samp{\\w} matches any word-constituent
14734 character and the @samp{\\s_} matches any character that is part of a
14735 symbol name but not a word-constituent character. The @samp{+}
14736 following the group indicates that the word or symbol constituent
14737 characters must be matched at least once.
14738
14739 However, the second part of the regexp is more difficult to design.
14740 What we want is to follow the first part with ``optionally one or more
14741 characters that are not constituents of a word or symbol''. At first,
14742 I thought I could define this with the following:
14743
14744 @smallexample
14745 "\\(\\W\\|\\S_\\)*"
14746 @end smallexample
14747
14748 @noindent
14749 The upper case @samp{W} and @samp{S} match characters that are
14750 @emph{not} word or symbol constituents. Unfortunately, this
14751 expression matches any character that is either not a word constituent
14752 or not a symbol constituent. This matches any character!
14753
14754 I then noticed that every word or symbol in my test region was
14755 followed by white space (blank space, tab, or newline). So I tried
14756 placing a pattern to match one or more blank spaces after the pattern
14757 for one or more word or symbol constituents. This failed, too. Words
14758 and symbols are often separated by whitespace, but in actual code
14759 parentheses may follow symbols and punctuation may follow words. So
14760 finally, I designed a pattern in which the word or symbol constituents
14761 are followed optionally by characters that are not white space and
14762 then followed optionally by white space.
14763
14764 @need 800
14765 Here is the full regular expression:
14766
14767 @smallexample
14768 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14769 @end smallexample
14770
14771 @node count-words-in-defun
14772 @section The @code{count-words-in-defun} Function
14773 @cindex Counting words in a @code{defun}
14774
14775 We have seen that there are several ways to write a
14776 @code{count-words-region} function. To write a
14777 @code{count-words-in-defun}, we need merely adapt one of these
14778 versions.
14779
14780 The version that uses a @code{while} loop is easy to understand, so I
14781 am going to adapt that. Because @code{count-words-in-defun} will be
14782 part of a more complex program, it need not be interactive and it need
14783 not display a message but just return the count. These considerations
14784 simplify the definition a little.
14785
14786 On the other hand, @code{count-words-in-defun} will be used within a
14787 buffer that contains function definitions. Consequently, it is
14788 reasonable to ask that the function determine whether it is called
14789 when point is within a function definition, and if it is, to return
14790 the count for that definition. This adds complexity to the
14791 definition, but saves us from needing to pass arguments to the
14792 function.
14793
14794 @need 1250
14795 These considerations lead us to prepare the following template:
14796
14797 @smallexample
14798 @group
14799 (defun count-words-in-defun ()
14800 "@var{documentation}@dots{}"
14801 (@var{set up}@dots{}
14802 (@var{while loop}@dots{})
14803 @var{return count})
14804 @end group
14805 @end smallexample
14806
14807 @noindent
14808 As usual, our job is to fill in the slots.
14809
14810 First, the set up.
14811
14812 We are presuming that this function will be called within a buffer
14813 containing function definitions. Point will either be within a
14814 function definition or not. For @code{count-words-in-defun} to work,
14815 point must move to the beginning of the definition, a counter must
14816 start at zero, and the counting loop must stop when point reaches the
14817 end of the definition.
14818
14819 The @code{beginning-of-defun} function searches backwards for an
14820 opening delimiter such as a @samp{(} at the beginning of a line, and
14821 moves point to that position, or else to the limit of the search. In
14822 practice, this means that @code{beginning-of-defun} moves point to the
14823 beginning of an enclosing or preceding function definition, or else to
14824 the beginning of the buffer. We can use @code{beginning-of-defun} to
14825 place point where we wish to start.
14826
14827 The @code{while} loop requires a counter to keep track of the words or
14828 symbols being counted. A @code{let} expression can be used to create
14829 a local variable for this purpose, and bind it to an initial value of zero.
14830
14831 The @code{end-of-defun} function works like @code{beginning-of-defun}
14832 except that it moves point to the end of the definition.
14833 @code{end-of-defun} can be used as part of an expression that
14834 determines the position of the end of the definition.
14835
14836 The set up for @code{count-words-in-defun} takes shape rapidly: first
14837 we move point to the beginning of the definition, then we create a
14838 local variable to hold the count, and finally, we record the position
14839 of the end of the definition so the @code{while} loop will know when to stop
14840 looping.
14841
14842 @need 1250
14843 The code looks like this:
14844
14845 @smallexample
14846 @group
14847 (beginning-of-defun)
14848 (let ((count 0)
14849 (end (save-excursion (end-of-defun) (point))))
14850 @end group
14851 @end smallexample
14852
14853 @noindent
14854 The code is simple. The only slight complication is likely to concern
14855 @code{end}: it is bound to the position of the end of the definition
14856 by a @code{save-excursion} expression that returns the value of point
14857 after @code{end-of-defun} temporarily moves it to the end of the
14858 definition.
14859
14860 The second part of the @code{count-words-in-defun}, after the set up,
14861 is the @code{while} loop.
14862
14863 The loop must contain an expression that jumps point forward word by
14864 word and symbol by symbol, and another expression that counts the
14865 jumps. The true-or-false-test for the @code{while} loop should test
14866 true so long as point should jump forward, and false when point is at
14867 the end of the definition. We have already redefined the regular
14868 expression for this, so the loop is straightforward:
14869
14870 @smallexample
14871 @group
14872 (while (and (< (point) end)
14873 (re-search-forward
14874 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t))
14875 (setq count (1+ count)))
14876 @end group
14877 @end smallexample
14878
14879 The third part of the function definition returns the count of words
14880 and symbols. This part is the last expression within the body of the
14881 @code{let} expression, and can be, very simply, the local variable
14882 @code{count}, which when evaluated returns the count.
14883
14884 @need 1250
14885 Put together, the @code{count-words-in-defun} definition looks like this:
14886
14887 @findex count-words-in-defun
14888 @smallexample
14889 @group
14890 (defun count-words-in-defun ()
14891 "Return the number of words and symbols in a defun."
14892 (beginning-of-defun)
14893 (let ((count 0)
14894 (end (save-excursion (end-of-defun) (point))))
14895 @end group
14896 @group
14897 (while
14898 (and (< (point) end)
14899 (re-search-forward
14900 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14901 end t))
14902 (setq count (1+ count)))
14903 count))
14904 @end group
14905 @end smallexample
14906
14907 How to test this? The function is not interactive, but it is easy to
14908 put a wrapper around the function to make it interactive; we can use
14909 almost the same code as for the recursive version of
14910 @code{@value{COUNT-WORDS}}:
14911
14912 @smallexample
14913 @group
14914 ;;; @r{Interactive version.}
14915 (defun count-words-defun ()
14916 "Number of words and symbols in a function definition."
14917 (interactive)
14918 (message
14919 "Counting words and symbols in function definition ... ")
14920 @end group
14921 @group
14922 (let ((count (count-words-in-defun)))
14923 (cond
14924 ((zerop count)
14925 (message
14926 "The definition does NOT have any words or symbols."))
14927 @end group
14928 @group
14929 ((= 1 count)
14930 (message
14931 "The definition has 1 word or symbol."))
14932 (t
14933 (message
14934 "The definition has %d words or symbols." count)))))
14935 @end group
14936 @end smallexample
14937
14938 @need 800
14939 @noindent
14940 Let's re-use @kbd{C-c =} as a convenient keybinding:
14941
14942 @smallexample
14943 (global-set-key "\C-c=" 'count-words-defun)
14944 @end smallexample
14945
14946 Now we can try out @code{count-words-defun}: install both
14947 @code{count-words-in-defun} and @code{count-words-defun}, and set the
14948 keybinding, and then place the cursor within the following definition:
14949
14950 @smallexample
14951 @group
14952 (defun multiply-by-seven (number)
14953 "Multiply NUMBER by seven."
14954 (* 7 number))
14955 @result{} 10
14956 @end group
14957 @end smallexample
14958
14959 @noindent
14960 Success! The definition has 10 words and symbols.
14961
14962 The next problem is to count the numbers of words and symbols in
14963 several definitions within a single file.
14964
14965 @node Several defuns
14966 @section Count Several @code{defuns} Within a File
14967
14968 A file such as @file{simple.el} may have a hundred or more function
14969 definitions within it. Our long term goal is to collect statistics on
14970 many files, but as a first step, our immediate goal is to collect
14971 statistics on one file.
14972
14973 The information will be a series of numbers, each number being the
14974 length of a function definition. We can store the numbers in a list.
14975
14976 We know that we will want to incorporate the information regarding one
14977 file with information about many other files; this means that the
14978 function for counting definition lengths within one file need only
14979 return the list of lengths. It need not and should not display any
14980 messages.
14981
14982 The word count commands contain one expression to jump point forward
14983 word by word and another expression to count the jumps. The function
14984 to return the lengths of definitions can be designed to work the same
14985 way, with one expression to jump point forward definition by
14986 definition and another expression to construct the lengths' list.
14987
14988 This statement of the problem makes it elementary to write the
14989 function definition. Clearly, we will start the count at the
14990 beginning of the file, so the first command will be @code{(goto-char
14991 (point-min))}. Next, we start the @code{while} loop; and the
14992 true-or-false test of the loop can be a regular expression search for
14993 the next function definition---so long as the search succeeds, point
14994 is moved forward and then the body of the loop is evaluated. The body
14995 needs an expression that constructs the lengths' list. @code{cons},
14996 the list construction command, can be used to create the list. That
14997 is almost all there is to it.
14998
14999 @need 800
15000 Here is what this fragment of code looks like:
15001
15002 @smallexample
15003 @group
15004 (goto-char (point-min))
15005 (while (re-search-forward "^(defun" nil t)
15006 (setq lengths-list
15007 (cons (count-words-in-defun) lengths-list)))
15008 @end group
15009 @end smallexample
15010
15011 What we have left out is the mechanism for finding the file that
15012 contains the function definitions.
15013
15014 In previous examples, we either used this, the Info file, or we
15015 switched back and forth to some other buffer, such as the
15016 @file{*scratch*} buffer.
15017
15018 Finding a file is a new process that we have not yet discussed.
15019
15020 @node Find a File
15021 @section Find a File
15022 @cindex Find a File
15023
15024 To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
15025 command. This command is almost, but not quite right for the lengths
15026 problem.
15027
15028 @need 1200
15029 Let's look at the source for @code{find-file}:
15030
15031 @smallexample
15032 @group
15033 (defun find-file (filename)
15034 "Edit file FILENAME.
15035 Switch to a buffer visiting file FILENAME,
15036 creating one if none already exists."
15037 (interactive "FFind file: ")
15038 (switch-to-buffer (find-file-noselect filename)))
15039 @end group
15040 @end smallexample
15041
15042 @noindent
15043 (The most recent version of the @code{find-file} function definition
15044 permits you to specify optional wildcards to visit multiple files; that
15045 makes the definition more complex and we will not discuss it here,
15046 since it is not relevant. You can see its source using either
15047 @kbd{M-.} (@code{find-tag}) or @kbd{C-h f} (@code{describe-function}).)
15048
15049 @ignore
15050 In Emacs 22
15051 (defun find-file (filename &optional wildcards)
15052 "Edit file FILENAME.
15053 Switch to a buffer visiting file FILENAME,
15054 creating one if none already exists.
15055 Interactively, the default if you just type RET is the current directory,
15056 but the visited file name is available through the minibuffer history:
15057 type M-n to pull it into the minibuffer.
15058
15059 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
15060 expand wildcards (if any) and visit multiple files. You can
15061 suppress wildcard expansion by setting `find-file-wildcards' to nil.
15062
15063 To visit a file without any kind of conversion and without
15064 automatically choosing a major mode, use \\[find-file-literally]."
15065 (interactive (find-file-read-args "Find file: " nil))
15066 (let ((value (find-file-noselect filename nil nil wildcards)))
15067 (if (listp value)
15068 (mapcar 'switch-to-buffer (nreverse value))
15069 (switch-to-buffer value))))
15070 @end ignore
15071
15072 The definition I am showing possesses short but complete documentation
15073 and an interactive specification that prompts you for a file name when
15074 you use the command interactively. The body of the definition
15075 contains two functions, @code{find-file-noselect} and
15076 @code{switch-to-buffer}.
15077
15078 According to its documentation as shown by @kbd{C-h f} (the
15079 @code{describe-function} command), the @code{find-file-noselect}
15080 function reads the named file into a buffer and returns the buffer.
15081 (Its most recent version includes an optional wildcards argument,
15082 too, as well as another to read a file literally and an other you
15083 suppress warning messages. These optional arguments are irrelevant.)
15084
15085 However, the @code{find-file-noselect} function does not select the
15086 buffer in which it puts the file. Emacs does not switch its attention
15087 (or yours if you are using @code{find-file-noselect}) to the selected
15088 buffer. That is what @code{switch-to-buffer} does: it switches the
15089 buffer to which Emacs attention is directed; and it switches the
15090 buffer displayed in the window to the new buffer. We have discussed
15091 buffer switching elsewhere. (@xref{Switching Buffers}.)
15092
15093 In this histogram project, we do not need to display each file on the
15094 screen as the program determines the length of each definition within
15095 it. Instead of employing @code{switch-to-buffer}, we can work with
15096 @code{set-buffer}, which redirects the attention of the computer
15097 program to a different buffer but does not redisplay it on the screen.
15098 So instead of calling on @code{find-file} to do the job, we must write
15099 our own expression.
15100
15101 The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
15102
15103 @node lengths-list-file
15104 @section @code{lengths-list-file} in Detail
15105
15106 The core of the @code{lengths-list-file} function is a @code{while}
15107 loop containing a function to move point forward `defun by defun' and
15108 a function to count the number of words and symbols in each defun.
15109 This core must be surrounded by functions that do various other tasks,
15110 including finding the file, and ensuring that point starts out at the
15111 beginning of the file. The function definition looks like this:
15112 @findex lengths-list-file
15113
15114 @smallexample
15115 @group
15116 (defun lengths-list-file (filename)
15117 "Return list of definitions' lengths within FILE.
15118 The returned list is a list of numbers.
15119 Each number is the number of words or
15120 symbols in one function definition."
15121 @end group
15122 @group
15123 (message "Working on `%s' ... " filename)
15124 (save-excursion
15125 (let ((buffer (find-file-noselect filename))
15126 (lengths-list))
15127 (set-buffer buffer)
15128 (setq buffer-read-only t)
15129 (widen)
15130 (goto-char (point-min))
15131 (while (re-search-forward "^(defun" nil t)
15132 (setq lengths-list
15133 (cons (count-words-in-defun) lengths-list)))
15134 (kill-buffer buffer)
15135 lengths-list)))
15136 @end group
15137 @end smallexample
15138
15139 @noindent
15140 The function is passed one argument, the name of the file on which it
15141 will work. It has four lines of documentation, but no interactive
15142 specification. Since people worry that a computer is broken if they
15143 don't see anything going on, the first line of the body is a
15144 message.
15145
15146 The next line contains a @code{save-excursion} that returns Emacs's
15147 attention to the current buffer when the function completes. This is
15148 useful in case you embed this function in another function that
15149 presumes point is restored to the original buffer.
15150
15151 In the varlist of the @code{let} expression, Emacs finds the file and
15152 binds the local variable @code{buffer} to the buffer containing the
15153 file. At the same time, Emacs creates @code{lengths-list} as a local
15154 variable.
15155
15156 Next, Emacs switches its attention to the buffer.
15157
15158 In the following line, Emacs makes the buffer read-only. Ideally,
15159 this line is not necessary. None of the functions for counting words
15160 and symbols in a function definition should change the buffer.
15161 Besides, the buffer is not going to be saved, even if it were changed.
15162 This line is entirely the consequence of great, perhaps excessive,
15163 caution. The reason for the caution is that this function and those
15164 it calls work on the sources for Emacs and it is inconvenient if they
15165 are inadvertently modified. It goes without saying that I did not
15166 realize a need for this line until an experiment went awry and started
15167 to modify my Emacs source files @dots{}
15168
15169 Next comes a call to widen the buffer if it is narrowed. This
15170 function is usually not needed---Emacs creates a fresh buffer if none
15171 already exists; but if a buffer visiting the file already exists Emacs
15172 returns that one. In this case, the buffer may be narrowed and must
15173 be widened. If we wanted to be fully `user-friendly', we would
15174 arrange to save the restriction and the location of point, but we
15175 won't.
15176
15177 The @code{(goto-char (point-min))} expression moves point to the
15178 beginning of the buffer.
15179
15180 Then comes a @code{while} loop in which the `work' of the function is
15181 carried out. In the loop, Emacs determines the length of each
15182 definition and constructs a lengths' list containing the information.
15183
15184 Emacs kills the buffer after working through it. This is to save
15185 space inside of Emacs. My version of GNU Emacs 19 contained over 300
15186 source files of interest; GNU Emacs 22 contains over a thousand source
15187 files. Another function will apply @code{lengths-list-file} to each
15188 of the files.
15189
15190 Finally, the last expression within the @code{let} expression is the
15191 @code{lengths-list} variable; its value is returned as the value of
15192 the whole function.
15193
15194 You can try this function by installing it in the usual fashion. Then
15195 place your cursor after the following expression and type @kbd{C-x
15196 C-e} (@code{eval-last-sexp}).
15197
15198 @c !!! 22.1.1 lisp sources location here
15199 @smallexample
15200 (lengths-list-file
15201 "/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el")
15202 @end smallexample
15203
15204 @noindent
15205 (You may need to change the pathname of the file; the one here is for
15206 GNU Emacs version 22.1.1. To change the expression, copy it to
15207 the @file{*scratch*} buffer and edit it.
15208
15209 @need 1200
15210 @noindent
15211 (Also, to see the full length of the list, rather than a truncated
15212 version, you may have to evaluate the following:
15213
15214 @smallexample
15215 (custom-set-variables '(eval-expression-print-length nil))
15216 @end smallexample
15217
15218 @noindent
15219 (@xref{defcustom, , Specifying Variables using @code{defcustom}}.
15220 Then evaluate the @code{lengths-list-file} expression.)
15221
15222 @need 1200
15223 The lengths' list for @file{debug.el} takes less than a second to
15224 produce and looks like this in GNU Emacs 22:
15225
15226 @smallexample
15227 (83 113 105 144 289 22 30 97 48 89 25 52 52 88 28 29 77 49 43 290 232 587)
15228 @end smallexample
15229
15230 @need 1500
15231 (Using my old machine, the version 19 lengths' list for @file{debug.el}
15232 took seven seconds to produce and looked like this:
15233
15234 @smallexample
15235 (75 41 80 62 20 45 44 68 45 12 34 235)
15236 @end smallexample
15237
15238 (The newer version of @file{debug.el} contains more defuns than the
15239 earlier one; and my new machine is much faster than the old one.)
15240
15241 Note that the length of the last definition in the file is first in
15242 the list.
15243
15244 @node Several files
15245 @section Count Words in @code{defuns} in Different Files
15246
15247 In the previous section, we created a function that returns a list of
15248 the lengths of each definition in a file. Now, we want to define a
15249 function to return a master list of the lengths of the definitions in
15250 a list of files.
15251
15252 Working on each of a list of files is a repetitious act, so we can use
15253 either a @code{while} loop or recursion.
15254
15255 @menu
15256 * lengths-list-many-files:: Return a list of the lengths of defuns.
15257 * append:: Attach one list to another.
15258 @end menu
15259
15260 @ifnottex
15261 @node lengths-list-many-files
15262 @unnumberedsubsec Determine the lengths of @code{defuns}
15263 @end ifnottex
15264
15265 The design using a @code{while} loop is routine. The argument passed
15266 the function is a list of files. As we saw earlier (@pxref{Loop
15267 Example}), you can write a @code{while} loop so that the body of the
15268 loop is evaluated if such a list contains elements, but to exit the
15269 loop if the list is empty. For this design to work, the body of the
15270 loop must contain an expression that shortens the list each time the
15271 body is evaluated, so that eventually the list is empty. The usual
15272 technique is to set the value of the list to the value of the @sc{cdr}
15273 of the list each time the body is evaluated.
15274
15275 @need 800
15276 The template looks like this:
15277
15278 @smallexample
15279 @group
15280 (while @var{test-whether-list-is-empty}
15281 @var{body}@dots{}
15282 @var{set-list-to-cdr-of-list})
15283 @end group
15284 @end smallexample
15285
15286 Also, we remember that a @code{while} loop returns @code{nil} (the
15287 result of evaluating the true-or-false-test), not the result of any
15288 evaluation within its body. (The evaluations within the body of the
15289 loop are done for their side effects.) However, the expression that
15290 sets the lengths' list is part of the body---and that is the value
15291 that we want returned by the function as a whole. To do this, we
15292 enclose the @code{while} loop within a @code{let} expression, and
15293 arrange that the last element of the @code{let} expression contains
15294 the value of the lengths' list. (@xref{Incrementing Example, , Loop
15295 Example with an Incrementing Counter}.)
15296
15297 @findex lengths-list-many-files
15298 @need 1250
15299 These considerations lead us directly to the function itself:
15300
15301 @smallexample
15302 @group
15303 ;;; @r{Use @code{while} loop.}
15304 (defun lengths-list-many-files (list-of-files)
15305 "Return list of lengths of defuns in LIST-OF-FILES."
15306 @end group
15307 @group
15308 (let (lengths-list)
15309
15310 ;;; @r{true-or-false-test}
15311 (while list-of-files
15312 (setq lengths-list
15313 (append
15314 lengths-list
15315
15316 ;;; @r{Generate a lengths' list.}
15317 (lengths-list-file
15318 (expand-file-name (car list-of-files)))))
15319 @end group
15320
15321 @group
15322 ;;; @r{Make files' list shorter.}
15323 (setq list-of-files (cdr list-of-files)))
15324
15325 ;;; @r{Return final value of lengths' list.}
15326 lengths-list))
15327 @end group
15328 @end smallexample
15329
15330 @code{expand-file-name} is a built-in function that converts a file
15331 name to the absolute, long, path name form. The function employs the
15332 name of the directory in which the function is called.
15333
15334 @c !!! 22.1.1 lisp sources location here
15335 @need 1500
15336 Thus, if @code{expand-file-name} is called on @code{debug.el} when
15337 Emacs is visiting the
15338 @file{/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/} directory,
15339
15340 @smallexample
15341 debug.el
15342 @end smallexample
15343
15344 @need 800
15345 @noindent
15346 becomes
15347
15348 @c !!! 22.1.1 lisp sources location here
15349 @smallexample
15350 /usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el
15351 @end smallexample
15352
15353 The only other new element of this function definition is the as yet
15354 unstudied function @code{append}, which merits a short section for
15355 itself.
15356
15357 @node append
15358 @subsection The @code{append} Function
15359
15360 @need 800
15361 The @code{append} function attaches one list to another. Thus,
15362
15363 @smallexample
15364 (append '(1 2 3 4) '(5 6 7 8))
15365 @end smallexample
15366
15367 @need 800
15368 @noindent
15369 produces the list
15370
15371 @smallexample
15372 (1 2 3 4 5 6 7 8)
15373 @end smallexample
15374
15375 This is exactly how we want to attach two lengths' lists produced by
15376 @code{lengths-list-file} to each other. The results contrast with
15377 @code{cons},
15378
15379 @smallexample
15380 (cons '(1 2 3 4) '(5 6 7 8))
15381 @end smallexample
15382
15383 @need 1250
15384 @noindent
15385 which constructs a new list in which the first argument to @code{cons}
15386 becomes the first element of the new list:
15387
15388 @smallexample
15389 ((1 2 3 4) 5 6 7 8)
15390 @end smallexample
15391
15392 @node Several files recursively
15393 @section Recursively Count Words in Different Files
15394
15395 Besides a @code{while} loop, you can work on each of a list of files
15396 with recursion. A recursive version of @code{lengths-list-many-files}
15397 is short and simple.
15398
15399 The recursive function has the usual parts: the `do-again-test', the
15400 `next-step-expression', and the recursive call. The `do-again-test'
15401 determines whether the function should call itself again, which it
15402 will do if the @code{list-of-files} contains any remaining elements;
15403 the `next-step-expression' resets the @code{list-of-files} to the
15404 @sc{cdr} of itself, so eventually the list will be empty; and the
15405 recursive call calls itself on the shorter list. The complete
15406 function is shorter than this description!
15407 @findex recursive-lengths-list-many-files
15408
15409 @smallexample
15410 @group
15411 (defun recursive-lengths-list-many-files (list-of-files)
15412 "Return list of lengths of each defun in LIST-OF-FILES."
15413 (if list-of-files ; @r{do-again-test}
15414 (append
15415 (lengths-list-file
15416 (expand-file-name (car list-of-files)))
15417 (recursive-lengths-list-many-files
15418 (cdr list-of-files)))))
15419 @end group
15420 @end smallexample
15421
15422 @noindent
15423 In a sentence, the function returns the lengths' list for the first of
15424 the @code{list-of-files} appended to the result of calling itself on
15425 the rest of the @code{list-of-files}.
15426
15427 Here is a test of @code{recursive-lengths-list-many-files}, along with
15428 the results of running @code{lengths-list-file} on each of the files
15429 individually.
15430
15431 Install @code{recursive-lengths-list-many-files} and
15432 @code{lengths-list-file}, if necessary, and then evaluate the
15433 following expressions. You may need to change the files' pathnames;
15434 those here work when this Info file and the Emacs sources are located
15435 in their customary places. To change the expressions, copy them to
15436 the @file{*scratch*} buffer, edit them, and then evaluate them.
15437
15438 The results are shown after the @samp{@result{}}. (These results are
15439 for files from Emacs version 22.1.1; files from other versions of
15440 Emacs may produce different results.)
15441
15442 @c !!! 22.1.1 lisp sources location here
15443 @smallexample
15444 @group
15445 (cd "/usr/local/share/emacs/22.1.1/")
15446
15447 (lengths-list-file "./lisp/macros.el")
15448 @result{} (283 263 480 90)
15449 @end group
15450
15451 @group
15452 (lengths-list-file "./lisp/mail/mailalias.el")
15453 @result{} (38 32 29 95 178 180 321 218 324)
15454 @end group
15455
15456 @group
15457 (lengths-list-file "./lisp/makesum.el")
15458 @result{} (85 181)
15459 @end group
15460
15461 @group
15462 (recursive-lengths-list-many-files
15463 '("./lisp/macros.el"
15464 "./lisp/mail/mailalias.el"
15465 "./lisp/makesum.el"))
15466 @result{} (283 263 480 90 38 32 29 95 178 180 321 218 324 85 181)
15467 @end group
15468 @end smallexample
15469
15470 The @code{recursive-lengths-list-many-files} function produces the
15471 output we want.
15472
15473 The next step is to prepare the data in the list for display in a graph.
15474
15475 @node Prepare the data
15476 @section Prepare the Data for Display in a Graph
15477
15478 The @code{recursive-lengths-list-many-files} function returns a list
15479 of numbers. Each number records the length of a function definition.
15480 What we need to do now is transform this data into a list of numbers
15481 suitable for generating a graph. The new list will tell how many
15482 functions definitions contain less than 10 words and
15483 symbols, how many contain between 10 and 19 words and symbols, how
15484 many contain between 20 and 29 words and symbols, and so on.
15485
15486 In brief, we need to go through the lengths' list produced by the
15487 @code{recursive-lengths-list-many-files} function and count the number
15488 of defuns within each range of lengths, and produce a list of those
15489 numbers.
15490
15491 @menu
15492 * Data for Display in Detail::
15493 * Sorting:: Sorting lists.
15494 * Files List:: Making a list of files.
15495 * Counting function definitions::
15496 @end menu
15497
15498 @ifnottex
15499 @node Data for Display in Detail
15500 @unnumberedsubsec The Data for Display in Detail
15501 @end ifnottex
15502
15503 Based on what we have done before, we can readily foresee that it
15504 should not be too hard to write a function that `@sc{cdr}s' down the
15505 lengths' list, looks at each element, determines which length range it
15506 is in, and increments a counter for that range.
15507
15508 However, before beginning to write such a function, we should consider
15509 the advantages of sorting the lengths' list first, so the numbers are
15510 ordered from smallest to largest. First, sorting will make it easier
15511 to count the numbers in each range, since two adjacent numbers will
15512 either be in the same length range or in adjacent ranges. Second, by
15513 inspecting a sorted list, we can discover the highest and lowest
15514 number, and thereby determine the largest and smallest length range
15515 that we will need.
15516
15517 @node Sorting
15518 @subsection Sorting Lists
15519 @findex sort
15520
15521 Emacs contains a function to sort lists, called (as you might guess)
15522 @code{sort}. The @code{sort} function takes two arguments, the list
15523 to be sorted, and a predicate that determines whether the first of
15524 two list elements is ``less'' than the second.
15525
15526 As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
15527 Type Object as an Argument}), a predicate is a function that
15528 determines whether some property is true or false. The @code{sort}
15529 function will reorder a list according to whatever property the
15530 predicate uses; this means that @code{sort} can be used to sort
15531 non-numeric lists by non-numeric criteria---it can, for example,
15532 alphabetize a list.
15533
15534 @need 1250
15535 The @code{<} function is used when sorting a numeric list. For example,
15536
15537 @smallexample
15538 (sort '(4 8 21 17 33 7 21 7) '<)
15539 @end smallexample
15540
15541 @need 800
15542 @noindent
15543 produces this:
15544
15545 @smallexample
15546 (4 7 7 8 17 21 21 33)
15547 @end smallexample
15548
15549 @noindent
15550 (Note that in this example, both the arguments are quoted so that the
15551 symbols are not evaluated before being passed to @code{sort} as
15552 arguments.)
15553
15554 Sorting the list returned by the
15555 @code{recursive-lengths-list-many-files} function is straightforward;
15556 it uses the @code{<} function:
15557
15558 @ignore
15559 2006 Oct 29
15560 In GNU Emacs 22, eval
15561 (progn
15562 (cd "/usr/local/share/emacs/22.0.50/")
15563 (sort
15564 (recursive-lengths-list-many-files
15565 '("./lisp/macros.el"
15566 "./lisp/mail/mailalias.el"
15567 "./lisp/makesum.el"))
15568 '<))
15569
15570 @end ignore
15571
15572 @smallexample
15573 @group
15574 (sort
15575 (recursive-lengths-list-many-files
15576 '("./lisp/macros.el"
15577 "./lisp/mailalias.el"
15578 "./lisp/makesum.el"))
15579 '<)
15580 @end group
15581 @end smallexample
15582
15583 @need 800
15584 @noindent
15585 which produces:
15586
15587 @smallexample
15588 (29 32 38 85 90 95 178 180 181 218 263 283 321 324 480)
15589 @end smallexample
15590
15591 @noindent
15592 (Note that in this example, the first argument to @code{sort} is not
15593 quoted, since the expression must be evaluated so as to produce the
15594 list that is passed to @code{sort}.)
15595
15596 @node Files List
15597 @subsection Making a List of Files
15598
15599 The @code{recursive-lengths-list-many-files} function requires a list
15600 of files as its argument. For our test examples, we constructed such
15601 a list by hand; but the Emacs Lisp source directory is too large for
15602 us to do for that. Instead, we will write a function to do the job
15603 for us. In this function, we will use both a @code{while} loop and a
15604 recursive call.
15605
15606 @findex directory-files
15607 We did not have to write a function like this for older versions of
15608 GNU Emacs, since they placed all the @samp{.el} files in one
15609 directory. Instead, we were able to use the @code{directory-files}
15610 function, which lists the names of files that match a specified
15611 pattern within a single directory.
15612
15613 However, recent versions of Emacs place Emacs Lisp files in
15614 sub-directories of the top level @file{lisp} directory. This
15615 re-arrangement eases navigation. For example, all the mail related
15616 files are in a @file{lisp} sub-directory called @file{mail}. But at
15617 the same time, this arrangement forces us to create a file listing
15618 function that descends into the sub-directories.
15619
15620 @findex files-in-below-directory
15621 We can create this function, called @code{files-in-below-directory},
15622 using familiar functions such as @code{car}, @code{nthcdr}, and
15623 @code{substring} in conjunction with an existing function called
15624 @code{directory-files-and-attributes}. This latter function not only
15625 lists all the filenames in a directory, including the names
15626 of sub-directories, but also their attributes.
15627
15628 To restate our goal: to create a function that will enable us
15629 to feed filenames to @code{recursive-lengths-list-many-files}
15630 as a list that looks like this (but with more elements):
15631
15632 @smallexample
15633 @group
15634 ("./lisp/macros.el"
15635 "./lisp/mail/rmail.el"
15636 "./lisp/makesum.el")
15637 @end group
15638 @end smallexample
15639
15640 The @code{directory-files-and-attributes} function returns a list of
15641 lists. Each of the lists within the main list consists of 13
15642 elements. The first element is a string that contains the name of the
15643 file---which, in GNU/Linux, may be a `directory file', that is to
15644 say, a file with the special attributes of a directory. The second
15645 element of the list is @code{t} for a directory, a string
15646 for symbolic link (the string is the name linked to), or @code{nil}.
15647
15648 For example, the first @samp{.el} file in the @file{lisp/} directory
15649 is @file{abbrev.el}. Its name is
15650 @file{/usr/local/share/emacs/22.1.1/lisp/abbrev.el} and it is not a
15651 directory or a symbolic link.
15652
15653 @need 1000
15654 This is how @code{directory-files-and-attributes} lists that file and
15655 its attributes:
15656
15657 @smallexample
15658 @group
15659 ("abbrev.el"
15660 nil
15661 1
15662 1000
15663 100
15664 @end group
15665 @group
15666 (20615 27034 579989 697000)
15667 (17905 55681 0 0)
15668 (20615 26327 734791 805000)
15669 13188
15670 "-rw-r--r--"
15671 @end group
15672 @group
15673 nil
15674 2971624
15675 773)
15676 @end group
15677 @end smallexample
15678
15679 @need 1200
15680 On the other hand, @file{mail/} is a directory within the @file{lisp/}
15681 directory. The beginning of its listing looks like this:
15682
15683 @smallexample
15684 @group
15685 ("mail"
15686 t
15687 @dots{}
15688 )
15689 @end group
15690 @end smallexample
15691
15692 (To learn about the different attributes, look at the documentation of
15693 @code{file-attributes}. Bear in mind that the @code{file-attributes}
15694 function does not list the filename, so its first element is
15695 @code{directory-files-and-attributes}'s second element.)
15696
15697 We will want our new function, @code{files-in-below-directory}, to
15698 list the @samp{.el} files in the directory it is told to check, and in
15699 any directories below that directory.
15700
15701 This gives us a hint on how to construct
15702 @code{files-in-below-directory}: within a directory, the function
15703 should add @samp{.el} filenames to a list; and if, within a directory,
15704 the function comes upon a sub-directory, it should go into that
15705 sub-directory and repeat its actions.
15706
15707 However, we should note that every directory contains a name that
15708 refers to itself, called @file{.}, (``dot'') and a name that refers to
15709 its parent directory, called @file{..} (``double dot''). (In
15710 @file{/}, the root directory, @file{..} refers to itself, since
15711 @file{/} has no parent.) Clearly, we do not want our
15712 @code{files-in-below-directory} function to enter those directories,
15713 since they always lead us, directly or indirectly, to the current
15714 directory.
15715
15716 Consequently, our @code{files-in-below-directory} function must do
15717 several tasks:
15718
15719 @itemize @bullet
15720 @item
15721 Check to see whether it is looking at a filename that ends in
15722 @samp{.el}; and if so, add its name to a list.
15723
15724 @item
15725 Check to see whether it is looking at a filename that is the name of a
15726 directory; and if so,
15727
15728 @itemize @minus
15729 @item
15730 Check to see whether it is looking at @file{.} or @file{..}; and if
15731 so skip it.
15732
15733 @item
15734 Or else, go into that directory and repeat the process.
15735 @end itemize
15736 @end itemize
15737
15738 Let's write a function definition to do these tasks. We will use a
15739 @code{while} loop to move from one filename to another within a
15740 directory, checking what needs to be done; and we will use a recursive
15741 call to repeat the actions on each sub-directory. The recursive
15742 pattern is `accumulate'
15743 (@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
15744 using @code{append} as the combiner.
15745
15746 @ignore
15747 (directory-files "/usr/local/src/emacs/lisp/" t "\\.el$")
15748 (shell-command "find /usr/local/src/emacs/lisp/ -name '*.el'")
15749
15750 (directory-files "/usr/local/share/emacs/22.1.1/lisp/" t "\\.el$")
15751 (shell-command "find /usr/local/share/emacs/22.1.1/lisp/ -name '*.el'")
15752 @end ignore
15753
15754 @c /usr/local/share/emacs/22.1.1/lisp/
15755
15756 @need 800
15757 Here is the function:
15758
15759 @smallexample
15760 @group
15761 (defun files-in-below-directory (directory)
15762 "List the .el files in DIRECTORY and in its sub-directories."
15763 ;; Although the function will be used non-interactively,
15764 ;; it will be easier to test if we make it interactive.
15765 ;; The directory will have a name such as
15766 ;; "/usr/local/share/emacs/22.1.1/lisp/"
15767 (interactive "DDirectory name: ")
15768 @end group
15769 @group
15770 (let (el-files-list
15771 (current-directory-list
15772 (directory-files-and-attributes directory t)))
15773 ;; while we are in the current directory
15774 (while current-directory-list
15775 @end group
15776 @group
15777 (cond
15778 ;; check to see whether filename ends in `.el'
15779 ;; and if so, append its name to a list.
15780 ((equal ".el" (substring (car (car current-directory-list)) -3))
15781 (setq el-files-list
15782 (cons (car (car current-directory-list)) el-files-list)))
15783 @end group
15784 @group
15785 ;; check whether filename is that of a directory
15786 ((eq t (car (cdr (car current-directory-list))))
15787 ;; decide whether to skip or recurse
15788 (if
15789 (equal "."
15790 (substring (car (car current-directory-list)) -1))
15791 ;; then do nothing since filename is that of
15792 ;; current directory or parent, "." or ".."
15793 ()
15794 @end group
15795 @group
15796 ;; else descend into the directory and repeat the process
15797 (setq el-files-list
15798 (append
15799 (files-in-below-directory
15800 (car (car current-directory-list)))
15801 el-files-list)))))
15802 ;; move to the next filename in the list; this also
15803 ;; shortens the list so the while loop eventually comes to an end
15804 (setq current-directory-list (cdr current-directory-list)))
15805 ;; return the filenames
15806 el-files-list))
15807 @end group
15808 @end smallexample
15809
15810 @c (files-in-below-directory "/usr/local/src/emacs/lisp/")
15811 @c (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15812
15813 The @code{files-in-below-directory} @code{directory-files} function
15814 takes one argument, the name of a directory.
15815
15816 @need 1250
15817 Thus, on my system,
15818
15819 @c (length (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15820
15821 @c !!! 22.1.1 lisp sources location here
15822 @smallexample
15823 @group
15824 (length
15825 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/"))
15826 @end group
15827 @end smallexample
15828
15829 @noindent
15830 tells me that in and below my Lisp sources directory are 1031
15831 @samp{.el} files.
15832
15833 @code{files-in-below-directory} returns a list in reverse alphabetical
15834 order. An expression to sort the list in alphabetical order looks
15835 like this:
15836
15837 @smallexample
15838 @group
15839 (sort
15840 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15841 'string-lessp)
15842 @end group
15843 @end smallexample
15844
15845 @ignore
15846 (defun test ()
15847 "Test how long it takes to find lengths of all sorted elisp defuns."
15848 (insert "\n" (current-time-string) "\n")
15849 (sit-for 0)
15850 (sort
15851 (recursive-lengths-list-many-files
15852 (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15853 '<)
15854 (insert (format "%s" (current-time-string))))
15855 @end ignore
15856
15857 @node Counting function definitions
15858 @subsection Counting function definitions
15859
15860 Our immediate goal is to generate a list that tells us how many
15861 function definitions contain fewer than 10 words and symbols, how many
15862 contain between 10 and 19 words and symbols, how many contain between
15863 20 and 29 words and symbols, and so on.
15864
15865 With a sorted list of numbers, this is easy: count how many elements
15866 of the list are smaller than 10, then, after moving past the numbers
15867 just counted, count how many are smaller than 20, then, after moving
15868 past the numbers just counted, count how many are smaller than 30, and
15869 so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
15870 larger than the top of that range. We can call the list of such
15871 numbers the @code{top-of-ranges} list.
15872
15873 @need 1200
15874 If we wished, we could generate this list automatically, but it is
15875 simpler to write a list manually. Here it is:
15876 @vindex top-of-ranges
15877
15878 @smallexample
15879 @group
15880 (defvar top-of-ranges
15881 '(10 20 30 40 50
15882 60 70 80 90 100
15883 110 120 130 140 150
15884 160 170 180 190 200
15885 210 220 230 240 250
15886 260 270 280 290 300)
15887 "List specifying ranges for `defuns-per-range'.")
15888 @end group
15889 @end smallexample
15890
15891 To change the ranges, we edit this list.
15892
15893 Next, we need to write the function that creates the list of the
15894 number of definitions within each range. Clearly, this function must
15895 take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15896 as arguments.
15897
15898 The @code{defuns-per-range} function must do two things again and
15899 again: it must count the number of definitions within a range
15900 specified by the current top-of-range value; and it must shift to the
15901 next higher value in the @code{top-of-ranges} list after counting the
15902 number of definitions in the current range. Since each of these
15903 actions is repetitive, we can use @code{while} loops for the job.
15904 One loop counts the number of definitions in the range defined by the
15905 current top-of-range value, and the other loop selects each of the
15906 top-of-range values in turn.
15907
15908 Several entries of the @code{sorted-lengths} list are counted for each
15909 range; this means that the loop for the @code{sorted-lengths} list
15910 will be inside the loop for the @code{top-of-ranges} list, like a
15911 small gear inside a big gear.
15912
15913 The inner loop counts the number of definitions within the range. It
15914 is a simple counting loop of the type we have seen before.
15915 (@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15916 The true-or-false test of the loop tests whether the value from the
15917 @code{sorted-lengths} list is smaller than the current value of the
15918 top of the range. If it is, the function increments the counter and
15919 tests the next value from the @code{sorted-lengths} list.
15920
15921 @need 1250
15922 The inner loop looks like this:
15923
15924 @smallexample
15925 @group
15926 (while @var{length-element-smaller-than-top-of-range}
15927 (setq number-within-range (1+ number-within-range))
15928 (setq sorted-lengths (cdr sorted-lengths)))
15929 @end group
15930 @end smallexample
15931
15932 The outer loop must start with the lowest value of the
15933 @code{top-of-ranges} list, and then be set to each of the succeeding
15934 higher values in turn. This can be done with a loop like this:
15935
15936 @smallexample
15937 @group
15938 (while top-of-ranges
15939 @var{body-of-loop}@dots{}
15940 (setq top-of-ranges (cdr top-of-ranges)))
15941 @end group
15942 @end smallexample
15943
15944 @need 1200
15945 Put together, the two loops look like this:
15946
15947 @smallexample
15948 @group
15949 (while top-of-ranges
15950
15951 ;; @r{Count the number of elements within the current range.}
15952 (while @var{length-element-smaller-than-top-of-range}
15953 (setq number-within-range (1+ number-within-range))
15954 (setq sorted-lengths (cdr sorted-lengths)))
15955
15956 ;; @r{Move to next range.}
15957 (setq top-of-ranges (cdr top-of-ranges)))
15958 @end group
15959 @end smallexample
15960
15961 In addition, in each circuit of the outer loop, Emacs should record
15962 the number of definitions within that range (the value of
15963 @code{number-within-range}) in a list. We can use @code{cons} for
15964 this purpose. (@xref{cons, , @code{cons}}.)
15965
15966 The @code{cons} function works fine, except that the list it
15967 constructs will contain the number of definitions for the highest
15968 range at its beginning and the number of definitions for the lowest
15969 range at its end. This is because @code{cons} attaches new elements
15970 of the list to the beginning of the list, and since the two loops are
15971 working their way through the lengths' list from the lower end first,
15972 the @code{defuns-per-range-list} will end up largest number first.
15973 But we will want to print our graph with smallest values first and the
15974 larger later. The solution is to reverse the order of the
15975 @code{defuns-per-range-list}. We can do this using the
15976 @code{nreverse} function, which reverses the order of a list.
15977 @findex nreverse
15978
15979 @need 800
15980 For example,
15981
15982 @smallexample
15983 (nreverse '(1 2 3 4))
15984 @end smallexample
15985
15986 @need 800
15987 @noindent
15988 produces:
15989
15990 @smallexample
15991 (4 3 2 1)
15992 @end smallexample
15993
15994 Note that the @code{nreverse} function is ``destructive''---that is,
15995 it changes the list to which it is applied; this contrasts with the
15996 @code{car} and @code{cdr} functions, which are non-destructive. In
15997 this case, we do not want the original @code{defuns-per-range-list},
15998 so it does not matter that it is destroyed. (The @code{reverse}
15999 function provides a reversed copy of a list, leaving the original list
16000 as is.)
16001 @findex reverse
16002
16003 @need 1250
16004 Put all together, the @code{defuns-per-range} looks like this:
16005
16006 @smallexample
16007 @group
16008 (defun defuns-per-range (sorted-lengths top-of-ranges)
16009 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
16010 (let ((top-of-range (car top-of-ranges))
16011 (number-within-range 0)
16012 defuns-per-range-list)
16013 @end group
16014
16015 @group
16016 ;; @r{Outer loop.}
16017 (while top-of-ranges
16018 @end group
16019
16020 @group
16021 ;; @r{Inner loop.}
16022 (while (and
16023 ;; @r{Need number for numeric test.}
16024 (car sorted-lengths)
16025 (< (car sorted-lengths) top-of-range))
16026 @end group
16027
16028 @group
16029 ;; @r{Count number of definitions within current range.}
16030 (setq number-within-range (1+ number-within-range))
16031 (setq sorted-lengths (cdr sorted-lengths)))
16032
16033 ;; @r{Exit inner loop but remain within outer loop.}
16034 @end group
16035
16036 @group
16037 (setq defuns-per-range-list
16038 (cons number-within-range defuns-per-range-list))
16039 (setq number-within-range 0) ; @r{Reset count to zero.}
16040 @end group
16041
16042 @group
16043 ;; @r{Move to next range.}
16044 (setq top-of-ranges (cdr top-of-ranges))
16045 ;; @r{Specify next top of range value.}
16046 (setq top-of-range (car top-of-ranges)))
16047 @end group
16048
16049 @group
16050 ;; @r{Exit outer loop and count the number of defuns larger than}
16051 ;; @r{ the largest top-of-range value.}
16052 (setq defuns-per-range-list
16053 (cons
16054 (length sorted-lengths)
16055 defuns-per-range-list))
16056 @end group
16057
16058 @group
16059 ;; @r{Return a list of the number of definitions within each range,}
16060 ;; @r{ smallest to largest.}
16061 (nreverse defuns-per-range-list)))
16062 @end group
16063 @end smallexample
16064
16065 @need 1200
16066 @noindent
16067 The function is straightforward except for one subtle feature. The
16068 true-or-false test of the inner loop looks like this:
16069
16070 @smallexample
16071 @group
16072 (and (car sorted-lengths)
16073 (< (car sorted-lengths) top-of-range))
16074 @end group
16075 @end smallexample
16076
16077 @need 800
16078 @noindent
16079 instead of like this:
16080
16081 @smallexample
16082 (< (car sorted-lengths) top-of-range)
16083 @end smallexample
16084
16085 The purpose of the test is to determine whether the first item in the
16086 @code{sorted-lengths} list is less than the value of the top of the
16087 range.
16088
16089 The simple version of the test works fine unless the
16090 @code{sorted-lengths} list has a @code{nil} value. In that case, the
16091 @code{(car sorted-lengths)} expression function returns
16092 @code{nil}. The @code{<} function cannot compare a number to
16093 @code{nil}, which is an empty list, so Emacs signals an error and
16094 stops the function from attempting to continue to execute.
16095
16096 The @code{sorted-lengths} list always becomes @code{nil} when the
16097 counter reaches the end of the list. This means that any attempt to
16098 use the @code{defuns-per-range} function with the simple version of
16099 the test will fail.
16100
16101 We solve the problem by using the @code{(car sorted-lengths)}
16102 expression in conjunction with the @code{and} expression. The
16103 @code{(car sorted-lengths)} expression returns a non-@code{nil}
16104 value so long as the list has at least one number within it, but
16105 returns @code{nil} if the list is empty. The @code{and} expression
16106 first evaluates the @code{(car sorted-lengths)} expression, and
16107 if it is @code{nil}, returns false @emph{without} evaluating the
16108 @code{<} expression. But if the @code{(car sorted-lengths)}
16109 expression returns a non-@code{nil} value, the @code{and} expression
16110 evaluates the @code{<} expression, and returns that value as the value
16111 of the @code{and} expression.
16112
16113 @c colon in printed section title causes problem in Info cross reference
16114 This way, we avoid an error.
16115 @iftex
16116 @noindent
16117 (For information about @code{and}, see
16118 @ref{kill-new function, , The @code{kill-new} function}.)
16119 @end iftex
16120 @ifinfo
16121 @noindent
16122 (@xref{kill-new function, , The @code{kill-new} function}, for
16123 information about @code{and}.)
16124 @end ifinfo
16125
16126 Here is a short test of the @code{defuns-per-range} function. First,
16127 evaluate the expression that binds (a shortened)
16128 @code{top-of-ranges} list to the list of values, then evaluate the
16129 expression for binding the @code{sorted-lengths} list, and then
16130 evaluate the @code{defuns-per-range} function.
16131
16132 @smallexample
16133 @group
16134 ;; @r{(Shorter list than we will use later.)}
16135 (setq top-of-ranges
16136 '(110 120 130 140 150
16137 160 170 180 190 200))
16138
16139 (setq sorted-lengths
16140 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
16141
16142 (defuns-per-range sorted-lengths top-of-ranges)
16143 @end group
16144 @end smallexample
16145
16146 @need 800
16147 @noindent
16148 The list returned looks like this:
16149
16150 @smallexample
16151 (2 2 2 0 0 1 0 2 0 0 4)
16152 @end smallexample
16153
16154 @noindent
16155 Indeed, there are two elements of the @code{sorted-lengths} list
16156 smaller than 110, two elements between 110 and 119, two elements
16157 between 120 and 129, and so on. There are four elements with a value
16158 of 200 or larger.
16159
16160 @c The next step is to turn this numbers' list into a graph.
16161 @node Readying a Graph
16162 @chapter Readying a Graph
16163 @cindex Readying a graph
16164 @cindex Graph prototype
16165 @cindex Prototype graph
16166 @cindex Body of graph
16167
16168 Our goal is to construct a graph showing the numbers of function
16169 definitions of various lengths in the Emacs lisp sources.
16170
16171 As a practical matter, if you were creating a graph, you would
16172 probably use a program such as @code{gnuplot} to do the job.
16173 (@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
16174 however, we create one from scratch, and in the process we will
16175 re-acquaint ourselves with some of what we learned before and learn
16176 more.
16177
16178 In this chapter, we will first write a simple graph printing function.
16179 This first definition will be a @dfn{prototype}, a rapidly written
16180 function that enables us to reconnoiter this unknown graph-making
16181 territory. We will discover dragons, or find that they are myth.
16182 After scouting the terrain, we will feel more confident and enhance
16183 the function to label the axes automatically.
16184
16185 @menu
16186 * Columns of a graph::
16187 * graph-body-print:: How to print the body of a graph.
16188 * recursive-graph-body-print::
16189 * Printed Axes::
16190 * Line Graph Exercise::
16191 @end menu
16192
16193 @ifnottex
16194 @node Columns of a graph
16195 @unnumberedsec Printing the Columns of a Graph
16196 @end ifnottex
16197
16198 Since Emacs is designed to be flexible and work with all kinds of
16199 terminals, including character-only terminals, the graph will need to
16200 be made from one of the `typewriter' symbols. An asterisk will do; as
16201 we enhance the graph-printing function, we can make the choice of
16202 symbol a user option.
16203
16204 We can call this function @code{graph-body-print}; it will take a
16205 @code{numbers-list} as its only argument. At this stage, we will not
16206 label the graph, but only print its body.
16207
16208 The @code{graph-body-print} function inserts a vertical column of
16209 asterisks for each element in the @code{numbers-list}. The height of
16210 each line is determined by the value of that element of the
16211 @code{numbers-list}.
16212
16213 Inserting columns is a repetitive act; that means that this function can
16214 be written either with a @code{while} loop or recursively.
16215
16216 Our first challenge is to discover how to print a column of asterisks.
16217 Usually, in Emacs, we print characters onto a screen horizontally,
16218 line by line, by typing. We have two routes we can follow: write our
16219 own column-insertion function or discover whether one exists in Emacs.
16220
16221 To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
16222 command. This command is like the @kbd{C-h a} (@code{command-apropos})
16223 command, except that the latter finds only those functions that are
16224 commands. The @kbd{M-x apropos} command lists all symbols that match
16225 a regular expression, including functions that are not interactive.
16226 @findex apropos
16227
16228 What we want to look for is some command that prints or inserts
16229 columns. Very likely, the name of the function will contain either
16230 the word `print' or the word `insert' or the word `column'.
16231 Therefore, we can simply type @kbd{M-x apropos RET
16232 print\|insert\|column RET} and look at the result. On my system, this
16233 command once too takes quite some time, and then produced a list of 79
16234 functions and variables. Now it does not take much time at all and
16235 produces a list of 211 functions and variables. Scanning down the
16236 list, the only function that looks as if it might do the job is
16237 @code{insert-rectangle}.
16238
16239 @need 1200
16240 Indeed, this is the function we want; its documentation says:
16241
16242 @smallexample
16243 @group
16244 insert-rectangle:
16245 Insert text of RECTANGLE with upper left corner at point.
16246 RECTANGLE's first line is inserted at point,
16247 its second line is inserted at a point vertically under point, etc.
16248 RECTANGLE should be a list of strings.
16249 After this command, the mark is at the upper left corner
16250 and point is at the lower right corner.
16251 @end group
16252 @end smallexample
16253
16254 We can run a quick test, to make sure it does what we expect of it.
16255
16256 Here is the result of placing the cursor after the
16257 @code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
16258 (@code{eval-last-sexp}). The function inserts the strings
16259 @samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
16260 point. Also the function returns @code{nil}.
16261
16262 @smallexample
16263 @group
16264 (insert-rectangle '("first" "second" "third"))first
16265 second
16266 thirdnil
16267 @end group
16268 @end smallexample
16269
16270 @noindent
16271 Of course, we won't be inserting the text of the
16272 @code{insert-rectangle} expression itself into the buffer in which we
16273 are making the graph, but will call the function from our program. We
16274 shall, however, have to make sure that point is in the buffer at the
16275 place where the @code{insert-rectangle} function will insert its
16276 column of strings.
16277
16278 If you are reading this in Info, you can see how this works by
16279 switching to another buffer, such as the @file{*scratch*} buffer,
16280 placing point somewhere in the buffer, typing @kbd{M-:}, typing the
16281 @code{insert-rectangle} expression into the minibuffer at the prompt,
16282 and then typing @key{RET}. This causes Emacs to evaluate the
16283 expression in the minibuffer, but to use as the value of point the
16284 position of point in the @file{*scratch*} buffer. (@kbd{M-:} is the
16285 keybinding for @code{eval-expression}. Also, @code{nil} does not
16286 appear in the @file{*scratch*} buffer since the expression is
16287 evaluated in the minibuffer.)
16288
16289 We find when we do this that point ends up at the end of the last
16290 inserted line---that is to say, this function moves point as a
16291 side-effect. If we were to repeat the command, with point at this
16292 position, the next insertion would be below and to the right of the
16293 previous insertion. We don't want this! If we are going to make a
16294 bar graph, the columns need to be beside each other.
16295
16296 So we discover that each cycle of the column-inserting @code{while}
16297 loop must reposition point to the place we want it, and that place
16298 will be at the top, not the bottom, of the column. Moreover, we
16299 remember that when we print a graph, we do not expect all the columns
16300 to be the same height. This means that the top of each column may be
16301 at a different height from the previous one. We cannot simply
16302 reposition point to the same line each time, but moved over to the
16303 right---or perhaps we can@dots{}
16304
16305 We are planning to make the columns of the bar graph out of asterisks.
16306 The number of asterisks in the column is the number specified by the
16307 current element of the @code{numbers-list}. We need to construct a
16308 list of asterisks of the right length for each call to
16309 @code{insert-rectangle}. If this list consists solely of the requisite
16310 number of asterisks, then we will have position point the right number
16311 of lines above the base for the graph to print correctly. This could
16312 be difficult.
16313
16314 Alternatively, if we can figure out some way to pass
16315 @code{insert-rectangle} a list of the same length each time, then we
16316 can place point on the same line each time, but move it over one
16317 column to the right for each new column. If we do this, however, some
16318 of the entries in the list passed to @code{insert-rectangle} must be
16319 blanks rather than asterisks. For example, if the maximum height of
16320 the graph is 5, but the height of the column is 3, then
16321 @code{insert-rectangle} requires an argument that looks like this:
16322
16323 @smallexample
16324 (" " " " "*" "*" "*")
16325 @end smallexample
16326
16327 This last proposal is not so difficult, so long as we can determine
16328 the column height. There are two ways for us to specify the column
16329 height: we can arbitrarily state what it will be, which would work
16330 fine for graphs of that height; or we can search through the list of
16331 numbers and use the maximum height of the list as the maximum height
16332 of the graph. If the latter operation were difficult, then the former
16333 procedure would be easiest, but there is a function built into Emacs
16334 that determines the maximum of its arguments. We can use that
16335 function. The function is called @code{max} and it returns the
16336 largest of all its arguments, which must be numbers. Thus, for
16337 example,
16338
16339 @smallexample
16340 (max 3 4 6 5 7 3)
16341 @end smallexample
16342
16343 @noindent
16344 returns 7. (A corresponding function called @code{min} returns the
16345 smallest of all its arguments.)
16346 @findex max
16347 @findex min
16348
16349 However, we cannot simply call @code{max} on the @code{numbers-list};
16350 the @code{max} function expects numbers as its argument, not a list of
16351 numbers. Thus, the following expression,
16352
16353 @smallexample
16354 (max '(3 4 6 5 7 3))
16355 @end smallexample
16356
16357 @need 800
16358 @noindent
16359 produces the following error message;
16360
16361 @smallexample
16362 Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
16363 @end smallexample
16364
16365 @findex apply
16366 We need a function that passes a list of arguments to a function.
16367 This function is @code{apply}. This function `applies' its first
16368 argument (a function) to its remaining arguments, the last of which
16369 may be a list.
16370
16371 @need 1250
16372 For example,
16373
16374 @smallexample
16375 (apply 'max 3 4 7 3 '(4 8 5))
16376 @end smallexample
16377
16378 @noindent
16379 returns 8.
16380
16381 (Incidentally, I don't know how you would learn of this function
16382 without a book such as this. It is possible to discover other
16383 functions, like @code{search-forward} or @code{insert-rectangle}, by
16384 guessing at a part of their names and then using @code{apropos}. Even
16385 though its base in metaphor is clear---`apply' its first argument to
16386 the rest---I doubt a novice would come up with that particular word
16387 when using @code{apropos} or other aid. Of course, I could be wrong;
16388 after all, the function was first named by someone who had to invent
16389 it.)
16390
16391 The second and subsequent arguments to @code{apply} are optional, so
16392 we can use @code{apply} to call a function and pass the elements of a
16393 list to it, like this, which also returns 8:
16394
16395 @smallexample
16396 (apply 'max '(4 8 5))
16397 @end smallexample
16398
16399 This latter way is how we will use @code{apply}. The
16400 @code{recursive-lengths-list-many-files} function returns a numbers'
16401 list to which we can apply @code{max} (we could also apply @code{max} to
16402 the sorted numbers' list; it does not matter whether the list is
16403 sorted or not.)
16404
16405 @need 800
16406 Hence, the operation for finding the maximum height of the graph is this:
16407
16408 @smallexample
16409 (setq max-graph-height (apply 'max numbers-list))
16410 @end smallexample
16411
16412 Now we can return to the question of how to create a list of strings
16413 for a column of the graph. Told the maximum height of the graph
16414 and the number of asterisks that should appear in the column, the
16415 function should return a list of strings for the
16416 @code{insert-rectangle} command to insert.
16417
16418 Each column is made up of asterisks or blanks. Since the function is
16419 passed the value of the height of the column and the number of
16420 asterisks in the column, the number of blanks can be found by
16421 subtracting the number of asterisks from the height of the column.
16422 Given the number of blanks and the number of asterisks, two
16423 @code{while} loops can be used to construct the list:
16424
16425 @smallexample
16426 @group
16427 ;;; @r{First version.}
16428 (defun column-of-graph (max-graph-height actual-height)
16429 "Return list of strings that is one column of a graph."
16430 (let ((insert-list nil)
16431 (number-of-top-blanks
16432 (- max-graph-height actual-height)))
16433 @end group
16434
16435 @group
16436 ;; @r{Fill in asterisks.}
16437 (while (> actual-height 0)
16438 (setq insert-list (cons "*" insert-list))
16439 (setq actual-height (1- actual-height)))
16440 @end group
16441
16442 @group
16443 ;; @r{Fill in blanks.}
16444 (while (> number-of-top-blanks 0)
16445 (setq insert-list (cons " " insert-list))
16446 (setq number-of-top-blanks
16447 (1- number-of-top-blanks)))
16448 @end group
16449
16450 @group
16451 ;; @r{Return whole list.}
16452 insert-list))
16453 @end group
16454 @end smallexample
16455
16456 If you install this function and then evaluate the following
16457 expression you will see that it returns the list as desired:
16458
16459 @smallexample
16460 (column-of-graph 5 3)
16461 @end smallexample
16462
16463 @need 800
16464 @noindent
16465 returns
16466
16467 @smallexample
16468 (" " " " "*" "*" "*")
16469 @end smallexample
16470
16471 As written, @code{column-of-graph} contains a major flaw: the symbols
16472 used for the blank and for the marked entries in the column are
16473 `hard-coded' as a space and asterisk. This is fine for a prototype,
16474 but you, or another user, may wish to use other symbols. For example,
16475 in testing the graph function, you many want to use a period in place
16476 of the space, to make sure the point is being repositioned properly
16477 each time the @code{insert-rectangle} function is called; or you might
16478 want to substitute a @samp{+} sign or other symbol for the asterisk.
16479 You might even want to make a graph-column that is more than one
16480 display column wide. The program should be more flexible. The way to
16481 do that is to replace the blank and the asterisk with two variables
16482 that we can call @code{graph-blank} and @code{graph-symbol} and define
16483 those variables separately.
16484
16485 Also, the documentation is not well written. These considerations
16486 lead us to the second version of the function:
16487
16488 @smallexample
16489 @group
16490 (defvar graph-symbol "*"
16491 "String used as symbol in graph, usually an asterisk.")
16492 @end group
16493
16494 @group
16495 (defvar graph-blank " "
16496 "String used as blank in graph, usually a blank space.
16497 graph-blank must be the same number of columns wide
16498 as graph-symbol.")
16499 @end group
16500 @end smallexample
16501
16502 @noindent
16503 (For an explanation of @code{defvar}, see
16504 @ref{defvar, , Initializing a Variable with @code{defvar}}.)
16505
16506 @smallexample
16507 @group
16508 ;;; @r{Second version.}
16509 (defun column-of-graph (max-graph-height actual-height)
16510 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
16511
16512 @end group
16513 @group
16514 The graph-symbols are contiguous entries at the end
16515 of the list.
16516 The list will be inserted as one column of a graph.
16517 The strings are either graph-blank or graph-symbol."
16518 @end group
16519
16520 @group
16521 (let ((insert-list nil)
16522 (number-of-top-blanks
16523 (- max-graph-height actual-height)))
16524 @end group
16525
16526 @group
16527 ;; @r{Fill in @code{graph-symbols}.}
16528 (while (> actual-height 0)
16529 (setq insert-list (cons graph-symbol insert-list))
16530 (setq actual-height (1- actual-height)))
16531 @end group
16532
16533 @group
16534 ;; @r{Fill in @code{graph-blanks}.}
16535 (while (> number-of-top-blanks 0)
16536 (setq insert-list (cons graph-blank insert-list))
16537 (setq number-of-top-blanks
16538 (1- number-of-top-blanks)))
16539
16540 ;; @r{Return whole list.}
16541 insert-list))
16542 @end group
16543 @end smallexample
16544
16545 If we wished, we could rewrite @code{column-of-graph} a third time to
16546 provide optionally for a line graph as well as for a bar graph. This
16547 would not be hard to do. One way to think of a line graph is that it
16548 is no more than a bar graph in which the part of each bar that is
16549 below the top is blank. To construct a column for a line graph, the
16550 function first constructs a list of blanks that is one shorter than
16551 the value, then it uses @code{cons} to attach a graph symbol to the
16552 list; then it uses @code{cons} again to attach the `top blanks' to
16553 the list.
16554
16555 It is easy to see how to write such a function, but since we don't
16556 need it, we will not do it. But the job could be done, and if it were
16557 done, it would be done with @code{column-of-graph}. Even more
16558 important, it is worth noting that few changes would have to be made
16559 anywhere else. The enhancement, if we ever wish to make it, is
16560 simple.
16561
16562 Now, finally, we come to our first actual graph printing function.
16563 This prints the body of a graph, not the labels for the vertical and
16564 horizontal axes, so we can call this @code{graph-body-print}.
16565
16566 @node graph-body-print
16567 @section The @code{graph-body-print} Function
16568 @findex graph-body-print
16569
16570 After our preparation in the preceding section, the
16571 @code{graph-body-print} function is straightforward. The function
16572 will print column after column of asterisks and blanks, using the
16573 elements of a numbers' list to specify the number of asterisks in each
16574 column. This is a repetitive act, which means we can use a
16575 decrementing @code{while} loop or recursive function for the job. In
16576 this section, we will write the definition using a @code{while} loop.
16577
16578 The @code{column-of-graph} function requires the height of the graph
16579 as an argument, so we should determine and record that as a local variable.
16580
16581 This leads us to the following template for the @code{while} loop
16582 version of this function:
16583
16584 @smallexample
16585 @group
16586 (defun graph-body-print (numbers-list)
16587 "@var{documentation}@dots{}"
16588 (let ((height @dots{}
16589 @dots{}))
16590 @end group
16591
16592 @group
16593 (while numbers-list
16594 @var{insert-columns-and-reposition-point}
16595 (setq numbers-list (cdr numbers-list)))))
16596 @end group
16597 @end smallexample
16598
16599 @noindent
16600 We need to fill in the slots of the template.
16601
16602 Clearly, we can use the @code{(apply 'max numbers-list)} expression to
16603 determine the height of the graph.
16604
16605 The @code{while} loop will cycle through the @code{numbers-list} one
16606 element at a time. As it is shortened by the @code{(setq numbers-list
16607 (cdr numbers-list))} expression, the @sc{car} of each instance of the
16608 list is the value of the argument for @code{column-of-graph}.
16609
16610 At each cycle of the @code{while} loop, the @code{insert-rectangle}
16611 function inserts the list returned by @code{column-of-graph}. Since
16612 the @code{insert-rectangle} function moves point to the lower right of
16613 the inserted rectangle, we need to save the location of point at the
16614 time the rectangle is inserted, move back to that position after the
16615 rectangle is inserted, and then move horizontally to the next place
16616 from which @code{insert-rectangle} is called.
16617
16618 If the inserted columns are one character wide, as they will be if
16619 single blanks and asterisks are used, the repositioning command is
16620 simply @code{(forward-char 1)}; however, the width of a column may be
16621 greater than one. This means that the repositioning command should be
16622 written @code{(forward-char symbol-width)}. The @code{symbol-width}
16623 itself is the length of a @code{graph-blank} and can be found using
16624 the expression @code{(length graph-blank)}. The best place to bind
16625 the @code{symbol-width} variable to the value of the width of graph
16626 column is in the varlist of the @code{let} expression.
16627
16628 @need 1250
16629 These considerations lead to the following function definition:
16630
16631 @smallexample
16632 @group
16633 (defun graph-body-print (numbers-list)
16634 "Print a bar graph of the NUMBERS-LIST.
16635 The numbers-list consists of the Y-axis values."
16636
16637 (let ((height (apply 'max numbers-list))
16638 (symbol-width (length graph-blank))
16639 from-position)
16640 @end group
16641
16642 @group
16643 (while numbers-list
16644 (setq from-position (point))
16645 (insert-rectangle
16646 (column-of-graph height (car numbers-list)))
16647 (goto-char from-position)
16648 (forward-char symbol-width)
16649 @end group
16650 @group
16651 ;; @r{Draw graph column by column.}
16652 (sit-for 0)
16653 (setq numbers-list (cdr numbers-list)))
16654 @end group
16655 @group
16656 ;; @r{Place point for X axis labels.}
16657 (forward-line height)
16658 (insert "\n")
16659 ))
16660 @end group
16661 @end smallexample
16662
16663 @noindent
16664 The one unexpected expression in this function is the
16665 @w{@code{(sit-for 0)}} expression in the @code{while} loop. This
16666 expression makes the graph printing operation more interesting to
16667 watch than it would be otherwise. The expression causes Emacs to
16668 `sit' or do nothing for a zero length of time and then redraw the
16669 screen. Placed here, it causes Emacs to redraw the screen column by
16670 column. Without it, Emacs would not redraw the screen until the
16671 function exits.
16672
16673 We can test @code{graph-body-print} with a short list of numbers.
16674
16675 @enumerate
16676 @item
16677 Install @code{graph-symbol}, @code{graph-blank},
16678 @code{column-of-graph}, which are in
16679 @iftex
16680 @ref{Readying a Graph, , Readying a Graph},
16681 @end iftex
16682 @ifinfo
16683 @ref{Columns of a graph},
16684 @end ifinfo
16685 and @code{graph-body-print}.
16686
16687 @need 800
16688 @item
16689 Copy the following expression:
16690
16691 @smallexample
16692 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
16693 @end smallexample
16694
16695 @item
16696 Switch to the @file{*scratch*} buffer and place the cursor where you
16697 want the graph to start.
16698
16699 @item
16700 Type @kbd{M-:} (@code{eval-expression}).
16701
16702 @item
16703 Yank the @code{graph-body-print} expression into the minibuffer
16704 with @kbd{C-y} (@code{yank)}.
16705
16706 @item
16707 Press @key{RET} to evaluate the @code{graph-body-print} expression.
16708 @end enumerate
16709
16710 @need 800
16711 Emacs will print a graph like this:
16712
16713 @smallexample
16714 @group
16715 *
16716 * **
16717 * ****
16718 *** ****
16719 ********* *
16720 ************
16721 *************
16722 @end group
16723 @end smallexample
16724
16725 @node recursive-graph-body-print
16726 @section The @code{recursive-graph-body-print} Function
16727 @findex recursive-graph-body-print
16728
16729 The @code{graph-body-print} function may also be written recursively.
16730 The recursive solution is divided into two parts: an outside `wrapper'
16731 that uses a @code{let} expression to determine the values of several
16732 variables that need only be found once, such as the maximum height of
16733 the graph, and an inside function that is called recursively to print
16734 the graph.
16735
16736 @need 1250
16737 The `wrapper' is uncomplicated:
16738
16739 @smallexample
16740 @group
16741 (defun recursive-graph-body-print (numbers-list)
16742 "Print a bar graph of the NUMBERS-LIST.
16743 The numbers-list consists of the Y-axis values."
16744 (let ((height (apply 'max numbers-list))
16745 (symbol-width (length graph-blank))
16746 from-position)
16747 (recursive-graph-body-print-internal
16748 numbers-list
16749 height
16750 symbol-width)))
16751 @end group
16752 @end smallexample
16753
16754 The recursive function is a little more difficult. It has four parts:
16755 the `do-again-test', the printing code, the recursive call, and the
16756 `next-step-expression'. The `do-again-test' is a @code{when}
16757 expression that determines whether the @code{numbers-list} contains
16758 any remaining elements; if it does, the function prints one column of
16759 the graph using the printing code and calls itself again. The
16760 function calls itself again according to the value produced by the
16761 `next-step-expression' which causes the call to act on a shorter
16762 version of the @code{numbers-list}.
16763
16764 @smallexample
16765 @group
16766 (defun recursive-graph-body-print-internal
16767 (numbers-list height symbol-width)
16768 "Print a bar graph.
16769 Used within recursive-graph-body-print function."
16770 @end group
16771
16772 @group
16773 (when numbers-list
16774 (setq from-position (point))
16775 (insert-rectangle
16776 (column-of-graph height (car numbers-list)))
16777 @end group
16778 @group
16779 (goto-char from-position)
16780 (forward-char symbol-width)
16781 (sit-for 0) ; @r{Draw graph column by column.}
16782 (recursive-graph-body-print-internal
16783 (cdr numbers-list) height symbol-width)))
16784 @end group
16785 @end smallexample
16786
16787 @need 1250
16788 After installation, this expression can be tested; here is a sample:
16789
16790 @smallexample
16791 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
16792 @end smallexample
16793
16794 @need 800
16795 Here is what @code{recursive-graph-body-print} produces:
16796
16797 @smallexample
16798 @group
16799 *
16800 ** *
16801 **** *
16802 **** ***
16803 * *********
16804 ************
16805 *************
16806 @end group
16807 @end smallexample
16808
16809 Either of these two functions, @code{graph-body-print} or
16810 @code{recursive-graph-body-print}, create the body of a graph.
16811
16812 @node Printed Axes
16813 @section Need for Printed Axes
16814
16815 A graph needs printed axes, so you can orient yourself. For a do-once
16816 project, it may be reasonable to draw the axes by hand using Emacs's
16817 Picture mode; but a graph drawing function may be used more than once.
16818
16819 For this reason, I have written enhancements to the basic
16820 @code{print-graph-body} function that automatically print labels for
16821 the horizontal and vertical axes. Since the label printing functions
16822 do not contain much new material, I have placed their description in
16823 an appendix. @xref{Full Graph, , A Graph with Labeled Axes}.
16824
16825 @node Line Graph Exercise
16826 @section Exercise
16827
16828 Write a line graph version of the graph printing functions.
16829
16830 @node Emacs Initialization
16831 @chapter Your @file{.emacs} File
16832 @cindex @file{.emacs} file
16833 @cindex Customizing your @file{.emacs} file
16834 @cindex Initialization file
16835
16836 ``You don't have to like Emacs to like it''---this seemingly
16837 paradoxical statement is the secret of GNU Emacs. The plain, `out of
16838 the box' Emacs is a generic tool. Most people who use it, customize
16839 it to suit themselves.
16840
16841 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
16842 expressions in Emacs Lisp you can change or extend Emacs.
16843
16844 @menu
16845 * Default Configuration::
16846 * Site-wide Init:: You can write site-wide init files.
16847 * defcustom:: Emacs will write code for you.
16848 * Beginning a .emacs File:: How to write a @code{.emacs file}.
16849 * Text and Auto-fill:: Automatically wrap lines.
16850 * Mail Aliases:: Use abbreviations for email addresses.
16851 * Indent Tabs Mode:: Don't use tabs with @TeX{}
16852 * Keybindings:: Create some personal keybindings.
16853 * Keymaps:: More about key binding.
16854 * Loading Files:: Load (i.e., evaluate) files automatically.
16855 * Autoload:: Make functions available.
16856 * Simple Extension:: Define a function; bind it to a key.
16857 * X11 Colors:: Colors in X.
16858 * Miscellaneous::
16859 * Mode Line:: How to customize your mode line.
16860 @end menu
16861
16862 @ifnottex
16863 @node Default Configuration
16864 @unnumberedsec Emacs's Default Configuration
16865 @end ifnottex
16866
16867 There are those who appreciate Emacs's default configuration. After
16868 all, Emacs starts you in C mode when you edit a C file, starts you in
16869 Fortran mode when you edit a Fortran file, and starts you in
16870 Fundamental mode when you edit an unadorned file. This all makes
16871 sense, if you do not know who is going to use Emacs. Who knows what a
16872 person hopes to do with an unadorned file? Fundamental mode is the
16873 right default for such a file, just as C mode is the right default for
16874 editing C code. (Enough programming languages have syntaxes
16875 that enable them to share or nearly share features, so C mode is
16876 now provided by CC mode, the `C Collection'.)
16877
16878 But when you do know who is going to use Emacs---you,
16879 yourself---then it makes sense to customize Emacs.
16880
16881 For example, I seldom want Fundamental mode when I edit an
16882 otherwise undistinguished file; I want Text mode. This is why I
16883 customize Emacs: so it suits me.
16884
16885 You can customize and extend Emacs by writing or adapting a
16886 @file{~/.emacs} file. This is your personal initialization file; its
16887 contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16888 may also add @file{.el} to @file{~/.emacs} and call it a
16889 @file{~/.emacs.el} file. In the past, you were forbidden to type the
16890 extra keystrokes that the name @file{~/.emacs.el} requires, but now
16891 you may. The new format is consistent with the Emacs Lisp file
16892 naming conventions; the old format saves typing.}
16893
16894 A @file{~/.emacs} file contains Emacs Lisp code. You can write this
16895 code yourself; or you can use Emacs's @code{customize} feature to write
16896 the code for you. You can combine your own expressions and
16897 auto-written Customize expressions in your @file{.emacs} file.
16898
16899 (I myself prefer to write my own expressions, except for those,
16900 particularly fonts, that I find easier to manipulate using the
16901 @code{customize} command. I combine the two methods.)
16902
16903 Most of this chapter is about writing expressions yourself. It
16904 describes a simple @file{.emacs} file; for more information, see
16905 @ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16906 @ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16907 Manual}.
16908
16909 @node Site-wide Init
16910 @section Site-wide Initialization Files
16911
16912 @cindex @file{default.el} init file
16913 @cindex @file{site-init.el} init file
16914 @cindex @file{site-load.el} init file
16915 In addition to your personal initialization file, Emacs automatically
16916 loads various site-wide initialization files, if they exist. These
16917 have the same form as your @file{.emacs} file, but are loaded by
16918 everyone.
16919
16920 Two site-wide initialization files, @file{site-load.el} and
16921 @file{site-init.el}, are loaded into Emacs and then `dumped' if a
16922 `dumped' version of Emacs is created, as is most common. (Dumped
16923 copies of Emacs load more quickly. However, once a file is loaded and
16924 dumped, a change to it does not lead to a change in Emacs unless you
16925 load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16926 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16927 @file{INSTALL} file.)
16928
16929 Three other site-wide initialization files are loaded automatically
16930 each time you start Emacs, if they exist. These are
16931 @file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16932 file, and @file{default.el}, and the terminal type file, which are both
16933 loaded @emph{after} your @file{.emacs} file.
16934
16935 Settings and definitions in your @file{.emacs} file will overwrite
16936 conflicting settings and definitions in a @file{site-start.el} file,
16937 if it exists; but the settings and definitions in a @file{default.el}
16938 or terminal type file will overwrite those in your @file{.emacs} file.
16939 (You can prevent interference from a terminal type file by setting
16940 @code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16941 Simple Extension}.)
16942
16943 @c Rewritten to avoid overfull hbox.
16944 The @file{INSTALL} file that comes in the distribution contains
16945 descriptions of the @file{site-init.el} and @file{site-load.el} files.
16946
16947 The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16948 control loading. These files are in the @file{lisp} directory of the
16949 Emacs distribution and are worth perusing.
16950
16951 The @file{loaddefs.el} file contains a good many suggestions as to
16952 what to put into your own @file{.emacs} file, or into a site-wide
16953 initialization file.
16954
16955 @node defcustom
16956 @section Specifying Variables using @code{defcustom}
16957 @findex defcustom
16958
16959 You can specify variables using @code{defcustom} so that you and
16960 others can then use Emacs's @code{customize} feature to set their
16961 values. (You cannot use @code{customize} to write function
16962 definitions; but you can write @code{defuns} in your @file{.emacs}
16963 file. Indeed, you can write any Lisp expression in your @file{.emacs}
16964 file.)
16965
16966 The @code{customize} feature depends on the @code{defcustom} special
16967 form. Although you can use @code{defvar} or @code{setq} for variables
16968 that users set, the @code{defcustom} special form is designed for the
16969 job.
16970
16971 You can use your knowledge of @code{defvar} for writing the
16972 first three arguments for @code{defcustom}. The first argument to
16973 @code{defcustom} is the name of the variable. The second argument is
16974 the variable's initial value, if any; and this value is set only if
16975 the value has not already been set. The third argument is the
16976 documentation.
16977
16978 The fourth and subsequent arguments to @code{defcustom} specify types
16979 and options; these are not featured in @code{defvar}. (These
16980 arguments are optional.)
16981
16982 Each of these arguments consists of a keyword followed by a value.
16983 Each keyword starts with the colon character @samp{:}.
16984
16985 @need 1250
16986 For example, the customizable user option variable
16987 @code{text-mode-hook} looks like this:
16988
16989 @smallexample
16990 @group
16991 (defcustom text-mode-hook nil
16992 "Normal hook run when entering Text mode and many related modes."
16993 :type 'hook
16994 :options '(turn-on-auto-fill flyspell-mode)
16995 :group 'wp)
16996 @end group
16997 @end smallexample
16998
16999 @noindent
17000 The name of the variable is @code{text-mode-hook}; it has no default
17001 value; and its documentation string tells you what it does.
17002
17003 The @code{:type} keyword tells Emacs the kind of data to which
17004 @code{text-mode-hook} should be set and how to display the value in a
17005 Customization buffer.
17006
17007 The @code{:options} keyword specifies a suggested list of values for
17008 the variable. Usually, @code{:options} applies to a hook.
17009 The list is only a suggestion; it is not exclusive; a person who sets
17010 the variable may set it to other values; the list shown following the
17011 @code{:options} keyword is intended to offer convenient choices to a
17012 user.
17013
17014 Finally, the @code{:group} keyword tells the Emacs Customization
17015 command in which group the variable is located. This tells where to
17016 find it.
17017
17018 The @code{defcustom} function recognizes more than a dozen keywords.
17019 For more information, see @ref{Customization, , Writing Customization
17020 Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
17021
17022 Consider @code{text-mode-hook} as an example.
17023
17024 There are two ways to customize this variable. You can use the
17025 customization command or write the appropriate expressions yourself.
17026
17027 @need 800
17028 Using the customization command, you can type:
17029
17030 @smallexample
17031 M-x customize
17032 @end smallexample
17033
17034 @noindent
17035 and find that the group for editing files of data is called `data'.
17036 Enter that group. Text Mode Hook is the first member. You can click
17037 on its various options, such as @code{turn-on-auto-fill}, to set the
17038 values. After you click on the button to
17039
17040 @smallexample
17041 Save for Future Sessions
17042 @end smallexample
17043
17044 @noindent
17045 Emacs will write an expression into your @file{.emacs} file.
17046 It will look like this:
17047
17048 @smallexample
17049 @group
17050 (custom-set-variables
17051 ;; custom-set-variables was added by Custom.
17052 ;; If you edit it by hand, you could mess it up, so be careful.
17053 ;; Your init file should contain only one such instance.
17054 ;; If there is more than one, they won't work right.
17055 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
17056 @end group
17057 @end smallexample
17058
17059 @noindent
17060 (The @code{text-mode-hook-identify} function tells
17061 @code{toggle-text-mode-auto-fill} which buffers are in Text mode.
17062 It comes on automatically.)
17063
17064 The @code{custom-set-variables} function works somewhat differently
17065 than a @code{setq}. While I have never learned the differences, I
17066 modify the @code{custom-set-variables} expressions in my @file{.emacs}
17067 file by hand: I make the changes in what appears to me to be a
17068 reasonable manner and have not had any problems. Others prefer to use
17069 the Customization command and let Emacs do the work for them.
17070
17071 Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
17072 This function sets the various font faces. Over time, I have set a
17073 considerable number of faces. Some of the time, I re-set them using
17074 @code{customize}; other times, I simply edit the
17075 @code{custom-set-faces} expression in my @file{.emacs} file itself.
17076
17077 The second way to customize your @code{text-mode-hook} is to set it
17078 yourself in your @file{.emacs} file using code that has nothing to do
17079 with the @code{custom-set-@dots{}} functions.
17080
17081 @need 800
17082 When you do this, and later use @code{customize}, you will see a
17083 message that says
17084
17085 @smallexample
17086 CHANGED outside Customize; operating on it here may be unreliable.
17087 @end smallexample
17088
17089 @need 800
17090 This message is only a warning. If you click on the button to
17091
17092 @smallexample
17093 Save for Future Sessions
17094 @end smallexample
17095
17096 @noindent
17097 Emacs will write a @code{custom-set-@dots{}} expression near the end
17098 of your @file{.emacs} file that will be evaluated after your
17099 hand-written expression. It will, therefore, overrule your
17100 hand-written expression. No harm will be done. When you do this,
17101 however, be careful to remember which expression is active; if you
17102 forget, you may confuse yourself.
17103
17104 So long as you remember where the values are set, you will have no
17105 trouble. In any event, the values are always set in your
17106 initialization file, which is usually called @file{.emacs}.
17107
17108 I myself use @code{customize} for hardly anything. Mostly, I write
17109 expressions myself.
17110
17111 @findex defsubst
17112 @findex defconst
17113 Incidentally, to be more complete concerning defines: @code{defsubst}
17114 defines an inline function. The syntax is just like that of
17115 @code{defun}. @code{defconst} defines a symbol as a constant. The
17116 intent is that neither programs nor users should ever change a value
17117 set by @code{defconst}. (You can change it; the value set is a
17118 variable; but please do not.)
17119
17120 @node Beginning a .emacs File
17121 @section Beginning a @file{.emacs} File
17122 @cindex @file{.emacs} file, beginning of
17123
17124 When you start Emacs, it loads your @file{.emacs} file unless you tell
17125 it not to by specifying @samp{-q} on the command line. (The
17126 @code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
17127
17128 A @file{.emacs} file contains Lisp expressions. Often, these are no
17129 more than expressions to set values; sometimes they are function
17130 definitions.
17131
17132 @xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
17133 Manual}, for a short description of initialization files.
17134
17135 This chapter goes over some of the same ground, but is a walk among
17136 extracts from a complete, long-used @file{.emacs} file---my own.
17137
17138 The first part of the file consists of comments: reminders to myself.
17139 By now, of course, I remember these things, but when I started, I did
17140 not.
17141
17142 @need 1200
17143 @smallexample
17144 @group
17145 ;;;; Bob's .emacs file
17146 ; Robert J. Chassell
17147 ; 26 September 1985
17148 @end group
17149 @end smallexample
17150
17151 @noindent
17152 Look at that date! I started this file a long time ago. I have been
17153 adding to it ever since.
17154
17155 @smallexample
17156 @group
17157 ; Each section in this file is introduced by a
17158 ; line beginning with four semicolons; and each
17159 ; entry is introduced by a line beginning with
17160 ; three semicolons.
17161 @end group
17162 @end smallexample
17163
17164 @noindent
17165 This describes the usual conventions for comments in Emacs Lisp.
17166 Everything on a line that follows a semicolon is a comment. Two,
17167 three, and four semicolons are used as subsection and section markers.
17168 (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference Manual}, for
17169 more about comments.)
17170
17171 @smallexample
17172 @group
17173 ;;;; The Help Key
17174 ; Control-h is the help key;
17175 ; after typing control-h, type a letter to
17176 ; indicate the subject about which you want help.
17177 ; For an explanation of the help facility,
17178 ; type control-h two times in a row.
17179 @end group
17180 @end smallexample
17181
17182 @noindent
17183 Just remember: type @kbd{C-h} two times for help.
17184
17185 @smallexample
17186 @group
17187 ; To find out about any mode, type control-h m
17188 ; while in that mode. For example, to find out
17189 ; about mail mode, enter mail mode and then type
17190 ; control-h m.
17191 @end group
17192 @end smallexample
17193
17194 @noindent
17195 `Mode help', as I call this, is very helpful. Usually, it tells you
17196 all you need to know.
17197
17198 Of course, you don't need to include comments like these in your
17199 @file{.emacs} file. I included them in mine because I kept forgetting
17200 about Mode help or the conventions for comments---but I was able to
17201 remember to look here to remind myself.
17202
17203 @node Text and Auto-fill
17204 @section Text and Auto Fill Mode
17205
17206 Now we come to the part that `turns on' Text mode and
17207 Auto Fill mode.
17208
17209 @smallexample
17210 @group
17211 ;;; Text mode and Auto Fill mode
17212 ;; The next two lines put Emacs into Text mode
17213 ;; and Auto Fill mode, and are for writers who
17214 ;; want to start writing prose rather than code.
17215 (setq-default major-mode 'text-mode)
17216 (add-hook 'text-mode-hook 'turn-on-auto-fill)
17217 @end group
17218 @end smallexample
17219
17220 Here is the first part of this @file{.emacs} file that does something
17221 besides remind a forgetful human!
17222
17223 The first of the two lines in parentheses tells Emacs to turn on Text
17224 mode when you find a file, @emph{unless} that file should go into some
17225 other mode, such as C mode.
17226
17227 @cindex Per-buffer, local variables list
17228 @cindex Local variables list, per-buffer,
17229 @cindex Automatic mode selection
17230 @cindex Mode selection, automatic
17231 When Emacs reads a file, it looks at the extension to the file name,
17232 if any. (The extension is the part that comes after a @samp{.}.) If
17233 the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
17234 on C mode. Also, Emacs looks at first nonblank line of the file; if
17235 the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
17236 possesses a list of extensions and specifications that it uses
17237 automatically. In addition, Emacs looks near the last page for a
17238 per-buffer, ``local variables list'', if any.
17239
17240 @ifinfo
17241 @xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
17242 Emacs Manual}.
17243
17244 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17245 Manual}.
17246 @end ifinfo
17247 @iftex
17248 See sections ``How Major Modes are Chosen'' and ``Local Variables in
17249 Files'' in @cite{The GNU Emacs Manual}.
17250 @end iftex
17251
17252 Now, back to the @file{.emacs} file.
17253
17254 @need 800
17255 Here is the line again; how does it work?
17256
17257 @cindex Text Mode turned on
17258 @smallexample
17259 (setq major-mode 'text-mode)
17260 @end smallexample
17261
17262 @noindent
17263 This line is a short, but complete Emacs Lisp expression.
17264
17265 We are already familiar with @code{setq}. It sets the following variable,
17266 @code{major-mode}, to the subsequent value, which is @code{text-mode}.
17267 The single quote mark before @code{text-mode} tells Emacs to deal directly
17268 with the @code{text-mode} symbol, not with whatever it might stand for.
17269 @xref{set & setq, , Setting the Value of a Variable},
17270 for a reminder of how @code{setq} works.
17271 The main point is that there is no difference between the procedure you
17272 use to set a value in your @file{.emacs} file and the procedure you use
17273 anywhere else in Emacs.
17274
17275 @need 800
17276 Here is the next line:
17277
17278 @cindex Auto Fill mode turned on
17279 @findex add-hook
17280 @smallexample
17281 (add-hook 'text-mode-hook 'turn-on-auto-fill)
17282 @end smallexample
17283
17284 @noindent
17285 In this line, the @code{add-hook} command adds
17286 @code{turn-on-auto-fill} to the variable.
17287
17288 @code{turn-on-auto-fill} is the name of a program, that, you guessed
17289 it!, turns on Auto Fill mode.
17290
17291 Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
17292 onto Text mode. So every time Emacs turns on Text mode, Emacs also
17293 turns on Auto Fill mode.
17294
17295 In brief, the first line causes Emacs to enter Text mode when you edit a
17296 file, unless the file name extension, a first non-blank line, or local
17297 variables to tell Emacs otherwise.
17298
17299 Text mode among other actions, sets the syntax table to work
17300 conveniently for writers. In Text mode, Emacs considers an apostrophe
17301 as part of a word like a letter; but Emacs does not consider a period
17302 or a space as part of a word. Thus, @kbd{M-f} moves you over
17303 @samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
17304 the @samp{t} of @samp{it's}.
17305
17306 The second line causes Emacs to turn on Auto Fill mode when it turns
17307 on Text mode. In Auto Fill mode, Emacs automatically breaks a line
17308 that is too wide and brings the excessively wide part of the line down
17309 to the next line. Emacs breaks lines between words, not within them.
17310
17311 When Auto Fill mode is turned off, lines continue to the right as you
17312 type them. Depending on how you set the value of
17313 @code{truncate-lines}, the words you type either disappear off the
17314 right side of the screen, or else are shown, in a rather ugly and
17315 unreadable manner, as a continuation line on the screen.
17316
17317 @need 1250
17318 In addition, in this part of my @file{.emacs} file, I tell the Emacs
17319 fill commands to insert two spaces after a colon:
17320
17321 @smallexample
17322 (setq colon-double-space t)
17323 @end smallexample
17324
17325 @node Mail Aliases
17326 @section Mail Aliases
17327
17328 Here is a @code{setq} that `turns on' mail aliases, along with more
17329 reminders.
17330
17331 @smallexample
17332 @group
17333 ;;; Mail mode
17334 ; To enter mail mode, type `C-x m'
17335 ; To enter RMAIL (for reading mail),
17336 ; type `M-x rmail'
17337 (setq mail-aliases t)
17338 @end group
17339 @end smallexample
17340
17341 @cindex Mail aliases
17342 @noindent
17343 This @code{setq} command sets the value of the variable
17344 @code{mail-aliases} to @code{t}. Since @code{t} means true, the line
17345 says, in effect, ``Yes, use mail aliases.''
17346
17347 Mail aliases are convenient short names for long email addresses or
17348 for lists of email addresses. The file where you keep your `aliases'
17349 is @file{~/.mailrc}. You write an alias like this:
17350
17351 @smallexample
17352 alias geo george@@foobar.wiz.edu
17353 @end smallexample
17354
17355 @noindent
17356 When you write a message to George, address it to @samp{geo}; the
17357 mailer will automatically expand @samp{geo} to the full address.
17358
17359 @node Indent Tabs Mode
17360 @section Indent Tabs Mode
17361 @cindex Tabs, preventing
17362 @findex indent-tabs-mode
17363
17364 By default, Emacs inserts tabs in place of multiple spaces when it
17365 formats a region. (For example, you might indent many lines of text
17366 all at once with the @code{indent-region} command.) Tabs look fine on
17367 a terminal or with ordinary printing, but they produce badly indented
17368 output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
17369
17370 @need 1250
17371 The following turns off Indent Tabs mode:
17372
17373 @smallexample
17374 @group
17375 ;;; Prevent Extraneous Tabs
17376 (setq-default indent-tabs-mode nil)
17377 @end group
17378 @end smallexample
17379
17380 Note that this line uses @code{setq-default} rather than the
17381 @code{setq} command that we have seen before. The @code{setq-default}
17382 command sets values only in buffers that do not have their own local
17383 values for the variable.
17384
17385 @ifinfo
17386 @xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
17387
17388 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17389 Manual}.
17390 @end ifinfo
17391 @iftex
17392 See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
17393 Files'' in @cite{The GNU Emacs Manual}.
17394 @end iftex
17395
17396 @need 1700
17397 @node Keybindings
17398 @section Some Keybindings
17399
17400 Now for some personal keybindings:
17401
17402 @smallexample
17403 @group
17404 ;;; Compare windows
17405 (global-set-key "\C-cw" 'compare-windows)
17406 @end group
17407 @end smallexample
17408
17409 @findex compare-windows
17410 @code{compare-windows} is a nifty command that compares the text in
17411 your current window with text in the next window. It makes the
17412 comparison by starting at point in each window, moving over text in
17413 each window as far as they match. I use this command all the time.
17414
17415 This also shows how to set a key globally, for all modes.
17416
17417 @cindex Setting a key globally
17418 @cindex Global set key
17419 @cindex Key setting globally
17420 @findex global-set-key
17421 The command is @code{global-set-key}. It is followed by the
17422 keybinding. In a @file{.emacs} file, the keybinding is written as
17423 shown: @code{\C-c} stands for `control-c', which means `press the
17424 control key and the @key{c} key at the same time'. The @code{w} means
17425 `press the @key{w} key'. The keybinding is surrounded by double
17426 quotation marks. In documentation, you would write this as
17427 @w{@kbd{C-c w}}. (If you were binding a @key{META} key, such as
17428 @kbd{M-c}, rather than a @key{CTRL} key, you would write
17429 @w{@code{\M-c}} in your @file{.emacs} file. @xref{Init Rebinding, ,
17430 Rebinding Keys in Your Init File, emacs, The GNU Emacs Manual}, for
17431 details.)
17432
17433 The command invoked by the keys is @code{compare-windows}. Note that
17434 @code{compare-windows} is preceded by a single quote; otherwise, Emacs
17435 would first try to evaluate the symbol to determine its value.
17436
17437 These three things, the double quotation marks, the backslash before
17438 the @samp{C}, and the single quote mark are necessary parts of
17439 keybinding that I tend to forget. Fortunately, I have come to
17440 remember that I should look at my existing @file{.emacs} file, and
17441 adapt what is there.
17442
17443 As for the keybinding itself: @kbd{C-c w}. This combines the prefix
17444 key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
17445 set of keys, @kbd{C-c} followed by a single character, is strictly
17446 reserved for individuals' own use. (I call these `own' keys, since
17447 these are for my own use.) You should always be able to create such a
17448 keybinding for your own use without stomping on someone else's
17449 keybinding. If you ever write an extension to Emacs, please avoid
17450 taking any of these keys for public use. Create a key like @kbd{C-c
17451 C-w} instead. Otherwise, we will run out of `own' keys.
17452
17453 @need 1250
17454 Here is another keybinding, with a comment:
17455
17456 @smallexample
17457 @group
17458 ;;; Keybinding for `occur'
17459 ; I use occur a lot, so let's bind it to a key:
17460 (global-set-key "\C-co" 'occur)
17461 @end group
17462 @end smallexample
17463
17464 @findex occur
17465 The @code{occur} command shows all the lines in the current buffer
17466 that contain a match for a regular expression. Matching lines are
17467 shown in a buffer called @file{*Occur*}. That buffer serves as a menu
17468 to jump to occurrences.
17469
17470 @findex global-unset-key
17471 @cindex Unbinding key
17472 @cindex Key unbinding
17473 @need 1250
17474 Here is how to unbind a key, so it does not
17475 work:
17476
17477 @smallexample
17478 @group
17479 ;;; Unbind `C-x f'
17480 (global-unset-key "\C-xf")
17481 @end group
17482 @end smallexample
17483
17484 There is a reason for this unbinding: I found I inadvertently typed
17485 @w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
17486 file, as I intended, I accidentally set the width for filled text,
17487 almost always to a width I did not want. Since I hardly ever reset my
17488 default width, I simply unbound the key.
17489
17490 @findex list-buffers, @r{rebound}
17491 @findex buffer-menu, @r{bound to key}
17492 @need 1250
17493 The following rebinds an existing key:
17494
17495 @smallexample
17496 @group
17497 ;;; Rebind `C-x C-b' for `buffer-menu'
17498 (global-set-key "\C-x\C-b" 'buffer-menu)
17499 @end group
17500 @end smallexample
17501
17502 By default, @kbd{C-x C-b} runs the
17503 @code{list-buffers} command. This command lists
17504 your buffers in @emph{another} window. Since I
17505 almost always want to do something in that
17506 window, I prefer the @code{buffer-menu}
17507 command, which not only lists the buffers,
17508 but moves point into that window.
17509
17510 @node Keymaps
17511 @section Keymaps
17512 @cindex Keymaps
17513 @cindex Rebinding keys
17514
17515 Emacs uses @dfn{keymaps} to record which keys call which commands.
17516 When you use @code{global-set-key} to set the keybinding for a single
17517 command in all parts of Emacs, you are specifying the keybinding in
17518 @code{current-global-map}.
17519
17520 Specific modes, such as C mode or Text mode, have their own keymaps;
17521 the mode-specific keymaps override the global map that is shared by
17522 all buffers.
17523
17524 The @code{global-set-key} function binds, or rebinds, the global
17525 keymap. For example, the following binds the key @kbd{C-x C-b} to the
17526 function @code{buffer-menu}:
17527
17528 @smallexample
17529 (global-set-key "\C-x\C-b" 'buffer-menu)
17530 @end smallexample
17531
17532 Mode-specific keymaps are bound using the @code{define-key} function,
17533 which takes a specific keymap as an argument, as well as the key and
17534 the command. For example, my @file{.emacs} file contains the
17535 following expression to bind the @code{texinfo-insert-@@group} command
17536 to @kbd{C-c C-c g}:
17537
17538 @smallexample
17539 @group
17540 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
17541 @end group
17542 @end smallexample
17543
17544 @noindent
17545 The @code{texinfo-insert-@@group} function itself is a little extension
17546 to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
17547 use this command all the time and prefer to type the three strokes
17548 @kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
17549 (@samp{@@group} and its matching @samp{@@end group} are commands that
17550 keep all enclosed text together on one page; many multi-line examples
17551 in this book are surrounded by @samp{@@group @dots{} @@end group}.)
17552
17553 @need 1250
17554 Here is the @code{texinfo-insert-@@group} function definition:
17555
17556 @smallexample
17557 @group
17558 (defun texinfo-insert-@@group ()
17559 "Insert the string @@group in a Texinfo buffer."
17560 (interactive)
17561 (beginning-of-line)
17562 (insert "@@group\n"))
17563 @end group
17564 @end smallexample
17565
17566 (Of course, I could have used Abbrev mode to save typing, rather than
17567 write a function to insert a word; but I prefer key strokes consistent
17568 with other Texinfo mode key bindings.)
17569
17570 You will see numerous @code{define-key} expressions in
17571 @file{loaddefs.el} as well as in the various mode libraries, such as
17572 @file{cc-mode.el} and @file{lisp-mode.el}.
17573
17574 @xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
17575 Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
17576 Reference Manual}, for more information about keymaps.
17577
17578 @node Loading Files
17579 @section Loading Files
17580 @cindex Loading files
17581 @c findex load
17582
17583 Many people in the GNU Emacs community have written extensions to
17584 Emacs. As time goes by, these extensions are often included in new
17585 releases. For example, the Calendar and Diary packages are now part
17586 of the standard GNU Emacs, as is Calc.
17587
17588 You can use a @code{load} command to evaluate a complete file and
17589 thereby install all the functions and variables in the file into Emacs.
17590 For example:
17591
17592 @c (auto-compression-mode t)
17593
17594 @smallexample
17595 (load "~/emacs/slowsplit")
17596 @end smallexample
17597
17598 This evaluates, i.e., loads, the @file{slowsplit.el} file or if it
17599 exists, the faster, byte compiled @file{slowsplit.elc} file from the
17600 @file{emacs} sub-directory of your home directory. The file contains
17601 the function @code{split-window-quietly}, which John Robinson wrote in
17602 1989.
17603
17604 The @code{split-window-quietly} function splits a window with the
17605 minimum of redisplay. I installed it in 1989 because it worked well
17606 with the slow 1200 baud terminals I was then using. Nowadays, I only
17607 occasionally come across such a slow connection, but I continue to use
17608 the function because I like the way it leaves the bottom half of a
17609 buffer in the lower of the new windows and the top half in the upper
17610 window.
17611
17612 @need 1250
17613 To replace the key binding for the default
17614 @code{split-window-vertically}, you must also unset that key and bind
17615 the keys to @code{split-window-quietly}, like this:
17616
17617 @smallexample
17618 @group
17619 (global-unset-key "\C-x2")
17620 (global-set-key "\C-x2" 'split-window-quietly)
17621 @end group
17622 @end smallexample
17623
17624 @vindex load-path
17625 If you load many extensions, as I do, then instead of specifying the
17626 exact location of the extension file, as shown above, you can specify
17627 that directory as part of Emacs's @code{load-path}. Then, when Emacs
17628 loads a file, it will search that directory as well as its default
17629 list of directories. (The default list is specified in @file{paths.h}
17630 when Emacs is built.)
17631
17632 @need 1250
17633 The following command adds your @file{~/emacs} directory to the
17634 existing load path:
17635
17636 @smallexample
17637 @group
17638 ;;; Emacs Load Path
17639 (setq load-path (cons "~/emacs" load-path))
17640 @end group
17641 @end smallexample
17642
17643 Incidentally, @code{load-library} is an interactive interface to the
17644 @code{load} function. The complete function looks like this:
17645
17646 @findex load-library
17647 @smallexample
17648 @group
17649 (defun load-library (library)
17650 "Load the library named LIBRARY.
17651 This is an interface to the function `load'."
17652 (interactive
17653 (list (completing-read "Load library: "
17654 (apply-partially 'locate-file-completion-table
17655 load-path
17656 (get-load-suffixes)))))
17657 (load library))
17658 @end group
17659 @end smallexample
17660
17661 The name of the function, @code{load-library}, comes from the use of
17662 `library' as a conventional synonym for `file'. The source for the
17663 @code{load-library} command is in the @file{files.el} library.
17664
17665 Another interactive command that does a slightly different job is
17666 @code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
17667 Emacs, emacs, The GNU Emacs Manual}, for information on the
17668 distinction between @code{load-library} and this command.
17669
17670 @node Autoload
17671 @section Autoloading
17672 @findex autoload
17673
17674 Instead of installing a function by loading the file that contains it,
17675 or by evaluating the function definition, you can make the function
17676 available but not actually install it until it is first called. This
17677 is called @dfn{autoloading}.
17678
17679 When you execute an autoloaded function, Emacs automatically evaluates
17680 the file that contains the definition, and then calls the function.
17681
17682 Emacs starts quicker with autoloaded functions, since their libraries
17683 are not loaded right away; but you need to wait a moment when you
17684 first use such a function, while its containing file is evaluated.
17685
17686 Rarely used functions are frequently autoloaded. The
17687 @file{loaddefs.el} library contains hundreds of autoloaded functions,
17688 from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
17689 come to use a `rare' function frequently. When you do, you should
17690 load that function's file with a @code{load} expression in your
17691 @file{.emacs} file.
17692
17693 In my @file{.emacs} file, I load 14 libraries that contain functions
17694 that would otherwise be autoloaded. (Actually, it would have been
17695 better to include these files in my `dumped' Emacs, but I forgot.
17696 @xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17697 Reference Manual}, and the @file{INSTALL} file for more about
17698 dumping.)
17699
17700 You may also want to include autoloaded expressions in your @file{.emacs}
17701 file. @code{autoload} is a built-in function that takes up to five
17702 arguments, the final three of which are optional. The first argument
17703 is the name of the function to be autoloaded; the second is the name
17704 of the file to be loaded. The third argument is documentation for the
17705 function, and the fourth tells whether the function can be called
17706 interactively. The fifth argument tells what type of
17707 object---@code{autoload} can handle a keymap or macro as well as a
17708 function (the default is a function).
17709
17710 @need 800
17711 Here is a typical example:
17712
17713 @smallexample
17714 @group
17715 (autoload 'html-helper-mode
17716 "html-helper-mode" "Edit HTML documents" t)
17717 @end group
17718 @end smallexample
17719
17720 @noindent
17721 (@code{html-helper-mode} is an older alternative to @code{html-mode},
17722 which is a standard part of the distribution.)
17723
17724 @noindent
17725 This expression autoloads the @code{html-helper-mode} function. It
17726 takes it from the @file{html-helper-mode.el} file (or from the byte
17727 compiled version @file{html-helper-mode.elc}, if that exists.) The
17728 file must be located in a directory specified by @code{load-path}.
17729 The documentation says that this is a mode to help you edit documents
17730 written in the HyperText Markup Language. You can call this mode
17731 interactively by typing @kbd{M-x html-helper-mode}. (You need to
17732 duplicate the function's regular documentation in the autoload
17733 expression because the regular function is not yet loaded, so its
17734 documentation is not available.)
17735
17736 @xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
17737 Manual}, for more information.
17738
17739 @node Simple Extension
17740 @section A Simple Extension: @code{line-to-top-of-window}
17741 @findex line-to-top-of-window
17742 @cindex Simple extension in @file{.emacs} file
17743
17744 Here is a simple extension to Emacs that moves the line point is on to
17745 the top of the window. I use this all the time, to make text easier
17746 to read.
17747
17748 You can put the following code into a separate file and then load it
17749 from your @file{.emacs} file, or you can include it within your
17750 @file{.emacs} file.
17751
17752 @need 1250
17753 Here is the definition:
17754
17755 @smallexample
17756 @group
17757 ;;; Line to top of window;
17758 ;;; replace three keystroke sequence C-u 0 C-l
17759 (defun line-to-top-of-window ()
17760 "Move the line point is on to top of window."
17761 (interactive)
17762 (recenter 0))
17763 @end group
17764 @end smallexample
17765
17766 @need 1250
17767 Now for the keybinding.
17768
17769 Nowadays, function keys as well as mouse button events and
17770 non-@sc{ascii} characters are written within square brackets, without
17771 quotation marks. (In Emacs version 18 and before, you had to write
17772 different function key bindings for each different make of terminal.)
17773
17774 I bind @code{line-to-top-of-window} to my @key{F6} function key like
17775 this:
17776
17777 @smallexample
17778 (global-set-key [f6] 'line-to-top-of-window)
17779 @end smallexample
17780
17781 For more information, see @ref{Init Rebinding, , Rebinding Keys in
17782 Your Init File, emacs, The GNU Emacs Manual}.
17783
17784 @cindex Conditional 'twixt two versions of Emacs
17785 @cindex Version of Emacs, choosing
17786 @cindex Emacs version, choosing
17787 If you run two versions of GNU Emacs, such as versions 22 and 23, and
17788 use one @file{.emacs} file, you can select which code to evaluate with
17789 the following conditional:
17790
17791 @smallexample
17792 @group
17793 (cond
17794 ((= 22 emacs-major-version)
17795 ;; evaluate version 22 code
17796 ( @dots{} ))
17797 ((= 23 emacs-major-version)
17798 ;; evaluate version 23 code
17799 ( @dots{} )))
17800 @end group
17801 @end smallexample
17802
17803 For example, recent versions blink
17804 their cursors by default. I hate such blinking, as well as other
17805 features, so I placed the following in my @file{.emacs}
17806 file@footnote{When I start instances of Emacs that do not load my
17807 @file{.emacs} file or any site file, I also turn off blinking:
17808
17809 @smallexample
17810 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
17811
17812 @exdent Or nowadays, using an even more sophisticated set of options,
17813
17814 emacs -Q - D
17815 @end smallexample
17816 }:
17817
17818 @smallexample
17819 @group
17820 (when (>= emacs-major-version 21)
17821 (blink-cursor-mode 0)
17822 ;; Insert newline when you press `C-n' (next-line)
17823 ;; at the end of the buffer
17824 (setq next-line-add-newlines t)
17825 @end group
17826 @group
17827 ;; Turn on image viewing
17828 (auto-image-file-mode t)
17829 @end group
17830 @group
17831 ;; Turn on menu bar (this bar has text)
17832 ;; (Use numeric argument to turn on)
17833 (menu-bar-mode 1)
17834 @end group
17835 @group
17836 ;; Turn off tool bar (this bar has icons)
17837 ;; (Use numeric argument to turn on)
17838 (tool-bar-mode nil)
17839 @end group
17840 @group
17841 ;; Turn off tooltip mode for tool bar
17842 ;; (This mode causes icon explanations to pop up)
17843 ;; (Use numeric argument to turn on)
17844 (tooltip-mode nil)
17845 ;; If tooltips turned on, make tips appear promptly
17846 (setq tooltip-delay 0.1) ; default is 0.7 second
17847 )
17848 @end group
17849 @end smallexample
17850
17851 @node X11 Colors
17852 @section X11 Colors
17853
17854 You can specify colors when you use Emacs with the MIT X Windowing
17855 system.
17856
17857 I dislike the default colors and specify my own.
17858
17859 @need 1250
17860 Here are the expressions in my @file{.emacs}
17861 file that set values:
17862
17863 @smallexample
17864 @group
17865 ;; Set cursor color
17866 (set-cursor-color "white")
17867
17868 ;; Set mouse color
17869 (set-mouse-color "white")
17870
17871 ;; Set foreground and background
17872 (set-foreground-color "white")
17873 (set-background-color "darkblue")
17874 @end group
17875
17876 @group
17877 ;;; Set highlighting colors for isearch and drag
17878 (set-face-foreground 'highlight "white")
17879 (set-face-background 'highlight "blue")
17880 @end group
17881
17882 @group
17883 (set-face-foreground 'region "cyan")
17884 (set-face-background 'region "blue")
17885 @end group
17886
17887 @group
17888 (set-face-foreground 'secondary-selection "skyblue")
17889 (set-face-background 'secondary-selection "darkblue")
17890 @end group
17891
17892 @group
17893 ;; Set calendar highlighting colors
17894 (setq calendar-load-hook
17895 (lambda ()
17896 (set-face-foreground 'diary-face "skyblue")
17897 (set-face-background 'holiday-face "slate blue")
17898 (set-face-foreground 'holiday-face "white")))
17899 @end group
17900 @end smallexample
17901
17902 The various shades of blue soothe my eye and prevent me from seeing
17903 the screen flicker.
17904
17905 Alternatively, I could have set my specifications in various X
17906 initialization files. For example, I could set the foreground,
17907 background, cursor, and pointer (i.e., mouse) colors in my
17908 @file{~/.Xresources} file like this:
17909
17910 @smallexample
17911 @group
17912 Emacs*foreground: white
17913 Emacs*background: darkblue
17914 Emacs*cursorColor: white
17915 Emacs*pointerColor: white
17916 @end group
17917 @end smallexample
17918
17919 In any event, since it is not part of Emacs, I set the root color of
17920 my X window in my @file{~/.xinitrc} file, like this@footnote{I also
17921 run more modern window managers, such as Enlightenment, Gnome, or KDE;
17922 in those cases, I often specify an image rather than a plain color.}:
17923
17924 @smallexample
17925 xsetroot -solid Navy -fg white &
17926 @end smallexample
17927
17928 @need 1700
17929 @node Miscellaneous
17930 @section Miscellaneous Settings for a @file{.emacs} File
17931
17932 @need 1250
17933 Here are a few miscellaneous settings:
17934 @sp 1
17935
17936 @itemize @minus
17937 @item
17938 Set the shape and color of the mouse cursor:
17939
17940 @smallexample
17941 @group
17942 ; Cursor shapes are defined in
17943 ; `/usr/include/X11/cursorfont.h';
17944 ; for example, the `target' cursor is number 128;
17945 ; the `top_left_arrow' cursor is number 132.
17946 @end group
17947
17948 @group
17949 (let ((mpointer (x-get-resource "*mpointer"
17950 "*emacs*mpointer")))
17951 ;; If you have not set your mouse pointer
17952 ;; then set it, otherwise leave as is:
17953 (if (eq mpointer nil)
17954 (setq mpointer "132")) ; top_left_arrow
17955 @end group
17956 @group
17957 (setq x-pointer-shape (string-to-int mpointer))
17958 (set-mouse-color "white"))
17959 @end group
17960 @end smallexample
17961
17962 @item
17963 Or you can set the values of a variety of features in an alist, like
17964 this:
17965
17966 @smallexample
17967 @group
17968 (setq-default
17969 default-frame-alist
17970 '((cursor-color . "white")
17971 (mouse-color . "white")
17972 (foreground-color . "white")
17973 (background-color . "DodgerBlue4")
17974 ;; (cursor-type . bar)
17975 (cursor-type . box)
17976 @end group
17977 @group
17978 (tool-bar-lines . 0)
17979 (menu-bar-lines . 1)
17980 (width . 80)
17981 (height . 58)
17982 (font .
17983 "-Misc-Fixed-Medium-R-Normal--20-200-75-75-C-100-ISO8859-1")
17984 ))
17985 @end group
17986 @end smallexample
17987
17988 @item
17989 Convert @kbd{@key{CTRL}-h} into @key{DEL} and @key{DEL}
17990 into @kbd{@key{CTRL}-h}.@*
17991 (Some older keyboards needed this, although I have not seen the
17992 problem recently.)
17993
17994 @smallexample
17995 @group
17996 ;; Translate `C-h' to <DEL>.
17997 ; (keyboard-translate ?\C-h ?\C-?)
17998
17999 ;; Translate <DEL> to `C-h'.
18000 (keyboard-translate ?\C-? ?\C-h)
18001 @end group
18002 @end smallexample
18003
18004 @item Turn off a blinking cursor!
18005
18006 @smallexample
18007 @group
18008 (if (fboundp 'blink-cursor-mode)
18009 (blink-cursor-mode -1))
18010 @end group
18011 @end smallexample
18012
18013 @noindent
18014 or start GNU Emacs with the command @code{emacs -nbc}.
18015
18016 @need 1250
18017 @item When using `grep'@*
18018 @samp{-i}@w{ } Ignore case distinctions@*
18019 @samp{-n}@w{ } Prefix each line of output with line number@*
18020 @samp{-H}@w{ } Print the filename for each match.@*
18021 @samp{-e}@w{ } Protect patterns beginning with a hyphen character, @samp{-}
18022
18023 @smallexample
18024 (setq grep-command "grep -i -nH -e ")
18025 @end smallexample
18026
18027 @ignore
18028 @c Evidently, no longer needed in GNU Emacs 22
18029
18030 item Automatically uncompress compressed files when visiting them
18031
18032 smallexample
18033 (load "uncompress")
18034 end smallexample
18035
18036 @end ignore
18037
18038 @item Find an existing buffer, even if it has a different name@*
18039 This avoids problems with symbolic links.
18040
18041 @smallexample
18042 (setq find-file-existing-other-name t)
18043 @end smallexample
18044
18045 @item Set your language environment and default input method
18046
18047 @smallexample
18048 @group
18049 (set-language-environment "latin-1")
18050 ;; Remember you can enable or disable multilingual text input
18051 ;; with the @code{toggle-input-method'} (@kbd{C-\}) command
18052 (setq default-input-method "latin-1-prefix")
18053 @end group
18054 @end smallexample
18055
18056 If you want to write with Chinese `GB' characters, set this instead:
18057
18058 @smallexample
18059 @group
18060 (set-language-environment "Chinese-GB")
18061 (setq default-input-method "chinese-tonepy")
18062 @end group
18063 @end smallexample
18064 @end itemize
18065
18066 @subsubheading Fixing Unpleasant Key Bindings
18067 @cindex Key bindings, fixing
18068 @cindex Bindings, key, fixing unpleasant
18069
18070 Some systems bind keys unpleasantly. Sometimes, for example, the
18071 @key{CTRL} key appears in an awkward spot rather than at the far left
18072 of the home row.
18073
18074 Usually, when people fix these sorts of keybindings, they do not
18075 change their @file{~/.emacs} file. Instead, they bind the proper keys
18076 on their consoles with the @code{loadkeys} or @code{install-keymap}
18077 commands in their boot script and then include @code{xmodmap} commands
18078 in their @file{.xinitrc} or @file{.Xsession} file for X Windows.
18079
18080 @need 1250
18081 @noindent
18082 For a boot script:
18083
18084 @smallexample
18085 @group
18086 loadkeys /usr/share/keymaps/i386/qwerty/emacs2.kmap.gz
18087 @exdent or
18088 install-keymap emacs2
18089 @end group
18090 @end smallexample
18091
18092 @need 1250
18093 @noindent
18094 For a @file{.xinitrc} or @file{.Xsession} file when the @key{Caps
18095 Lock} key is at the far left of the home row:
18096
18097 @smallexample
18098 @group
18099 # Bind the key labeled `Caps Lock' to `Control'
18100 # (Such a broken user interface suggests that keyboard manufacturers
18101 # think that computers are typewriters from 1885.)
18102
18103 xmodmap -e "clear Lock"
18104 xmodmap -e "add Control = Caps_Lock"
18105 @end group
18106 @end smallexample
18107
18108 @need 1250
18109 @noindent
18110 In a @file{.xinitrc} or @file{.Xsession} file, to convert an @key{ALT}
18111 key to a @key{META} key:
18112
18113 @smallexample
18114 @group
18115 # Some ill designed keyboards have a key labeled ALT and no Meta
18116 xmodmap -e "keysym Alt_L = Meta_L Alt_L"
18117 @end group
18118 @end smallexample
18119
18120 @need 1700
18121 @node Mode Line
18122 @section A Modified Mode Line
18123 @vindex mode-line-format
18124 @cindex Mode line format
18125
18126 Finally, a feature I really like: a modified mode line.
18127
18128 When I work over a network, I forget which machine I am using. Also,
18129 I tend to I lose track of where I am, and which line point is on.
18130
18131 So I reset my mode line to look like this:
18132
18133 @smallexample
18134 -:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
18135 @end smallexample
18136
18137 I am visiting a file called @file{foo.texi}, on my machine
18138 @file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
18139 Texinfo mode, and am at the top of the buffer.
18140
18141 @need 1200
18142 My @file{.emacs} file has a section that looks like this:
18143
18144 @smallexample
18145 @group
18146 ;; Set a Mode Line that tells me which machine, which directory,
18147 ;; and which line I am on, plus the other customary information.
18148 (setq-default mode-line-format
18149 (quote
18150 (#("-" 0 1
18151 (help-echo
18152 "mouse-1: select window, mouse-2: delete others ..."))
18153 mode-line-mule-info
18154 mode-line-modified
18155 mode-line-frame-identification
18156 " "
18157 @end group
18158 @group
18159 mode-line-buffer-identification
18160 " "
18161 (:eval (substring
18162 (system-name) 0 (string-match "\\..+" (system-name))))
18163 ":"
18164 default-directory
18165 #(" " 0 1
18166 (help-echo
18167 "mouse-1: select window, mouse-2: delete others ..."))
18168 (line-number-mode " Line %l ")
18169 global-mode-string
18170 @end group
18171 @group
18172 #(" %[(" 0 6
18173 (help-echo
18174 "mouse-1: select window, mouse-2: delete others ..."))
18175 (:eval (mode-line-mode-name))
18176 mode-line-process
18177 minor-mode-alist
18178 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
18179 ")%] "
18180 (-3 . "%P")
18181 ;; "-%-"
18182 )))
18183 @end group
18184 @end smallexample
18185
18186 @noindent
18187 Here, I redefine the default mode line. Most of the parts are from
18188 the original; but I make a few changes. I set the @emph{default} mode
18189 line format so as to permit various modes, such as Info, to override
18190 it.
18191
18192 Many elements in the list are self-explanatory:
18193 @code{mode-line-modified} is a variable that tells whether the buffer
18194 has been modified, @code{mode-name} tells the name of the mode, and so
18195 on. However, the format looks complicated because of two features we
18196 have not discussed.
18197
18198 @cindex Properties, in mode line example
18199 The first string in the mode line is a dash or hyphen, @samp{-}. In
18200 the old days, it would have been specified simply as @code{"-"}. But
18201 nowadays, Emacs can add properties to a string, such as highlighting
18202 or, as in this case, a help feature. If you place your mouse cursor
18203 over the hyphen, some help information appears (By default, you must
18204 wait seven-tenths of a second before the information appears. You can
18205 change that timing by changing the value of @code{tooltip-delay}.)
18206
18207 @need 1000
18208 The new string format has a special syntax:
18209
18210 @smallexample
18211 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
18212 @end smallexample
18213
18214 @noindent
18215 The @code{#(} begins a list. The first element of the list is the
18216 string itself, just one @samp{-}. The second and third
18217 elements specify the range over which the fourth element applies. A
18218 range starts @emph{after} a character, so a zero means the range
18219 starts just before the first character; a 1 means that the range ends
18220 just after the first character. The third element is the property for
18221 the range. It consists of a property list, a
18222 property name, in this case, @samp{help-echo}, followed by a value, in this
18223 case, a string. The second, third, and fourth elements of this new
18224 string format can be repeated.
18225
18226 @xref{Text Properties, , Text Properties, elisp, The GNU Emacs Lisp
18227 Reference Manual}, and see @ref{Mode Line Format, , Mode Line Format,
18228 elisp, The GNU Emacs Lisp Reference Manual}, for more information.
18229
18230 @code{mode-line-buffer-identification}
18231 displays the current buffer name. It is a list
18232 beginning @code{(#("%12b" 0 4 @dots{}}.
18233 The @code{#(} begins the list.
18234
18235 The @samp{"%12b"} displays the current buffer name, using the
18236 @code{buffer-name} function with which we are familiar; the `12'
18237 specifies the maximum number of characters that will be displayed.
18238 When a name has fewer characters, whitespace is added to fill out to
18239 this number. (Buffer names can and often should be longer than 12
18240 characters; this length works well in a typical 80 column wide
18241 window.)
18242
18243 @code{:eval} says to evaluate the following form and use the result as
18244 a string to display. In this case, the expression displays the first
18245 component of the full system name. The end of the first component is
18246 a @samp{.} (`period'), so I use the @code{string-match} function to
18247 tell me the length of the first component. The substring from the
18248 zeroth character to that length is the name of the machine.
18249
18250 @need 1250
18251 This is the expression:
18252
18253 @smallexample
18254 @group
18255 (:eval (substring
18256 (system-name) 0 (string-match "\\..+" (system-name))))
18257 @end group
18258 @end smallexample
18259
18260 @samp{%[} and @samp{%]} cause a pair of square brackets
18261 to appear for each recursive editing level. @samp{%n} says `Narrow'
18262 when narrowing is in effect. @samp{%P} tells you the percentage of
18263 the buffer that is above the bottom of the window, or `Top', `Bottom',
18264 or `All'. (A lower case @samp{p} tell you the percentage above the
18265 @emph{top} of the window.) @samp{%-} inserts enough dashes to fill
18266 out the line.
18267
18268 Remember, ``You don't have to like Emacs to like it''---your own
18269 Emacs can have different colors, different commands, and different
18270 keys than a default Emacs.
18271
18272 On the other hand, if you want to bring up a plain `out of the box'
18273 Emacs, with no customization, type:
18274
18275 @smallexample
18276 emacs -q
18277 @end smallexample
18278
18279 @noindent
18280 This will start an Emacs that does @emph{not} load your
18281 @file{~/.emacs} initialization file. A plain, default Emacs. Nothing
18282 more.
18283
18284 @node Debugging
18285 @chapter Debugging
18286 @cindex debugging
18287
18288 GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
18289 first is built into the internals of Emacs and is always with you;
18290 the second requires that you instrument a function before you can use it.
18291
18292 Both debuggers are described extensively in @ref{Debugging, ,
18293 Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
18294 In this chapter, I will walk through a short example of each.
18295
18296 @menu
18297 * debug:: How to use the built-in debugger.
18298 * debug-on-entry:: Start debugging when you call a function.
18299 * debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
18300 * edebug:: How to use Edebug, a source level debugger.
18301 * Debugging Exercises::
18302 @end menu
18303
18304 @node debug
18305 @section @code{debug}
18306 @findex debug
18307
18308 Suppose you have written a function definition that is intended to
18309 return the sum of the numbers 1 through a given number. (This is the
18310 @code{triangle} function discussed earlier. @xref{Decrementing
18311 Example, , Example with Decrementing Counter}, for a discussion.)
18312 @c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
18313
18314 However, your function definition has a bug. You have mistyped
18315 @samp{1=} for @samp{1-}. Here is the broken definition:
18316
18317 @findex triangle-bugged
18318 @smallexample
18319 @group
18320 (defun triangle-bugged (number)
18321 "Return sum of numbers 1 through NUMBER inclusive."
18322 (let ((total 0))
18323 (while (> number 0)
18324 (setq total (+ total number))
18325 (setq number (1= number))) ; @r{Error here.}
18326 total))
18327 @end group
18328 @end smallexample
18329
18330 If you are reading this in Info, you can evaluate this definition in
18331 the normal fashion. You will see @code{triangle-bugged} appear in the
18332 echo area.
18333
18334 @need 1250
18335 Now evaluate the @code{triangle-bugged} function with an
18336 argument of 4:
18337
18338 @smallexample
18339 (triangle-bugged 4)
18340 @end smallexample
18341
18342 @noindent
18343 In a recent GNU Emacs, you will create and enter a @file{*Backtrace*}
18344 buffer that says:
18345
18346 @noindent
18347 @smallexample
18348 @group
18349 ---------- Buffer: *Backtrace* ----------
18350 Debugger entered--Lisp error: (void-function 1=)
18351 (1= number)
18352 (setq number (1= number))
18353 (while (> number 0) (setq total (+ total number))
18354 (setq number (1= number)))
18355 (let ((total 0)) (while (> number 0) (setq total ...)
18356 (setq number ...)) total)
18357 triangle-bugged(4)
18358 @end group
18359 @group
18360 eval((triangle-bugged 4))
18361 eval-last-sexp-1(nil)
18362 eval-last-sexp(nil)
18363 call-interactively(eval-last-sexp)
18364 ---------- Buffer: *Backtrace* ----------
18365 @end group
18366 @end smallexample
18367
18368 @noindent
18369 (I have reformatted this example slightly; the debugger does not fold
18370 long lines. As usual, you can quit the debugger by typing @kbd{q} in
18371 the @file{*Backtrace*} buffer.)
18372
18373 In practice, for a bug as simple as this, the `Lisp error' line will
18374 tell you what you need to know to correct the definition. The
18375 function @code{1=} is `void'.
18376
18377 @ignore
18378 @need 800
18379 In GNU Emacs 20 and before, you will see:
18380
18381 @smallexample
18382 Symbol's function definition is void:@: 1=
18383 @end smallexample
18384
18385 @noindent
18386 which has the same meaning as the @file{*Backtrace*} buffer line in
18387 version 21.
18388 @end ignore
18389
18390 However, suppose you are not quite certain what is going on?
18391 You can read the complete backtrace.
18392
18393 In this case, you need to run a recent GNU Emacs, which automatically
18394 starts the debugger that puts you in the @file{*Backtrace*} buffer; or
18395 else, you need to start the debugger manually as described below.
18396
18397 Read the @file{*Backtrace*} buffer from the bottom up; it tells you
18398 what Emacs did that led to the error. Emacs made an interactive call
18399 to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
18400 of the @code{triangle-bugged} expression. Each line above tells you
18401 what the Lisp interpreter evaluated next.
18402
18403 @need 1250
18404 The third line from the top of the buffer is
18405
18406 @smallexample
18407 (setq number (1= number))
18408 @end smallexample
18409
18410 @noindent
18411 Emacs tried to evaluate this expression; in order to do so, it tried
18412 to evaluate the inner expression shown on the second line from the
18413 top:
18414
18415 @smallexample
18416 (1= number)
18417 @end smallexample
18418
18419 @need 1250
18420 @noindent
18421 This is where the error occurred; as the top line says:
18422
18423 @smallexample
18424 Debugger entered--Lisp error: (void-function 1=)
18425 @end smallexample
18426
18427 @noindent
18428 You can correct the mistake, re-evaluate the function definition, and
18429 then run your test again.
18430
18431 @node debug-on-entry
18432 @section @code{debug-on-entry}
18433 @findex debug-on-entry
18434
18435 A recent GNU Emacs starts the debugger automatically when your
18436 function has an error.
18437
18438 @ignore
18439 GNU Emacs version 20 and before did not; it simply
18440 presented you with an error message. You had to start the debugger
18441 manually.
18442 @end ignore
18443
18444 Incidentally, you can start the debugger manually for all versions of
18445 Emacs; the advantage is that the debugger runs even if you do not have
18446 a bug in your code. Sometimes your code will be free of bugs!
18447
18448 You can enter the debugger when you call the function by calling
18449 @code{debug-on-entry}.
18450
18451 @need 1250
18452 @noindent
18453 Type:
18454
18455 @smallexample
18456 M-x debug-on-entry RET triangle-bugged RET
18457 @end smallexample
18458
18459 @need 1250
18460 @noindent
18461 Now, evaluate the following:
18462
18463 @smallexample
18464 (triangle-bugged 5)
18465 @end smallexample
18466
18467 @noindent
18468 All versions of Emacs will create a @file{*Backtrace*} buffer and tell
18469 you that it is beginning to evaluate the @code{triangle-bugged}
18470 function:
18471
18472 @smallexample
18473 @group
18474 ---------- Buffer: *Backtrace* ----------
18475 Debugger entered--entering a function:
18476 * triangle-bugged(5)
18477 eval((triangle-bugged 5))
18478 @end group
18479 @group
18480 eval-last-sexp-1(nil)
18481 eval-last-sexp(nil)
18482 call-interactively(eval-last-sexp)
18483 ---------- Buffer: *Backtrace* ----------
18484 @end group
18485 @end smallexample
18486
18487 In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
18488 the first expression in @code{triangle-bugged}; the buffer will look
18489 like this:
18490
18491 @smallexample
18492 @group
18493 ---------- Buffer: *Backtrace* ----------
18494 Debugger entered--beginning evaluation of function call form:
18495 * (let ((total 0)) (while (> number 0) (setq total ...)
18496 (setq number ...)) total)
18497 * triangle-bugged(5)
18498 eval((triangle-bugged 5))
18499 @end group
18500 @group
18501 eval-last-sexp-1(nil)
18502 eval-last-sexp(nil)
18503 call-interactively(eval-last-sexp)
18504 ---------- Buffer: *Backtrace* ----------
18505 @end group
18506 @end smallexample
18507
18508 @noindent
18509 Now, type @kbd{d} again, eight times, slowly. Each time you type
18510 @kbd{d}, Emacs will evaluate another expression in the function
18511 definition.
18512
18513 @need 1750
18514 Eventually, the buffer will look like this:
18515
18516 @smallexample
18517 @group
18518 ---------- Buffer: *Backtrace* ----------
18519 Debugger entered--beginning evaluation of function call form:
18520 * (setq number (1= number))
18521 * (while (> number 0) (setq total (+ total number))
18522 (setq number (1= number)))
18523 @group
18524 @end group
18525 * (let ((total 0)) (while (> number 0) (setq total ...)
18526 (setq number ...)) total)
18527 * triangle-bugged(5)
18528 eval((triangle-bugged 5))
18529 @group
18530 @end group
18531 eval-last-sexp-1(nil)
18532 eval-last-sexp(nil)
18533 call-interactively(eval-last-sexp)
18534 ---------- Buffer: *Backtrace* ----------
18535 @end group
18536 @end smallexample
18537
18538 @need 1500
18539 @noindent
18540 Finally, after you type @kbd{d} two more times, Emacs will reach the
18541 error, and the top two lines of the @file{*Backtrace*} buffer will look
18542 like this:
18543
18544 @smallexample
18545 @group
18546 ---------- Buffer: *Backtrace* ----------
18547 Debugger entered--Lisp error: (void-function 1=)
18548 * (1= number)
18549 @dots{}
18550 ---------- Buffer: *Backtrace* ----------
18551 @end group
18552 @end smallexample
18553
18554 By typing @kbd{d}, you were able to step through the function.
18555
18556 You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
18557 quits the trace, but does not cancel @code{debug-on-entry}.
18558
18559 @findex cancel-debug-on-entry
18560 To cancel the effect of @code{debug-on-entry}, call
18561 @code{cancel-debug-on-entry} and the name of the function, like this:
18562
18563 @smallexample
18564 M-x cancel-debug-on-entry RET triangle-bugged RET
18565 @end smallexample
18566
18567 @noindent
18568 (If you are reading this in Info, cancel @code{debug-on-entry} now.)
18569
18570 @node debug-on-quit
18571 @section @code{debug-on-quit} and @code{(debug)}
18572
18573 In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
18574 there are two other ways to start @code{debug}.
18575
18576 @findex debug-on-quit
18577 You can start @code{debug} whenever you type @kbd{C-g}
18578 (@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
18579 @code{t}. This is useful for debugging infinite loops.
18580
18581 @need 1500
18582 @cindex @code{(debug)} in code
18583 Or, you can insert a line that says @code{(debug)} into your code
18584 where you want the debugger to start, like this:
18585
18586 @smallexample
18587 @group
18588 (defun triangle-bugged (number)
18589 "Return sum of numbers 1 through NUMBER inclusive."
18590 (let ((total 0))
18591 (while (> number 0)
18592 (setq total (+ total number))
18593 (debug) ; @r{Start debugger.}
18594 (setq number (1= number))) ; @r{Error here.}
18595 total))
18596 @end group
18597 @end smallexample
18598
18599 The @code{debug} function is described in detail in @ref{Debugger, ,
18600 The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
18601
18602 @node edebug
18603 @section The @code{edebug} Source Level Debugger
18604 @cindex Source level debugger
18605 @findex edebug
18606
18607 Edebug is a source level debugger. Edebug normally displays the
18608 source of the code you are debugging, with an arrow at the left that
18609 shows which line you are currently executing.
18610
18611 You can walk through the execution of a function, line by line, or run
18612 quickly until reaching a @dfn{breakpoint} where execution stops.
18613
18614 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18615 Lisp Reference Manual}.
18616
18617 @need 1250
18618 Here is a bugged function definition for @code{triangle-recursively}.
18619 @xref{Recursive triangle function, , Recursion in place of a counter},
18620 for a review of it.
18621
18622 @smallexample
18623 @group
18624 (defun triangle-recursively-bugged (number)
18625 "Return sum of numbers 1 through NUMBER inclusive.
18626 Uses recursion."
18627 (if (= number 1)
18628 1
18629 (+ number
18630 (triangle-recursively-bugged
18631 (1= number))))) ; @r{Error here.}
18632 @end group
18633 @end smallexample
18634
18635 @noindent
18636 Normally, you would install this definition by positioning your cursor
18637 after the function's closing parenthesis and typing @kbd{C-x C-e}
18638 (@code{eval-last-sexp}) or else by positioning your cursor within the
18639 definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
18640 the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
18641 Interaction mode.)
18642
18643 @need 1500
18644 However, to prepare this function definition for Edebug, you must
18645 first @dfn{instrument} the code using a different command. You can do
18646 this by positioning your cursor within or just after the definition
18647 and typing
18648
18649 @smallexample
18650 M-x edebug-defun RET
18651 @end smallexample
18652
18653 @noindent
18654 This will cause Emacs to load Edebug automatically if it is not
18655 already loaded, and properly instrument the function.
18656
18657 After instrumenting the function, place your cursor after the
18658 following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
18659
18660 @smallexample
18661 (triangle-recursively-bugged 3)
18662 @end smallexample
18663
18664 @noindent
18665 You will be jumped back to the source for
18666 @code{triangle-recursively-bugged} and the cursor positioned at the
18667 beginning of the @code{if} line of the function. Also, you will see
18668 an arrowhead at the left hand side of that line. The arrowhead marks
18669 the line where the function is executing. (In the following examples,
18670 we show the arrowhead with @samp{=>}; in a windowing system, you may
18671 see the arrowhead as a solid triangle in the window `fringe'.)
18672
18673 @smallexample
18674 =>@point{}(if (= number 1)
18675 @end smallexample
18676
18677 @noindent
18678 @iftex
18679 In the example, the location of point is displayed with a star,
18680 @samp{@point{}} (in Info, it is displayed as @samp{-!-}).
18681 @end iftex
18682 @ifnottex
18683 In the example, the location of point is displayed as @samp{@point{}}
18684 (in a printed book, it is displayed with a five pointed star).
18685 @end ifnottex
18686
18687 If you now press @key{SPC}, point will move to the next expression to
18688 be executed; the line will look like this:
18689
18690 @smallexample
18691 =>(if @point{}(= number 1)
18692 @end smallexample
18693
18694 @noindent
18695 As you continue to press @key{SPC}, point will move from expression to
18696 expression. At the same time, whenever an expression returns a value,
18697 that value will be displayed in the echo area. For example, after you
18698 move point past @code{number}, you will see the following:
18699
18700 @smallexample
18701 Result: 3 (#o3, #x3, ?\C-c)
18702 @end smallexample
18703
18704 @noindent
18705 This means the value of @code{number} is 3, which is octal three,
18706 hexadecimal three, and @sc{ascii} `control-c' (the third letter of the
18707 alphabet, in case you need to know this information).
18708
18709 You can continue moving through the code until you reach the line with
18710 the error. Before evaluation, that line looks like this:
18711
18712 @smallexample
18713 => @point{}(1= number))))) ; @r{Error here.}
18714 @end smallexample
18715
18716 @need 1250
18717 @noindent
18718 When you press @key{SPC} once again, you will produce an error message
18719 that says:
18720
18721 @smallexample
18722 Symbol's function definition is void:@: 1=
18723 @end smallexample
18724
18725 @noindent
18726 This is the bug.
18727
18728 Press @kbd{q} to quit Edebug.
18729
18730 To remove instrumentation from a function definition, simply
18731 re-evaluate it with a command that does not instrument it.
18732 For example, you could place your cursor after the definition's
18733 closing parenthesis and type @kbd{C-x C-e}.
18734
18735 Edebug does a great deal more than walk with you through a function.
18736 You can set it so it races through on its own, stopping only at an
18737 error or at specified stopping points; you can cause it to display the
18738 changing values of various expressions; you can find out how many
18739 times a function is called, and more.
18740
18741 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18742 Lisp Reference Manual}.
18743
18744 @need 1500
18745 @node Debugging Exercises
18746 @section Debugging Exercises
18747
18748 @itemize @bullet
18749 @item
18750 Install the @code{@value{COUNT-WORDS}} function and then cause it to
18751 enter the built-in debugger when you call it. Run the command on a
18752 region containing two words. You will need to press @kbd{d} a
18753 remarkable number of times. On your system, is a `hook' called after
18754 the command finishes? (For information on hooks, see @ref{Command
18755 Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
18756 Manual}.)
18757
18758 @item
18759 Copy @code{@value{COUNT-WORDS}} into the @file{*scratch*} buffer,
18760 instrument the function for Edebug, and walk through its execution.
18761 The function does not need to have a bug, although you can introduce
18762 one if you wish. If the function lacks a bug, the walk-through
18763 completes without problems.
18764
18765 @item
18766 While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
18767 (The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.,
18768 @kbd{@key{CTRL}-x} followed by an upper case @kbd{X}; use this prefix
18769 for commands made outside of the Edebug debugging buffer.)
18770
18771 @item
18772 In the Edebug debugging buffer, use the @kbd{p}
18773 (@code{edebug-bounce-point}) command to see where in the region the
18774 @code{@value{COUNT-WORDS}} is working.
18775
18776 @item
18777 Move point to some spot further down the function and then type the
18778 @kbd{h} (@code{edebug-goto-here}) command to jump to that location.
18779
18780 @item
18781 Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
18782 walk through the function on its own; use an upper case @kbd{T} for
18783 @code{edebug-Trace-fast-mode}.
18784
18785 @item
18786 Set a breakpoint, then run Edebug in Trace mode until it reaches the
18787 stopping point.
18788 @end itemize
18789
18790 @node Conclusion
18791 @chapter Conclusion
18792
18793 We have now reached the end of this Introduction. You have now
18794 learned enough about programming in Emacs Lisp to set values, to write
18795 simple @file{.emacs} files for yourself and your friends, and write
18796 simple customizations and extensions to Emacs.
18797
18798 This is a place to stop. Or, if you wish, you can now go onward, and
18799 teach yourself.
18800
18801 You have learned some of the basic nuts and bolts of programming. But
18802 only some. There are a great many more brackets and hinges that are
18803 easy to use that we have not touched.
18804
18805 A path you can follow right now lies among the sources to GNU Emacs
18806 and in
18807 @ifnotinfo
18808 @cite{The GNU Emacs Lisp Reference Manual}.
18809 @end ifnotinfo
18810 @ifinfo
18811 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
18812 Emacs Lisp Reference Manual}.
18813 @end ifinfo
18814
18815 The Emacs Lisp sources are an adventure. When you read the sources and
18816 come across a function or expression that is unfamiliar, you need to
18817 figure out or find out what it does.
18818
18819 Go to the Reference Manual. It is a thorough, complete, and fairly
18820 easy-to-read description of Emacs Lisp. It is written not only for
18821 experts, but for people who know what you know. (The @cite{Reference
18822 Manual} comes with the standard GNU Emacs distribution. Like this
18823 introduction, it comes as a Texinfo source file, so you can read it
18824 on-line and as a typeset, printed book.)
18825
18826 Go to the other on-line help that is part of GNU Emacs: the on-line
18827 documentation for all functions and variables, and @code{find-tag},
18828 the program that takes you to sources.
18829
18830 Here is an example of how I explore the sources. Because of its name,
18831 @file{simple.el} is the file I looked at first, a long time ago. As
18832 it happens some of the functions in @file{simple.el} are complicated,
18833 or at least look complicated at first sight. The @code{open-line}
18834 function, for example, looks complicated.
18835
18836 You may want to walk through this function slowly, as we did with the
18837 @code{forward-sentence} function. (@xref{forward-sentence, The
18838 @code{forward-sentence} function}.) Or you may want to skip that
18839 function and look at another, such as @code{split-line}. You don't
18840 need to read all the functions. According to
18841 @code{count-words-in-defun}, the @code{split-line} function contains
18842 102 words and symbols.
18843
18844 Even though it is short, @code{split-line} contains expressions
18845 we have not studied: @code{skip-chars-forward}, @code{indent-to},
18846 @code{current-column} and @code{insert-and-inherit}.
18847
18848 Consider the @code{skip-chars-forward} function. (It is part of the
18849 function definition for @code{back-to-indentation}, which is shown in
18850 @ref{Review, , Review}.)
18851
18852 In GNU Emacs, you can find out more about @code{skip-chars-forward} by
18853 typing @kbd{C-h f} (@code{describe-function}) and the name of the
18854 function. This gives you the function documentation.
18855
18856 You may be able to guess what is done by a well named function such as
18857 @code{indent-to}; or you can look it up, too. Incidentally, the
18858 @code{describe-function} function itself is in @file{help.el}; it is
18859 one of those long, but decipherable functions. You can look up
18860 @code{describe-function} using the @kbd{C-h f} command!
18861
18862 In this instance, since the code is Lisp, the @file{*Help*} buffer
18863 contains the name of the library containing the function's source.
18864 You can put point over the name of the library and press the RET key,
18865 which in this situation is bound to @code{help-follow}, and be taken
18866 directly to the source, in the same way as @kbd{M-.}
18867 (@code{find-tag}).
18868
18869 The definition for @code{describe-function} illustrates how to
18870 customize the @code{interactive} expression without using the standard
18871 character codes; and it shows how to create a temporary buffer.
18872
18873 (The @code{indent-to} function is written in C rather than Emacs Lisp;
18874 it is a `built-in' function. @code{help-follow} takes you to its
18875 source as does @code{find-tag}, when properly set up.)
18876
18877 You can look at a function's source using @code{find-tag}, which is
18878 bound to @kbd{M-.} Finally, you can find out what the Reference
18879 Manual has to say by visiting the manual in Info, and typing @kbd{i}
18880 (@code{Info-index}) and the name of the function, or by looking up the
18881 function in the index to a printed copy of the manual.
18882
18883 Similarly, you can find out what is meant by
18884 @code{insert-and-inherit}.
18885
18886 Other interesting source files include @file{paragraphs.el},
18887 @file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
18888 file includes short, easily understood functions as well as longer
18889 ones. The @file{loaddefs.el} file contains the many standard
18890 autoloads and many keymaps. I have never looked at it all; only at
18891 parts. @file{loadup.el} is the file that loads the standard parts of
18892 Emacs; it tells you a great deal about how Emacs is built.
18893 (@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
18894 Reference Manual}, for more about building.)
18895
18896 As I said, you have learned some nuts and bolts; however, and very
18897 importantly, we have hardly touched major aspects of programming; I
18898 have said nothing about how to sort information, except to use the
18899 predefined @code{sort} function; I have said nothing about how to store
18900 information, except to use variables and lists; I have said nothing
18901 about how to write programs that write programs. These are topics for
18902 another, and different kind of book, a different kind of learning.
18903
18904 What you have done is learn enough for much practical work with GNU
18905 Emacs. What you have done is get started. This is the end of a
18906 beginning.
18907
18908 @c ================ Appendix ================
18909
18910 @node the-the
18911 @appendix The @code{the-the} Function
18912 @findex the-the
18913 @cindex Duplicated words function
18914 @cindex Words, duplicated
18915
18916 Sometimes when you you write text, you duplicate words---as with ``you
18917 you'' near the beginning of this sentence. I find that most
18918 frequently, I duplicate ``the''; hence, I call the function for
18919 detecting duplicated words, @code{the-the}.
18920
18921 @need 1250
18922 As a first step, you could use the following regular expression to
18923 search for duplicates:
18924
18925 @smallexample
18926 \\(\\w+[ \t\n]+\\)\\1
18927 @end smallexample
18928
18929 @noindent
18930 This regexp matches one or more word-constituent characters followed
18931 by one or more spaces, tabs, or newlines. However, it does not detect
18932 duplicated words on different lines, since the ending of the first
18933 word, the end of the line, is different from the ending of the second
18934 word, a space. (For more information about regular expressions, see
18935 @ref{Regexp Search, , Regular Expression Searches}, as well as
18936 @ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
18937 Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
18938 The GNU Emacs Lisp Reference Manual}.)
18939
18940 You might try searching just for duplicated word-constituent
18941 characters but that does not work since the pattern detects doubles
18942 such as the two occurrences of `th' in `with the'.
18943
18944 Another possible regexp searches for word-constituent characters
18945 followed by non-word-constituent characters, reduplicated. Here,
18946 @w{@samp{\\w+}} matches one or more word-constituent characters and
18947 @w{@samp{\\W*}} matches zero or more non-word-constituent characters.
18948
18949 @smallexample
18950 \\(\\(\\w+\\)\\W*\\)\\1
18951 @end smallexample
18952
18953 @noindent
18954 Again, not useful.
18955
18956 Here is the pattern that I use. It is not perfect, but good enough.
18957 @w{@samp{\\b}} matches the empty string, provided it is at the beginning
18958 or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
18959 any characters that are @emph{not} an @@-sign, space, newline, or tab.
18960
18961 @smallexample
18962 \\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
18963 @end smallexample
18964
18965 One can write more complicated expressions, but I found that this
18966 expression is good enough, so I use it.
18967
18968 Here is the @code{the-the} function, as I include it in my
18969 @file{.emacs} file, along with a handy global key binding:
18970
18971 @smallexample
18972 @group
18973 (defun the-the ()
18974 "Search forward for for a duplicated word."
18975 (interactive)
18976 (message "Searching for for duplicated words ...")
18977 (push-mark)
18978 @end group
18979 @group
18980 ;; This regexp is not perfect
18981 ;; but is fairly good over all:
18982 (if (re-search-forward
18983 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
18984 (message "Found duplicated word.")
18985 (message "End of buffer")))
18986 @end group
18987
18988 @group
18989 ;; Bind `the-the' to C-c \
18990 (global-set-key "\C-c\\" 'the-the)
18991 @end group
18992 @end smallexample
18993
18994 @sp 1
18995 Here is test text:
18996
18997 @smallexample
18998 @group
18999 one two two three four five
19000 five six seven
19001 @end group
19002 @end smallexample
19003
19004 You can substitute the other regular expressions shown above in the
19005 function definition and try each of them on this list.
19006
19007 @node Kill Ring
19008 @appendix Handling the Kill Ring
19009 @cindex Kill ring handling
19010 @cindex Handling the kill ring
19011 @cindex Ring, making a list like a
19012
19013 The kill ring is a list that is transformed into a ring by the
19014 workings of the @code{current-kill} function. The @code{yank} and
19015 @code{yank-pop} commands use the @code{current-kill} function.
19016
19017 This appendix describes the @code{current-kill} function as well as
19018 both the @code{yank} and the @code{yank-pop} commands, but first,
19019 consider the workings of the kill ring.
19020
19021 @menu
19022 * What the Kill Ring Does::
19023 * current-kill::
19024 * yank:: Paste a copy of a clipped element.
19025 * yank-pop:: Insert element pointed to.
19026 * ring file::
19027 @end menu
19028
19029 @ifnottex
19030 @node What the Kill Ring Does
19031 @unnumberedsec What the Kill Ring Does
19032 @end ifnottex
19033
19034 @need 1250
19035 The kill ring has a default maximum length of sixty items; this number
19036 is too large for an explanation. Instead, set it to four. Please
19037 evaluate the following:
19038
19039 @smallexample
19040 @group
19041 (setq old-kill-ring-max kill-ring-max)
19042 (setq kill-ring-max 4)
19043 @end group
19044 @end smallexample
19045
19046 @noindent
19047 Then, please copy each line of the following indented example into the
19048 kill ring. You may kill each line with @kbd{C-k} or mark it and copy
19049 it with @kbd{M-w}.
19050
19051 @noindent
19052 (In a read-only buffer, such as the @file{*info*} buffer, the kill
19053 command, @kbd{C-k} (@code{kill-line}), will not remove the text,
19054 merely copy it to the kill ring. However, your machine may beep at
19055 you. Alternatively, for silence, you may copy the region of each line
19056 with the @kbd{M-w} (@code{kill-ring-save}) command. You must mark
19057 each line for this command to succeed, but it does not matter at which
19058 end you put point or mark.)
19059
19060 @need 1250
19061 @noindent
19062 Please invoke the calls in order, so that five elements attempt to
19063 fill the kill ring:
19064
19065 @smallexample
19066 @group
19067 first some text
19068 second piece of text
19069 third line
19070 fourth line of text
19071 fifth bit of text
19072 @end group
19073 @end smallexample
19074
19075 @need 1250
19076 @noindent
19077 Then find the value of @code{kill-ring} by evaluating
19078
19079 @smallexample
19080 kill-ring
19081 @end smallexample
19082
19083 @need 800
19084 @noindent
19085 It is:
19086
19087 @smallexample
19088 @group
19089 ("fifth bit of text" "fourth line of text"
19090 "third line" "second piece of text")
19091 @end group
19092 @end smallexample
19093
19094 @noindent
19095 The first element, @samp{first some text}, was dropped.
19096
19097 @need 1250
19098 To return to the old value for the length of the kill ring, evaluate:
19099
19100 @smallexample
19101 (setq kill-ring-max old-kill-ring-max)
19102 @end smallexample
19103
19104 @node current-kill
19105 @appendixsec The @code{current-kill} Function
19106 @findex current-kill
19107
19108 The @code{current-kill} function changes the element in the kill ring
19109 to which @code{kill-ring-yank-pointer} points. (Also, the
19110 @code{kill-new} function sets @code{kill-ring-yank-pointer} to point
19111 to the latest element of the kill ring. The @code{kill-new}
19112 function is used directly or indirectly by @code{kill-append},
19113 @code{copy-region-as-kill}, @code{kill-ring-save}, @code{kill-line},
19114 and @code{kill-region}.)
19115
19116 @menu
19117 * Code for current-kill::
19118 * Understanding current-kill::
19119 @end menu
19120
19121 @ifnottex
19122 @node Code for current-kill
19123 @unnumberedsubsec The code for @code{current-kill}
19124 @end ifnottex
19125
19126
19127 @need 1500
19128 The @code{current-kill} function is used by @code{yank} and by
19129 @code{yank-pop}. Here is the code for @code{current-kill}:
19130
19131 @smallexample
19132 @group
19133 (defun current-kill (n &optional do-not-move)
19134 "Rotate the yanking point by N places, and then return that kill.
19135 If N is zero, `interprogram-paste-function' is set, and calling it
19136 returns a string, then that string is added to the front of the
19137 kill ring and returned as the latest kill.
19138 @end group
19139 @group
19140 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
19141 yanking point; just return the Nth kill forward."
19142 (let ((interprogram-paste (and (= n 0)
19143 interprogram-paste-function
19144 (funcall interprogram-paste-function))))
19145 @end group
19146 @group
19147 (if interprogram-paste
19148 (progn
19149 ;; Disable the interprogram cut function when we add the new
19150 ;; text to the kill ring, so Emacs doesn't try to own the
19151 ;; selection, with identical text.
19152 (let ((interprogram-cut-function nil))
19153 (kill-new interprogram-paste))
19154 interprogram-paste)
19155 @end group
19156 @group
19157 (or kill-ring (error "Kill ring is empty"))
19158 (let ((ARGth-kill-element
19159 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19160 (length kill-ring))
19161 kill-ring)))
19162 (or do-not-move
19163 (setq kill-ring-yank-pointer ARGth-kill-element))
19164 (car ARGth-kill-element)))))
19165 @end group
19166 @end smallexample
19167
19168 Remember also that the @code{kill-new} function sets
19169 @code{kill-ring-yank-pointer} to the latest element of the kill
19170 ring, which means that all the functions that call it set the value
19171 indirectly: @code{kill-append}, @code{copy-region-as-kill},
19172 @code{kill-ring-save}, @code{kill-line}, and @code{kill-region}.
19173
19174 @need 1500
19175 Here is the line in @code{kill-new}, which is explained in
19176 @ref{kill-new function, , The @code{kill-new} function}.
19177
19178 @smallexample
19179 (setq kill-ring-yank-pointer kill-ring)
19180 @end smallexample
19181
19182 @ifnottex
19183 @node Understanding current-kill
19184 @unnumberedsubsec @code{current-kill} in Outline
19185 @end ifnottex
19186
19187 The @code{current-kill} function looks complex, but as usual, it can
19188 be understood by taking it apart piece by piece. First look at it in
19189 skeletal form:
19190
19191 @smallexample
19192 @group
19193 (defun current-kill (n &optional do-not-move)
19194 "Rotate the yanking point by N places, and then return that kill."
19195 (let @var{varlist}
19196 @var{body}@dots{})
19197 @end group
19198 @end smallexample
19199
19200 This function takes two arguments, one of which is optional. It has a
19201 documentation string. It is @emph{not} interactive.
19202
19203 @menu
19204 * Body of current-kill::
19205 * Digression concerning error:: How to mislead humans, but not computers.
19206 * Determining the Element::
19207 @end menu
19208
19209 @ifnottex
19210 @node Body of current-kill
19211 @unnumberedsubsubsec The Body of @code{current-kill}
19212 @end ifnottex
19213
19214 The body of the function definition is a @code{let} expression, which
19215 itself has a body as well as a @var{varlist}.
19216
19217 The @code{let} expression declares a variable that will be only usable
19218 within the bounds of this function. This variable is called
19219 @code{interprogram-paste} and is for copying to another program. It
19220 is not for copying within this instance of GNU Emacs. Most window
19221 systems provide a facility for interprogram pasting. Sadly, that
19222 facility usually provides only for the last element. Most windowing
19223 systems have not adopted a ring of many possibilities, even though
19224 Emacs has provided it for decades.
19225
19226 The @code{if} expression has two parts, one if there exists
19227 @code{interprogram-paste} and one if not.
19228
19229 @need 2000
19230 Let us consider the `if not' or else-part of the @code{current-kill}
19231 function. (The then-part uses the @code{kill-new} function, which
19232 we have already described. @xref{kill-new function, , The
19233 @code{kill-new} function}.)
19234
19235 @smallexample
19236 @group
19237 (or kill-ring (error "Kill ring is empty"))
19238 (let ((ARGth-kill-element
19239 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19240 (length kill-ring))
19241 kill-ring)))
19242 (or do-not-move
19243 (setq kill-ring-yank-pointer ARGth-kill-element))
19244 (car ARGth-kill-element))
19245 @end group
19246 @end smallexample
19247
19248 @noindent
19249 The code first checks whether the kill ring has content; otherwise it
19250 signals an error.
19251
19252 @need 1000
19253 Note that the @code{or} expression is very similar to testing length
19254 with an @code{if}:
19255
19256 @findex zerop
19257 @findex error
19258 @smallexample
19259 @group
19260 (if (zerop (length kill-ring)) ; @r{if-part}
19261 (error "Kill ring is empty")) ; @r{then-part}
19262 ;; No else-part
19263 @end group
19264 @end smallexample
19265
19266 @noindent
19267 If there is not anything in the kill ring, its length must be zero and
19268 an error message sent to the user: @samp{Kill ring is empty}. The
19269 @code{current-kill} function uses an @code{or} expression which is
19270 simpler. But an @code{if} expression reminds us what goes on.
19271
19272 This @code{if} expression uses the function @code{zerop} which returns
19273 true if the value it is testing is zero. When @code{zerop} tests
19274 true, the then-part of the @code{if} is evaluated. The then-part is a
19275 list starting with the function @code{error}, which is a function that
19276 is similar to the @code{message} function
19277 (@pxref{message, , The @code{message} Function}) in that
19278 it prints a one-line message in the echo area. However, in addition
19279 to printing a message, @code{error} also stops evaluation of the
19280 function within which it is embedded. This means that the rest of the
19281 function will not be evaluated if the length of the kill ring is zero.
19282
19283 Then the @code{current-kill} function selects the element to return.
19284 The selection depends on the number of places that @code{current-kill}
19285 rotates and on where @code{kill-ring-yank-pointer} points.
19286
19287 Next, either the optional @code{do-not-move} argument is true or the
19288 current value of @code{kill-ring-yank-pointer} is set to point to the
19289 list. Finally, another expression returns the first element of the
19290 list even if the @code{do-not-move} argument is true.
19291
19292 @ifnottex
19293 @node Digression concerning error
19294 @unnumberedsubsubsec Digression about the word `error'
19295 @end ifnottex
19296
19297 In my opinion, it is slightly misleading, at least to humans, to use
19298 the term `error' as the name of the @code{error} function. A better
19299 term would be `cancel'. Strictly speaking, of course, you cannot
19300 point to, much less rotate a pointer to a list that has no length, so
19301 from the point of view of the computer, the word `error' is correct.
19302 But a human expects to attempt this sort of thing, if only to find out
19303 whether the kill ring is full or empty. This is an act of
19304 exploration.
19305
19306 From the human point of view, the act of exploration and discovery is
19307 not necessarily an error, and therefore should not be labeled as one,
19308 even in the bowels of a computer. As it is, the code in Emacs implies
19309 that a human who is acting virtuously, by exploring his or her
19310 environment, is making an error. This is bad. Even though the computer
19311 takes the same steps as it does when there is an `error', a term such as
19312 `cancel' would have a clearer connotation.
19313
19314 @ifnottex
19315 @node Determining the Element
19316 @unnumberedsubsubsec Determining the Element
19317 @end ifnottex
19318
19319 Among other actions, the else-part of the @code{if} expression sets
19320 the value of @code{kill-ring-yank-pointer} to
19321 @code{ARGth-kill-element} when the kill ring has something in it and
19322 the value of @code{do-not-move} is @code{nil}.
19323
19324 @need 800
19325 The code looks like this:
19326
19327 @smallexample
19328 @group
19329 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19330 (length kill-ring))
19331 kill-ring)))
19332 @end group
19333 @end smallexample
19334
19335 This needs some examination. Unless it is not supposed to move the
19336 pointer, the @code{current-kill} function changes where
19337 @code{kill-ring-yank-pointer} points.
19338 That is what the
19339 @w{@code{(setq kill-ring-yank-pointer ARGth-kill-element))}}
19340 expression does. Also, clearly, @code{ARGth-kill-element} is being
19341 set to be equal to some @sc{cdr} of the kill ring, using the
19342 @code{nthcdr} function that is described in an earlier section.
19343 (@xref{copy-region-as-kill}.) How does it do this?
19344
19345 As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
19346 works by repeatedly taking the @sc{cdr} of a list---it takes the
19347 @sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
19348
19349 @need 800
19350 The two following expressions produce the same result:
19351
19352 @smallexample
19353 @group
19354 (setq kill-ring-yank-pointer (cdr kill-ring))
19355
19356 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
19357 @end group
19358 @end smallexample
19359
19360 However, the @code{nthcdr} expression is more complicated. It uses
19361 the @code{mod} function to determine which @sc{cdr} to select.
19362
19363 (You will remember to look at inner functions first; indeed, we will
19364 have to go inside the @code{mod}.)
19365
19366 The @code{mod} function returns the value of its first argument modulo
19367 the second; that is to say, it returns the remainder after dividing
19368 the first argument by the second. The value returned has the same
19369 sign as the second argument.
19370
19371 @need 800
19372 Thus,
19373
19374 @smallexample
19375 @group
19376 (mod 12 4)
19377 @result{} 0 ;; @r{because there is no remainder}
19378 (mod 13 4)
19379 @result{} 1
19380 @end group
19381 @end smallexample
19382
19383 @need 1250
19384 In this case, the first argument is often smaller than the second.
19385 That is fine.
19386
19387 @smallexample
19388 @group
19389 (mod 0 4)
19390 @result{} 0
19391 (mod 1 4)
19392 @result{} 1
19393 @end group
19394 @end smallexample
19395
19396 We can guess what the @code{-} function does. It is like @code{+} but
19397 subtracts instead of adds; the @code{-} function subtracts its second
19398 argument from its first. Also, we already know what the @code{length}
19399 function does (@pxref{length}). It returns the length of a list.
19400
19401 And @code{n} is the name of the required argument to the
19402 @code{current-kill} function.
19403
19404 @need 1250
19405 So when the first argument to @code{nthcdr} is zero, the @code{nthcdr}
19406 expression returns the whole list, as you can see by evaluating the
19407 following:
19408
19409 @smallexample
19410 @group
19411 ;; kill-ring-yank-pointer @r{and} kill-ring @r{have a length of four}
19412 ;; @r{and} (mod (- 0 4) 4) @result{} 0
19413 (nthcdr (mod (- 0 4) 4)
19414 '("fourth line of text"
19415 "third line"
19416 "second piece of text"
19417 "first some text"))
19418 @end group
19419 @end smallexample
19420
19421 @need 1250
19422 When the first argument to the @code{current-kill} function is one,
19423 the @code{nthcdr} expression returns the list without its first
19424 element.
19425
19426 @smallexample
19427 @group
19428 (nthcdr (mod (- 1 4) 4)
19429 '("fourth line of text"
19430 "third line"
19431 "second piece of text"
19432 "first some text"))
19433 @end group
19434 @end smallexample
19435
19436 @cindex @samp{global variable} defined
19437 @cindex @samp{variable, global}, defined
19438 Incidentally, both @code{kill-ring} and @code{kill-ring-yank-pointer}
19439 are @dfn{global variables}. That means that any expression in Emacs
19440 Lisp can access them. They are not like the local variables set by
19441 @code{let} or like the symbols in an argument list.
19442 Local variables can only be accessed
19443 within the @code{let} that defines them or the function that specifies
19444 them in an argument list (and within expressions called by them).
19445
19446 @ignore
19447 @c texi2dvi fails when the name of the section is within ifnottex ...
19448 (@xref{Prevent confusion, , @code{let} Prevents Confusion}, and
19449 @ref{defun, , The @code{defun} Special Form}.)
19450 @end ignore
19451
19452 @node yank
19453 @appendixsec @code{yank}
19454 @findex yank
19455
19456 After learning about @code{current-kill}, the code for the
19457 @code{yank} function is almost easy.
19458
19459 The @code{yank} function does not use the
19460 @code{kill-ring-yank-pointer} variable directly. It calls
19461 @code{insert-for-yank} which calls @code{current-kill} which sets the
19462 @code{kill-ring-yank-pointer} variable.
19463
19464 @need 1250
19465 The code looks like this:
19466
19467 @c in GNU Emacs 22
19468 @smallexample
19469 @group
19470 (defun yank (&optional arg)
19471 "Reinsert (\"paste\") the last stretch of killed text.
19472 More precisely, reinsert the stretch of killed text most recently
19473 killed OR yanked. Put point at end, and set mark at beginning.
19474 With just \\[universal-argument] as argument, same but put point at
19475 beginning (and mark at end). With argument N, reinsert the Nth most
19476 recently killed stretch of killed text.
19477
19478 When this command inserts killed text into the buffer, it honors
19479 `yank-excluded-properties' and `yank-handler' as described in the
19480 doc string for `insert-for-yank-1', which see.
19481
19482 See also the command \\[yank-pop]."
19483 @end group
19484 @group
19485 (interactive "*P")
19486 (setq yank-window-start (window-start))
19487 ;; If we don't get all the way thru, make last-command indicate that
19488 ;; for the following command.
19489 (setq this-command t)
19490 (push-mark (point))
19491 @end group
19492 @group
19493 (insert-for-yank (current-kill (cond
19494 ((listp arg) 0)
19495 ((eq arg '-) -2)
19496 (t (1- arg)))))
19497 (if (consp arg)
19498 ;; This is like exchange-point-and-mark,
19499 ;; but doesn't activate the mark.
19500 ;; It is cleaner to avoid activation, even though the command
19501 ;; loop would deactivate the mark because we inserted text.
19502 (goto-char (prog1 (mark t)
19503 (set-marker (mark-marker) (point) (current-buffer)))))
19504 @end group
19505 @group
19506 ;; If we do get all the way thru, make this-command indicate that.
19507 (if (eq this-command t)
19508 (setq this-command 'yank))
19509 nil)
19510 @end group
19511 @end smallexample
19512
19513 The key expression is @code{insert-for-yank}, which inserts the string
19514 returned by @code{current-kill}, but removes some text properties from
19515 it.
19516
19517 However, before getting to that expression, the function sets the value
19518 of @code{yank-window-start} to the position returned by the
19519 @code{(window-start)} expression, the position at which the display
19520 currently starts. The @code{yank} function also sets
19521 @code{this-command} and pushes the mark.
19522
19523 After it yanks the appropriate element, if the optional argument is a
19524 @sc{cons} rather than a number or nothing, it puts point at beginning
19525 of the yanked text and mark at its end.
19526
19527 (The @code{prog1} function is like @code{progn} but returns the value
19528 of its first argument rather than the value of its last argument. Its
19529 first argument is forced to return the buffer's mark as an integer.
19530 You can see the documentation for these functions by placing point
19531 over them in this buffer and then typing @kbd{C-h f}
19532 (@code{describe-function}) followed by a @kbd{RET}; the default is the
19533 function.)
19534
19535 The last part of the function tells what to do when it succeeds.
19536
19537 @node yank-pop
19538 @appendixsec @code{yank-pop}
19539 @findex yank-pop
19540
19541 After understanding @code{yank} and @code{current-kill}, you know how
19542 to approach the @code{yank-pop} function. Leaving out the
19543 documentation to save space, it looks like this:
19544
19545 @c GNU Emacs 22
19546 @smallexample
19547 @group
19548 (defun yank-pop (&optional arg)
19549 "@dots{}"
19550 (interactive "*p")
19551 (if (not (eq last-command 'yank))
19552 (error "Previous command was not a yank"))
19553 @end group
19554 @group
19555 (setq this-command 'yank)
19556 (unless arg (setq arg 1))
19557 (let ((inhibit-read-only t)
19558 (before (< (point) (mark t))))
19559 @end group
19560 @group
19561 (if before
19562 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
19563 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
19564 (setq yank-undo-function nil)
19565 @end group
19566 @group
19567 (set-marker (mark-marker) (point) (current-buffer))
19568 (insert-for-yank (current-kill arg))
19569 ;; Set the window start back where it was in the yank command,
19570 ;; if possible.
19571 (set-window-start (selected-window) yank-window-start t)
19572 @end group
19573 @group
19574 (if before
19575 ;; This is like exchange-point-and-mark,
19576 ;; but doesn't activate the mark.
19577 ;; It is cleaner to avoid activation, even though the command
19578 ;; loop would deactivate the mark because we inserted text.
19579 (goto-char (prog1 (mark t)
19580 (set-marker (mark-marker)
19581 (point)
19582 (current-buffer))))))
19583 nil)
19584 @end group
19585 @end smallexample
19586
19587 The function is interactive with a small @samp{p} so the prefix
19588 argument is processed and passed to the function. The command can
19589 only be used after a previous yank; otherwise an error message is
19590 sent. This check uses the variable @code{last-command} which is set
19591 by @code{yank} and is discussed elsewhere.
19592 (@xref{copy-region-as-kill}.)
19593
19594 The @code{let} clause sets the variable @code{before} to true or false
19595 depending whether point is before or after mark and then the region
19596 between point and mark is deleted. This is the region that was just
19597 inserted by the previous yank and it is this text that will be
19598 replaced.
19599
19600 @code{funcall} calls its first argument as a function, passing
19601 remaining arguments to it. The first argument is whatever the
19602 @code{or} expression returns. The two remaining arguments are the
19603 positions of point and mark set by the preceding @code{yank} command.
19604
19605 There is more, but that is the hardest part.
19606
19607 @node ring file
19608 @appendixsec The @file{ring.el} File
19609 @cindex @file{ring.el} file
19610
19611 Interestingly, GNU Emacs posses a file called @file{ring.el} that
19612 provides many of the features we just discussed. But functions such
19613 as @code{kill-ring-yank-pointer} do not use this library, possibly
19614 because they were written earlier.
19615
19616 @node Full Graph
19617 @appendix A Graph with Labeled Axes
19618
19619 Printed axes help you understand a graph. They convey scale. In an
19620 earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
19621 wrote the code to print the body of a graph. Here we write the code
19622 for printing and labeling vertical and horizontal axes, along with the
19623 body itself.
19624
19625 @menu
19626 * Labeled Example::
19627 * print-graph Varlist:: @code{let} expression in @code{print-graph}.
19628 * print-Y-axis:: Print a label for the vertical axis.
19629 * print-X-axis:: Print a horizontal label.
19630 * Print Whole Graph:: The function to print a complete graph.
19631 @end menu
19632
19633 @ifnottex
19634 @node Labeled Example
19635 @unnumberedsec Labeled Example Graph
19636 @end ifnottex
19637
19638 Since insertions fill a buffer to the right and below point, the new
19639 graph printing function should first print the Y or vertical axis,
19640 then the body of the graph, and finally the X or horizontal axis.
19641 This sequence lays out for us the contents of the function:
19642
19643 @enumerate
19644 @item
19645 Set up code.
19646
19647 @item
19648 Print Y axis.
19649
19650 @item
19651 Print body of graph.
19652
19653 @item
19654 Print X axis.
19655 @end enumerate
19656
19657 @need 800
19658 Here is an example of how a finished graph should look:
19659
19660 @smallexample
19661 @group
19662 10 -
19663 *
19664 * *
19665 * **
19666 * ***
19667 5 - * *******
19668 * *** *******
19669 *************
19670 ***************
19671 1 - ****************
19672 | | | |
19673 1 5 10 15
19674 @end group
19675 @end smallexample
19676
19677 @noindent
19678 In this graph, both the vertical and the horizontal axes are labeled
19679 with numbers. However, in some graphs, the horizontal axis is time
19680 and would be better labeled with months, like this:
19681
19682 @smallexample
19683 @group
19684 5 - *
19685 * ** *
19686 *******
19687 ********** **
19688 1 - **************
19689 | ^ |
19690 Jan June Jan
19691 @end group
19692 @end smallexample
19693
19694 Indeed, with a little thought, we can easily come up with a variety of
19695 vertical and horizontal labeling schemes. Our task could become
19696 complicated. But complications breed confusion. Rather than permit
19697 this, it is better choose a simple labeling scheme for our first
19698 effort, and to modify or replace it later.
19699
19700 @need 1200
19701 These considerations suggest the following outline for the
19702 @code{print-graph} function:
19703
19704 @smallexample
19705 @group
19706 (defun print-graph (numbers-list)
19707 "@var{documentation}@dots{}"
19708 (let ((height @dots{}
19709 @dots{}))
19710 @end group
19711 @group
19712 (print-Y-axis height @dots{} )
19713 (graph-body-print numbers-list)
19714 (print-X-axis @dots{} )))
19715 @end group
19716 @end smallexample
19717
19718 We can work on each part of the @code{print-graph} function definition
19719 in turn.
19720
19721 @node print-graph Varlist
19722 @appendixsec The @code{print-graph} Varlist
19723 @cindex @code{print-graph} varlist
19724
19725 In writing the @code{print-graph} function, the first task is to write
19726 the varlist in the @code{let} expression. (We will leave aside for the
19727 moment any thoughts about making the function interactive or about the
19728 contents of its documentation string.)
19729
19730 The varlist should set several values. Clearly, the top of the label
19731 for the vertical axis must be at least the height of the graph, which
19732 means that we must obtain this information here. Note that the
19733 @code{print-graph-body} function also requires this information. There
19734 is no reason to calculate the height of the graph in two different
19735 places, so we should change @code{print-graph-body} from the way we
19736 defined it earlier to take advantage of the calculation.
19737
19738 Similarly, both the function for printing the X axis labels and the
19739 @code{print-graph-body} function need to learn the value of the width of
19740 each symbol. We can perform the calculation here and change the
19741 definition for @code{print-graph-body} from the way we defined it in the
19742 previous chapter.
19743
19744 The length of the label for the horizontal axis must be at least as long
19745 as the graph. However, this information is used only in the function
19746 that prints the horizontal axis, so it does not need to be calculated here.
19747
19748 These thoughts lead us directly to the following form for the varlist
19749 in the @code{let} for @code{print-graph}:
19750
19751 @smallexample
19752 @group
19753 (let ((height (apply 'max numbers-list)) ; @r{First version.}
19754 (symbol-width (length graph-blank)))
19755 @end group
19756 @end smallexample
19757
19758 @noindent
19759 As we shall see, this expression is not quite right.
19760
19761 @need 2000
19762 @node print-Y-axis
19763 @appendixsec The @code{print-Y-axis} Function
19764 @cindex Axis, print vertical
19765 @cindex Y axis printing
19766 @cindex Vertical axis printing
19767 @cindex Print vertical axis
19768
19769 The job of the @code{print-Y-axis} function is to print a label for
19770 the vertical axis that looks like this:
19771
19772 @smallexample
19773 @group
19774 10 -
19775
19776
19777
19778
19779 5 -
19780
19781
19782
19783 1 -
19784 @end group
19785 @end smallexample
19786
19787 @noindent
19788 The function should be passed the height of the graph, and then should
19789 construct and insert the appropriate numbers and marks.
19790
19791 @menu
19792 * print-Y-axis in Detail::
19793 * Height of label:: What height for the Y axis?
19794 * Compute a Remainder:: How to compute the remainder of a division.
19795 * Y Axis Element:: Construct a line for the Y axis.
19796 * Y-axis-column:: Generate a list of Y axis labels.
19797 * print-Y-axis Penultimate:: A not quite final version.
19798 @end menu
19799
19800 @ifnottex
19801 @node print-Y-axis in Detail
19802 @unnumberedsubsec The @code{print-Y-axis} Function in Detail
19803 @end ifnottex
19804
19805 It is easy enough to see in the figure what the Y axis label should
19806 look like; but to say in words, and then to write a function
19807 definition to do the job is another matter. It is not quite true to
19808 say that we want a number and a tic every five lines: there are only
19809 three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
19810 but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
19811 and 9). It is better to say that we want a number and a tic mark on
19812 the base line (number 1) and then that we want a number and a tic on
19813 the fifth line from the bottom and on every line that is a multiple of
19814 five.
19815
19816 @ifnottex
19817 @node Height of label
19818 @unnumberedsubsec What height should the label be?
19819 @end ifnottex
19820
19821 The next issue is what height the label should be? Suppose the maximum
19822 height of tallest column of the graph is seven. Should the highest
19823 label on the Y axis be @samp{5 -}, and should the graph stick up above
19824 the label? Or should the highest label be @samp{7 -}, and mark the peak
19825 of the graph? Or should the highest label be @code{10 -}, which is a
19826 multiple of five, and be higher than the topmost value of the graph?
19827
19828 The latter form is preferred. Most graphs are drawn within rectangles
19829 whose sides are an integral number of steps long---5, 10, 15, and so
19830 on for a step distance of five. But as soon as we decide to use a
19831 step height for the vertical axis, we discover that the simple
19832 expression in the varlist for computing the height is wrong. The
19833 expression is @code{(apply 'max numbers-list)}. This returns the
19834 precise height, not the maximum height plus whatever is necessary to
19835 round up to the nearest multiple of five. A more complex expression
19836 is required.
19837
19838 As usual in cases like this, a complex problem becomes simpler if it is
19839 divided into several smaller problems.
19840
19841 First, consider the case when the highest value of the graph is an
19842 integral multiple of five---when it is 5, 10, 15, or some higher
19843 multiple of five. We can use this value as the Y axis height.
19844
19845 A fairly simply way to determine whether a number is a multiple of
19846 five is to divide it by five and see if the division results in a
19847 remainder. If there is no remainder, the number is a multiple of
19848 five. Thus, seven divided by five has a remainder of two, and seven
19849 is not an integral multiple of five. Put in slightly different
19850 language, more reminiscent of the classroom, five goes into seven
19851 once, with a remainder of two. However, five goes into ten twice,
19852 with no remainder: ten is an integral multiple of five.
19853
19854 @node Compute a Remainder
19855 @appendixsubsec Side Trip: Compute a Remainder
19856
19857 @findex % @r{(remainder function)}
19858 @cindex Remainder function, @code{%}
19859 In Lisp, the function for computing a remainder is @code{%}. The
19860 function returns the remainder of its first argument divided by its
19861 second argument. As it happens, @code{%} is a function in Emacs Lisp
19862 that you cannot discover using @code{apropos}: you find nothing if you
19863 type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
19864 learn of the existence of @code{%} is to read about it in a book such
19865 as this or in the Emacs Lisp sources.
19866
19867 You can try the @code{%} function by evaluating the following two
19868 expressions:
19869
19870 @smallexample
19871 @group
19872 (% 7 5)
19873
19874 (% 10 5)
19875 @end group
19876 @end smallexample
19877
19878 @noindent
19879 The first expression returns 2 and the second expression returns 0.
19880
19881 To test whether the returned value is zero or some other number, we
19882 can use the @code{zerop} function. This function returns @code{t} if
19883 its argument, which must be a number, is zero.
19884
19885 @smallexample
19886 @group
19887 (zerop (% 7 5))
19888 @result{} nil
19889
19890 (zerop (% 10 5))
19891 @result{} t
19892 @end group
19893 @end smallexample
19894
19895 Thus, the following expression will return @code{t} if the height
19896 of the graph is evenly divisible by five:
19897
19898 @smallexample
19899 (zerop (% height 5))
19900 @end smallexample
19901
19902 @noindent
19903 (The value of @code{height}, of course, can be found from @code{(apply
19904 'max numbers-list)}.)
19905
19906 On the other hand, if the value of @code{height} is not a multiple of
19907 five, we want to reset the value to the next higher multiple of five.
19908 This is straightforward arithmetic using functions with which we are
19909 already familiar. First, we divide the value of @code{height} by five
19910 to determine how many times five goes into the number. Thus, five
19911 goes into twelve twice. If we add one to this quotient and multiply by
19912 five, we will obtain the value of the next multiple of five that is
19913 larger than the height. Five goes into twelve twice. Add one to two,
19914 and multiply by five; the result is fifteen, which is the next multiple
19915 of five that is higher than twelve. The Lisp expression for this is:
19916
19917 @smallexample
19918 (* (1+ (/ height 5)) 5)
19919 @end smallexample
19920
19921 @noindent
19922 For example, if you evaluate the following, the result is 15:
19923
19924 @smallexample
19925 (* (1+ (/ 12 5)) 5)
19926 @end smallexample
19927
19928 All through this discussion, we have been using `five' as the value
19929 for spacing labels on the Y axis; but we may want to use some other
19930 value. For generality, we should replace `five' with a variable to
19931 which we can assign a value. The best name I can think of for this
19932 variable is @code{Y-axis-label-spacing}.
19933
19934 @need 1250
19935 Using this term, and an @code{if} expression, we produce the
19936 following:
19937
19938 @smallexample
19939 @group
19940 (if (zerop (% height Y-axis-label-spacing))
19941 height
19942 ;; @r{else}
19943 (* (1+ (/ height Y-axis-label-spacing))
19944 Y-axis-label-spacing))
19945 @end group
19946 @end smallexample
19947
19948 @noindent
19949 This expression returns the value of @code{height} itself if the height
19950 is an even multiple of the value of the @code{Y-axis-label-spacing} or
19951 else it computes and returns a value of @code{height} that is equal to
19952 the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19953
19954 We can now include this expression in the @code{let} expression of the
19955 @code{print-graph} function (after first setting the value of
19956 @code{Y-axis-label-spacing}):
19957 @vindex Y-axis-label-spacing
19958
19959 @smallexample
19960 @group
19961 (defvar Y-axis-label-spacing 5
19962 "Number of lines from one Y axis label to next.")
19963 @end group
19964
19965 @group
19966 @dots{}
19967 (let* ((height (apply 'max numbers-list))
19968 (height-of-top-line
19969 (if (zerop (% height Y-axis-label-spacing))
19970 height
19971 @end group
19972 @group
19973 ;; @r{else}
19974 (* (1+ (/ height Y-axis-label-spacing))
19975 Y-axis-label-spacing)))
19976 (symbol-width (length graph-blank))))
19977 @dots{}
19978 @end group
19979 @end smallexample
19980
19981 @noindent
19982 (Note use of the @code{let*} function: the initial value of height is
19983 computed once by the @code{(apply 'max numbers-list)} expression and
19984 then the resulting value of @code{height} is used to compute its
19985 final value. @xref{fwd-para let, , The @code{let*} expression}, for
19986 more about @code{let*}.)
19987
19988 @node Y Axis Element
19989 @appendixsubsec Construct a Y Axis Element
19990
19991 When we print the vertical axis, we want to insert strings such as
19992 @w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19993 Moreover, we want the numbers and dashes to line up, so shorter
19994 numbers must be padded with leading spaces. If some of the strings
19995 use two digit numbers, the strings with single digit numbers must
19996 include a leading blank space before the number.
19997
19998 @findex number-to-string
19999 To figure out the length of the number, the @code{length} function is
20000 used. But the @code{length} function works only with a string, not with
20001 a number. So the number has to be converted from being a number to
20002 being a string. This is done with the @code{number-to-string} function.
20003 For example,
20004
20005 @smallexample
20006 @group
20007 (length (number-to-string 35))
20008 @result{} 2
20009
20010 (length (number-to-string 100))
20011 @result{} 3
20012 @end group
20013 @end smallexample
20014
20015 @noindent
20016 (@code{number-to-string} is also called @code{int-to-string}; you will
20017 see this alternative name in various sources.)
20018
20019 In addition, in each label, each number is followed by a string such
20020 as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
20021 This variable is defined with @code{defvar}:
20022
20023 @vindex Y-axis-tic
20024 @smallexample
20025 @group
20026 (defvar Y-axis-tic " - "
20027 "String that follows number in a Y axis label.")
20028 @end group
20029 @end smallexample
20030
20031 The length of the Y label is the sum of the length of the Y axis tic
20032 mark and the length of the number of the top of the graph.
20033
20034 @smallexample
20035 (length (concat (number-to-string height) Y-axis-tic)))
20036 @end smallexample
20037
20038 This value will be calculated by the @code{print-graph} function in
20039 its varlist as @code{full-Y-label-width} and passed on. (Note that we
20040 did not think to include this in the varlist when we first proposed it.)
20041
20042 To make a complete vertical axis label, a tic mark is concatenated
20043 with a number; and the two together may be preceded by one or more
20044 spaces depending on how long the number is. The label consists of
20045 three parts: the (optional) leading spaces, the number, and the tic
20046 mark. The function is passed the value of the number for the specific
20047 row, and the value of the width of the top line, which is calculated
20048 (just once) by @code{print-graph}.
20049
20050 @smallexample
20051 @group
20052 (defun Y-axis-element (number full-Y-label-width)
20053 "Construct a NUMBERed label element.
20054 A numbered element looks like this ` 5 - ',
20055 and is padded as needed so all line up with
20056 the element for the largest number."
20057 @end group
20058 @group
20059 (let* ((leading-spaces
20060 (- full-Y-label-width
20061 (length
20062 (concat (number-to-string number)
20063 Y-axis-tic)))))
20064 @end group
20065 @group
20066 (concat
20067 (make-string leading-spaces ? )
20068 (number-to-string number)
20069 Y-axis-tic)))
20070 @end group
20071 @end smallexample
20072
20073 The @code{Y-axis-element} function concatenates together the leading
20074 spaces, if any; the number, as a string; and the tic mark.
20075
20076 To figure out how many leading spaces the label will need, the
20077 function subtracts the actual length of the label---the length of the
20078 number plus the length of the tic mark---from the desired label width.
20079
20080 @findex make-string
20081 Blank spaces are inserted using the @code{make-string} function. This
20082 function takes two arguments: the first tells it how long the string
20083 will be and the second is a symbol for the character to insert, in a
20084 special format. The format is a question mark followed by a blank
20085 space, like this, @samp{? }. @xref{Character Type, , Character Type,
20086 elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
20087 syntax for characters. (Of course, you might want to replace the
20088 blank space by some other character @dots{} You know what to do.)
20089
20090 The @code{number-to-string} function is used in the concatenation
20091 expression, to convert the number to a string that is concatenated
20092 with the leading spaces and the tic mark.
20093
20094 @node Y-axis-column
20095 @appendixsubsec Create a Y Axis Column
20096
20097 The preceding functions provide all the tools needed to construct a
20098 function that generates a list of numbered and blank strings to insert
20099 as the label for the vertical axis:
20100
20101 @findex Y-axis-column
20102 @smallexample
20103 @group
20104 (defun Y-axis-column (height width-of-label)
20105 "Construct list of Y axis labels and blank strings.
20106 For HEIGHT of line above base and WIDTH-OF-LABEL."
20107 (let (Y-axis)
20108 @group
20109 @end group
20110 (while (> height 1)
20111 (if (zerop (% height Y-axis-label-spacing))
20112 ;; @r{Insert label.}
20113 (setq Y-axis
20114 (cons
20115 (Y-axis-element height width-of-label)
20116 Y-axis))
20117 @group
20118 @end group
20119 ;; @r{Else, insert blanks.}
20120 (setq Y-axis
20121 (cons
20122 (make-string width-of-label ? )
20123 Y-axis)))
20124 (setq height (1- height)))
20125 ;; @r{Insert base line.}
20126 (setq Y-axis
20127 (cons (Y-axis-element 1 width-of-label) Y-axis))
20128 (nreverse Y-axis)))
20129 @end group
20130 @end smallexample
20131
20132 In this function, we start with the value of @code{height} and
20133 repetitively subtract one from its value. After each subtraction, we
20134 test to see whether the value is an integral multiple of the
20135 @code{Y-axis-label-spacing}. If it is, we construct a numbered label
20136 using the @code{Y-axis-element} function; if not, we construct a
20137 blank label using the @code{make-string} function. The base line
20138 consists of the number one followed by a tic mark.
20139
20140 @need 2000
20141 @node print-Y-axis Penultimate
20142 @appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
20143
20144 The list constructed by the @code{Y-axis-column} function is passed to
20145 the @code{print-Y-axis} function, which inserts the list as a column.
20146
20147 @findex print-Y-axis
20148 @smallexample
20149 @group
20150 (defun print-Y-axis (height full-Y-label-width)
20151 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
20152 Height must be the maximum height of the graph.
20153 Full width is the width of the highest label element."
20154 ;; Value of height and full-Y-label-width
20155 ;; are passed by `print-graph'.
20156 @end group
20157 @group
20158 (let ((start (point)))
20159 (insert-rectangle
20160 (Y-axis-column height full-Y-label-width))
20161 ;; @r{Place point ready for inserting graph.}
20162 (goto-char start)
20163 ;; @r{Move point forward by value of} full-Y-label-width
20164 (forward-char full-Y-label-width)))
20165 @end group
20166 @end smallexample
20167
20168 The @code{print-Y-axis} uses the @code{insert-rectangle} function to
20169 insert the Y axis labels created by the @code{Y-axis-column} function.
20170 In addition, it places point at the correct position for printing the body of
20171 the graph.
20172
20173 You can test @code{print-Y-axis}:
20174
20175 @enumerate
20176 @item
20177 Install
20178
20179 @smallexample
20180 @group
20181 Y-axis-label-spacing
20182 Y-axis-tic
20183 Y-axis-element
20184 Y-axis-column
20185 print-Y-axis
20186 @end group
20187 @end smallexample
20188
20189 @item
20190 Copy the following expression:
20191
20192 @smallexample
20193 (print-Y-axis 12 5)
20194 @end smallexample
20195
20196 @item
20197 Switch to the @file{*scratch*} buffer and place the cursor where you
20198 want the axis labels to start.
20199
20200 @item
20201 Type @kbd{M-:} (@code{eval-expression}).
20202
20203 @item
20204 Yank the @code{graph-body-print} expression into the minibuffer
20205 with @kbd{C-y} (@code{yank)}.
20206
20207 @item
20208 Press @key{RET} to evaluate the expression.
20209 @end enumerate
20210
20211 Emacs will print labels vertically, the top one being @w{@samp{10 -@w{
20212 }}}. (The @code{print-graph} function will pass the value of
20213 @code{height-of-top-line}, which in this case will end up as 15,
20214 thereby getting rid of what might appear as a bug.)
20215
20216 @need 2000
20217 @node print-X-axis
20218 @appendixsec The @code{print-X-axis} Function
20219 @cindex Axis, print horizontal
20220 @cindex X axis printing
20221 @cindex Print horizontal axis
20222 @cindex Horizontal axis printing
20223
20224 X axis labels are much like Y axis labels, except that the ticks are on a
20225 line above the numbers. Labels should look like this:
20226
20227 @smallexample
20228 @group
20229 | | | |
20230 1 5 10 15
20231 @end group
20232 @end smallexample
20233
20234 The first tic is under the first column of the graph and is preceded by
20235 several blank spaces. These spaces provide room in rows above for the Y
20236 axis labels. The second, third, fourth, and subsequent ticks are all
20237 spaced equally, according to the value of @code{X-axis-label-spacing}.
20238
20239 The second row of the X axis consists of numbers, preceded by several
20240 blank spaces and also separated according to the value of the variable
20241 @code{X-axis-label-spacing}.
20242
20243 The value of the variable @code{X-axis-label-spacing} should itself be
20244 measured in units of @code{symbol-width}, since you may want to change
20245 the width of the symbols that you are using to print the body of the
20246 graph without changing the ways the graph is labeled.
20247
20248 @menu
20249 * Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
20250 * X Axis Tic Marks:: Create tic marks for the horizontal axis.
20251 @end menu
20252
20253 @ifnottex
20254 @node Similarities differences
20255 @unnumberedsubsec Similarities and differences
20256 @end ifnottex
20257
20258 The @code{print-X-axis} function is constructed in more or less the
20259 same fashion as the @code{print-Y-axis} function except that it has
20260 two lines: the line of tic marks and the numbers. We will write a
20261 separate function to print each line and then combine them within the
20262 @code{print-X-axis} function.
20263
20264 This is a three step process:
20265
20266 @enumerate
20267 @item
20268 Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
20269
20270 @item
20271 Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
20272
20273 @item
20274 Write a function to print both lines, the @code{print-X-axis} function,
20275 using @code{print-X-axis-tic-line} and
20276 @code{print-X-axis-numbered-line}.
20277 @end enumerate
20278
20279 @node X Axis Tic Marks
20280 @appendixsubsec X Axis Tic Marks
20281
20282 The first function should print the X axis tic marks. We must specify
20283 the tic marks themselves and their spacing:
20284
20285 @smallexample
20286 @group
20287 (defvar X-axis-label-spacing
20288 (if (boundp 'graph-blank)
20289 (* 5 (length graph-blank)) 5)
20290 "Number of units from one X axis label to next.")
20291 @end group
20292 @end smallexample
20293
20294 @noindent
20295 (Note that the value of @code{graph-blank} is set by another
20296 @code{defvar}. The @code{boundp} predicate checks whether it has
20297 already been set; @code{boundp} returns @code{nil} if it has not. If
20298 @code{graph-blank} were unbound and we did not use this conditional
20299 construction, in a recent GNU Emacs, we would enter the debugger and
20300 see an error message saying @samp{@w{Debugger entered--Lisp error:}
20301 @w{(void-variable graph-blank)}}.)
20302
20303 @need 1200
20304 Here is the @code{defvar} for @code{X-axis-tic-symbol}:
20305
20306 @smallexample
20307 @group
20308 (defvar X-axis-tic-symbol "|"
20309 "String to insert to point to a column in X axis.")
20310 @end group
20311 @end smallexample
20312
20313 @need 1250
20314 The goal is to make a line that looks like this:
20315
20316 @smallexample
20317 | | | |
20318 @end smallexample
20319
20320 The first tic is indented so that it is under the first column, which is
20321 indented to provide space for the Y axis labels.
20322
20323 A tic element consists of the blank spaces that stretch from one tic to
20324 the next plus a tic symbol. The number of blanks is determined by the
20325 width of the tic symbol and the @code{X-axis-label-spacing}.
20326
20327 @need 1250
20328 The code looks like this:
20329
20330 @smallexample
20331 @group
20332 ;;; X-axis-tic-element
20333 @dots{}
20334 (concat
20335 (make-string
20336 ;; @r{Make a string of blanks.}
20337 (- (* symbol-width X-axis-label-spacing)
20338 (length X-axis-tic-symbol))
20339 ? )
20340 ;; @r{Concatenate blanks with tic symbol.}
20341 X-axis-tic-symbol)
20342 @dots{}
20343 @end group
20344 @end smallexample
20345
20346 Next, we determine how many blanks are needed to indent the first tic
20347 mark to the first column of the graph. This uses the value of
20348 @code{full-Y-label-width} passed it by the @code{print-graph} function.
20349
20350 @need 1250
20351 The code to make @code{X-axis-leading-spaces}
20352 looks like this:
20353
20354 @smallexample
20355 @group
20356 ;; X-axis-leading-spaces
20357 @dots{}
20358 (make-string full-Y-label-width ? )
20359 @dots{}
20360 @end group
20361 @end smallexample
20362
20363 We also need to determine the length of the horizontal axis, which is
20364 the length of the numbers list, and the number of ticks in the horizontal
20365 axis:
20366
20367 @smallexample
20368 @group
20369 ;; X-length
20370 @dots{}
20371 (length numbers-list)
20372 @end group
20373
20374 @group
20375 ;; tic-width
20376 @dots{}
20377 (* symbol-width X-axis-label-spacing)
20378 @end group
20379
20380 @group
20381 ;; number-of-X-ticks
20382 (if (zerop (% (X-length tic-width)))
20383 (/ (X-length tic-width))
20384 (1+ (/ (X-length tic-width))))
20385 @end group
20386 @end smallexample
20387
20388 @need 1250
20389 All this leads us directly to the function for printing the X axis tic line:
20390
20391 @findex print-X-axis-tic-line
20392 @smallexample
20393 @group
20394 (defun print-X-axis-tic-line
20395 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20396 "Print ticks for X axis."
20397 (insert X-axis-leading-spaces)
20398 (insert X-axis-tic-symbol) ; @r{Under first column.}
20399 @end group
20400 @group
20401 ;; @r{Insert second tic in the right spot.}
20402 (insert (concat
20403 (make-string
20404 (- (* symbol-width X-axis-label-spacing)
20405 ;; @r{Insert white space up to second tic symbol.}
20406 (* 2 (length X-axis-tic-symbol)))
20407 ? )
20408 X-axis-tic-symbol))
20409 @end group
20410 @group
20411 ;; @r{Insert remaining ticks.}
20412 (while (> number-of-X-tics 1)
20413 (insert X-axis-tic-element)
20414 (setq number-of-X-tics (1- number-of-X-tics))))
20415 @end group
20416 @end smallexample
20417
20418 The line of numbers is equally straightforward:
20419
20420 @need 1250
20421 First, we create a numbered element with blank spaces before each number:
20422
20423 @findex X-axis-element
20424 @smallexample
20425 @group
20426 (defun X-axis-element (number)
20427 "Construct a numbered X axis element."
20428 (let ((leading-spaces
20429 (- (* symbol-width X-axis-label-spacing)
20430 (length (number-to-string number)))))
20431 (concat (make-string leading-spaces ? )
20432 (number-to-string number))))
20433 @end group
20434 @end smallexample
20435
20436 Next, we create the function to print the numbered line, starting with
20437 the number ``1'' under the first column:
20438
20439 @findex print-X-axis-numbered-line
20440 @smallexample
20441 @group
20442 (defun print-X-axis-numbered-line
20443 (number-of-X-tics X-axis-leading-spaces)
20444 "Print line of X-axis numbers"
20445 (let ((number X-axis-label-spacing))
20446 (insert X-axis-leading-spaces)
20447 (insert "1")
20448 @end group
20449 @group
20450 (insert (concat
20451 (make-string
20452 ;; @r{Insert white space up to next number.}
20453 (- (* symbol-width X-axis-label-spacing) 2)
20454 ? )
20455 (number-to-string number)))
20456 @end group
20457 @group
20458 ;; @r{Insert remaining numbers.}
20459 (setq number (+ number X-axis-label-spacing))
20460 (while (> number-of-X-tics 1)
20461 (insert (X-axis-element number))
20462 (setq number (+ number X-axis-label-spacing))
20463 (setq number-of-X-tics (1- number-of-X-tics)))))
20464 @end group
20465 @end smallexample
20466
20467 Finally, we need to write the @code{print-X-axis} that uses
20468 @code{print-X-axis-tic-line} and
20469 @code{print-X-axis-numbered-line}.
20470
20471 The function must determine the local values of the variables used by both
20472 @code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
20473 then it must call them. Also, it must print the carriage return that
20474 separates the two lines.
20475
20476 The function consists of a varlist that specifies five local variables,
20477 and calls to each of the two line printing functions:
20478
20479 @findex print-X-axis
20480 @smallexample
20481 @group
20482 (defun print-X-axis (numbers-list)
20483 "Print X axis labels to length of NUMBERS-LIST."
20484 (let* ((leading-spaces
20485 (make-string full-Y-label-width ? ))
20486 @end group
20487 @group
20488 ;; symbol-width @r{is provided by} graph-body-print
20489 (tic-width (* symbol-width X-axis-label-spacing))
20490 (X-length (length numbers-list))
20491 @end group
20492 @group
20493 (X-tic
20494 (concat
20495 (make-string
20496 @end group
20497 @group
20498 ;; @r{Make a string of blanks.}
20499 (- (* symbol-width X-axis-label-spacing)
20500 (length X-axis-tic-symbol))
20501 ? )
20502 @end group
20503 @group
20504 ;; @r{Concatenate blanks with tic symbol.}
20505 X-axis-tic-symbol))
20506 @end group
20507 @group
20508 (tic-number
20509 (if (zerop (% X-length tic-width))
20510 (/ X-length tic-width)
20511 (1+ (/ X-length tic-width)))))
20512 @end group
20513 @group
20514 (print-X-axis-tic-line tic-number leading-spaces X-tic)
20515 (insert "\n")
20516 (print-X-axis-numbered-line tic-number leading-spaces)))
20517 @end group
20518 @end smallexample
20519
20520 @need 1250
20521 You can test @code{print-X-axis}:
20522
20523 @enumerate
20524 @item
20525 Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
20526 @code{print-X-axis-tic-line}, as well as @code{X-axis-element},
20527 @code{print-X-axis-numbered-line}, and @code{print-X-axis}.
20528
20529 @item
20530 Copy the following expression:
20531
20532 @smallexample
20533 @group
20534 (progn
20535 (let ((full-Y-label-width 5)
20536 (symbol-width 1))
20537 (print-X-axis
20538 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
20539 @end group
20540 @end smallexample
20541
20542 @item
20543 Switch to the @file{*scratch*} buffer and place the cursor where you
20544 want the axis labels to start.
20545
20546 @item
20547 Type @kbd{M-:} (@code{eval-expression}).
20548
20549 @item
20550 Yank the test expression into the minibuffer
20551 with @kbd{C-y} (@code{yank)}.
20552
20553 @item
20554 Press @key{RET} to evaluate the expression.
20555 @end enumerate
20556
20557 @need 1250
20558 Emacs will print the horizontal axis like this:
20559 @sp 1
20560
20561 @smallexample
20562 @group
20563 | | | | |
20564 1 5 10 15 20
20565 @end group
20566 @end smallexample
20567
20568 @node Print Whole Graph
20569 @appendixsec Printing the Whole Graph
20570 @cindex Printing the whole graph
20571 @cindex Whole graph printing
20572 @cindex Graph, printing all
20573
20574 Now we are nearly ready to print the whole graph.
20575
20576 The function to print the graph with the proper labels follows the
20577 outline we created earlier (@pxref{Full Graph, , A Graph with Labeled
20578 Axes}), but with additions.
20579
20580 @need 1250
20581 Here is the outline:
20582
20583 @smallexample
20584 @group
20585 (defun print-graph (numbers-list)
20586 "@var{documentation}@dots{}"
20587 (let ((height @dots{}
20588 @dots{}))
20589 @end group
20590 @group
20591 (print-Y-axis height @dots{} )
20592 (graph-body-print numbers-list)
20593 (print-X-axis @dots{} )))
20594 @end group
20595 @end smallexample
20596
20597 @menu
20598 * The final version:: A few changes.
20599 * Test print-graph:: Run a short test.
20600 * Graphing words in defuns:: Executing the final code.
20601 * lambda:: How to write an anonymous function.
20602 * mapcar:: Apply a function to elements of a list.
20603 * Another Bug:: Yet another bug @dots{} most insidious.
20604 * Final printed graph:: The graph itself!
20605 @end menu
20606
20607 @ifnottex
20608 @node The final version
20609 @unnumberedsubsec Changes for the Final Version
20610 @end ifnottex
20611
20612 The final version is different from what we planned in two ways:
20613 first, it contains additional values calculated once in the varlist;
20614 second, it carries an option to specify the labels' increment per row.
20615 This latter feature turns out to be essential; otherwise, a graph may
20616 have more rows than fit on a display or on a sheet of paper.
20617
20618 @need 1500
20619 This new feature requires a change to the @code{Y-axis-column}
20620 function, to add @code{vertical-step} to it. The function looks like
20621 this:
20622
20623 @findex Y-axis-column @r{Final version.}
20624 @smallexample
20625 @group
20626 ;;; @r{Final version.}
20627 (defun Y-axis-column
20628 (height width-of-label &optional vertical-step)
20629 "Construct list of labels for Y axis.
20630 HEIGHT is maximum height of graph.
20631 WIDTH-OF-LABEL is maximum width of label.
20632 VERTICAL-STEP, an option, is a positive integer
20633 that specifies how much a Y axis label increments
20634 for each line. For example, a step of 5 means
20635 that each line is five units of the graph."
20636 @end group
20637 @group
20638 (let (Y-axis
20639 (number-per-line (or vertical-step 1)))
20640 (while (> height 1)
20641 (if (zerop (% height Y-axis-label-spacing))
20642 @end group
20643 @group
20644 ;; @r{Insert label.}
20645 (setq Y-axis
20646 (cons
20647 (Y-axis-element
20648 (* height number-per-line)
20649 width-of-label)
20650 Y-axis))
20651 @end group
20652 @group
20653 ;; @r{Else, insert blanks.}
20654 (setq Y-axis
20655 (cons
20656 (make-string width-of-label ? )
20657 Y-axis)))
20658 (setq height (1- height)))
20659 @end group
20660 @group
20661 ;; @r{Insert base line.}
20662 (setq Y-axis (cons (Y-axis-element
20663 (or vertical-step 1)
20664 width-of-label)
20665 Y-axis))
20666 (nreverse Y-axis)))
20667 @end group
20668 @end smallexample
20669
20670 The values for the maximum height of graph and the width of a symbol
20671 are computed by @code{print-graph} in its @code{let} expression; so
20672 @code{graph-body-print} must be changed to accept them.
20673
20674 @findex graph-body-print @r{Final version.}
20675 @smallexample
20676 @group
20677 ;;; @r{Final version.}
20678 (defun graph-body-print (numbers-list height symbol-width)
20679 "Print a bar graph of the NUMBERS-LIST.
20680 The numbers-list consists of the Y-axis values.
20681 HEIGHT is maximum height of graph.
20682 SYMBOL-WIDTH is number of each column."
20683 @end group
20684 @group
20685 (let (from-position)
20686 (while numbers-list
20687 (setq from-position (point))
20688 (insert-rectangle
20689 (column-of-graph height (car numbers-list)))
20690 (goto-char from-position)
20691 (forward-char symbol-width)
20692 @end group
20693 @group
20694 ;; @r{Draw graph column by column.}
20695 (sit-for 0)
20696 (setq numbers-list (cdr numbers-list)))
20697 ;; @r{Place point for X axis labels.}
20698 (forward-line height)
20699 (insert "\n")))
20700 @end group
20701 @end smallexample
20702
20703 @need 1250
20704 Finally, the code for the @code{print-graph} function:
20705
20706 @findex print-graph @r{Final version.}
20707 @smallexample
20708 @group
20709 ;;; @r{Final version.}
20710 (defun print-graph
20711 (numbers-list &optional vertical-step)
20712 "Print labeled bar graph of the NUMBERS-LIST.
20713 The numbers-list consists of the Y-axis values.
20714 @end group
20715
20716 @group
20717 Optionally, VERTICAL-STEP, a positive integer,
20718 specifies how much a Y axis label increments for
20719 each line. For example, a step of 5 means that
20720 each row is five units."
20721 @end group
20722 @group
20723 (let* ((symbol-width (length graph-blank))
20724 ;; @code{height} @r{is both the largest number}
20725 ;; @r{and the number with the most digits.}
20726 (height (apply 'max numbers-list))
20727 @end group
20728 @group
20729 (height-of-top-line
20730 (if (zerop (% height Y-axis-label-spacing))
20731 height
20732 ;; @r{else}
20733 (* (1+ (/ height Y-axis-label-spacing))
20734 Y-axis-label-spacing)))
20735 @end group
20736 @group
20737 (vertical-step (or vertical-step 1))
20738 (full-Y-label-width
20739 (length
20740 @end group
20741 @group
20742 (concat
20743 (number-to-string
20744 (* height-of-top-line vertical-step))
20745 Y-axis-tic))))
20746 @end group
20747
20748 @group
20749 (print-Y-axis
20750 height-of-top-line full-Y-label-width vertical-step)
20751 @end group
20752 @group
20753 (graph-body-print
20754 numbers-list height-of-top-line symbol-width)
20755 (print-X-axis numbers-list)))
20756 @end group
20757 @end smallexample
20758
20759 @node Test print-graph
20760 @appendixsubsec Testing @code{print-graph}
20761
20762 @need 1250
20763 We can test the @code{print-graph} function with a short list of numbers:
20764
20765 @enumerate
20766 @item
20767 Install the final versions of @code{Y-axis-column},
20768 @code{graph-body-print}, and @code{print-graph} (in addition to the
20769 rest of the code.)
20770
20771 @item
20772 Copy the following expression:
20773
20774 @smallexample
20775 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
20776 @end smallexample
20777
20778 @item
20779 Switch to the @file{*scratch*} buffer and place the cursor where you
20780 want the axis labels to start.
20781
20782 @item
20783 Type @kbd{M-:} (@code{eval-expression}).
20784
20785 @item
20786 Yank the test expression into the minibuffer
20787 with @kbd{C-y} (@code{yank)}.
20788
20789 @item
20790 Press @key{RET} to evaluate the expression.
20791 @end enumerate
20792
20793 @need 1250
20794 Emacs will print a graph that looks like this:
20795
20796 @smallexample
20797 @group
20798 10 -
20799
20800
20801 *
20802 ** *
20803 5 - **** *
20804 **** ***
20805 * *********
20806 ************
20807 1 - *************
20808
20809 | | | |
20810 1 5 10 15
20811 @end group
20812 @end smallexample
20813
20814 @need 1200
20815 On the other hand, if you pass @code{print-graph} a
20816 @code{vertical-step} value of 2, by evaluating this expression:
20817
20818 @smallexample
20819 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
20820 @end smallexample
20821
20822 @need 1250
20823 @noindent
20824 The graph looks like this:
20825
20826 @smallexample
20827 @group
20828 20 -
20829
20830
20831 *
20832 ** *
20833 10 - **** *
20834 **** ***
20835 * *********
20836 ************
20837 2 - *************
20838
20839 | | | |
20840 1 5 10 15
20841 @end group
20842 @end smallexample
20843
20844 @noindent
20845 (A question: is the `2' on the bottom of the vertical axis a bug or a
20846 feature? If you think it is a bug, and should be a `1' instead, (or
20847 even a `0'), you can modify the sources.)
20848
20849 @node Graphing words in defuns
20850 @appendixsubsec Graphing Numbers of Words and Symbols
20851
20852 Now for the graph for which all this code was written: a graph that
20853 shows how many function definitions contain fewer than 10 words and
20854 symbols, how many contain between 10 and 19 words and symbols, how
20855 many contain between 20 and 29 words and symbols, and so on.
20856
20857 This is a multi-step process. First make sure you have loaded all the
20858 requisite code.
20859
20860 @need 1500
20861 It is a good idea to reset the value of @code{top-of-ranges} in case
20862 you have set it to some different value. You can evaluate the
20863 following:
20864
20865 @smallexample
20866 @group
20867 (setq top-of-ranges
20868 '(10 20 30 40 50
20869 60 70 80 90 100
20870 110 120 130 140 150
20871 160 170 180 190 200
20872 210 220 230 240 250
20873 260 270 280 290 300)
20874 @end group
20875 @end smallexample
20876
20877 @noindent
20878 Next create a list of the number of words and symbols in each range.
20879
20880 @need 1500
20881 @noindent
20882 Evaluate the following:
20883
20884 @smallexample
20885 @group
20886 (setq list-for-graph
20887 (defuns-per-range
20888 (sort
20889 (recursive-lengths-list-many-files
20890 (directory-files "/usr/local/emacs/lisp"
20891 t ".+el$"))
20892 '<)
20893 top-of-ranges))
20894 @end group
20895 @end smallexample
20896
20897 @noindent
20898 On my old machine, this took about an hour. It looked though 303 Lisp
20899 files in my copy of Emacs version 19.23. After all that computing,
20900 the @code{list-for-graph} had this value:
20901
20902 @smallexample
20903 @group
20904 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
20905 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20906 @end group
20907 @end smallexample
20908
20909 @noindent
20910 This means that my copy of Emacs had 537 function definitions with
20911 fewer than 10 words or symbols in them, 1,027 function definitions
20912 with 10 to 19 words or symbols in them, 955 function definitions with
20913 20 to 29 words or symbols in them, and so on.
20914
20915 Clearly, just by looking at this list we can see that most function
20916 definitions contain ten to thirty words and symbols.
20917
20918 Now for printing. We do @emph{not} want to print a graph that is
20919 1,030 lines high @dots{} Instead, we should print a graph that is
20920 fewer than twenty-five lines high. A graph that height can be
20921 displayed on almost any monitor, and easily printed on a sheet of paper.
20922
20923 This means that each value in @code{list-for-graph} must be reduced to
20924 one-fiftieth its present value.
20925
20926 Here is a short function to do just that, using two functions we have
20927 not yet seen, @code{mapcar} and @code{lambda}.
20928
20929 @smallexample
20930 @group
20931 (defun one-fiftieth (full-range)
20932 "Return list, each number one-fiftieth of previous."
20933 (mapcar (lambda (arg) (/ arg 50)) full-range))
20934 @end group
20935 @end smallexample
20936
20937 @node lambda
20938 @appendixsubsec A @code{lambda} Expression: Useful Anonymity
20939 @cindex Anonymous function
20940 @findex lambda
20941
20942 @code{lambda} is the symbol for an anonymous function, a function
20943 without a name. Every time you use an anonymous function, you need to
20944 include its whole body.
20945
20946 @need 1250
20947 @noindent
20948 Thus,
20949
20950 @smallexample
20951 (lambda (arg) (/ arg 50))
20952 @end smallexample
20953
20954 @noindent
20955 is a function definition that says `return the value resulting from
20956 dividing whatever is passed to me as @code{arg} by 50'.
20957
20958 @need 1200
20959 Earlier, for example, we had a function @code{multiply-by-seven}; it
20960 multiplied its argument by 7. This function is similar, except it
20961 divides its argument by 50; and, it has no name. The anonymous
20962 equivalent of @code{multiply-by-seven} is:
20963
20964 @smallexample
20965 (lambda (number) (* 7 number))
20966 @end smallexample
20967
20968 @noindent
20969 (@xref{defun, , The @code{defun} Special Form}.)
20970
20971 @need 1250
20972 @noindent
20973 If we want to multiply 3 by 7, we can write:
20974
20975 @c !!! Clear print-postscript-figures if the computer formatting this
20976 @c document is too small and cannot handle all the diagrams and figures.
20977 @c clear print-postscript-figures
20978 @c set print-postscript-figures
20979 @c lambda example diagram #1
20980 @ifnottex
20981 @smallexample
20982 @group
20983 (multiply-by-seven 3)
20984 \_______________/ ^
20985 | |
20986 function argument
20987 @end group
20988 @end smallexample
20989 @end ifnottex
20990 @ifset print-postscript-figures
20991 @sp 1
20992 @tex
20993 @center @image{lambda-1}
20994 %%%% old method of including an image
20995 % \input /usr/local/lib/tex/inputs/psfig.tex
20996 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
20997 % \catcode`\@=0 %
20998 @end tex
20999 @sp 1
21000 @end ifset
21001 @ifclear print-postscript-figures
21002 @iftex
21003 @smallexample
21004 @group
21005 (multiply-by-seven 3)
21006 \_______________/ ^
21007 | |
21008 function argument
21009 @end group
21010 @end smallexample
21011 @end iftex
21012 @end ifclear
21013
21014 @noindent
21015 This expression returns 21.
21016
21017 @need 1250
21018 @noindent
21019 Similarly, we can write:
21020
21021 @c lambda example diagram #2
21022 @ifnottex
21023 @smallexample
21024 @group
21025 ((lambda (number) (* 7 number)) 3)
21026 \____________________________/ ^
21027 | |
21028 anonymous function argument
21029 @end group
21030 @end smallexample
21031 @end ifnottex
21032 @ifset print-postscript-figures
21033 @sp 1
21034 @tex
21035 @center @image{lambda-2}
21036 %%%% old method of including an image
21037 % \input /usr/local/lib/tex/inputs/psfig.tex
21038 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
21039 % \catcode`\@=0 %
21040 @end tex
21041 @sp 1
21042 @end ifset
21043 @ifclear print-postscript-figures
21044 @iftex
21045 @smallexample
21046 @group
21047 ((lambda (number) (* 7 number)) 3)
21048 \____________________________/ ^
21049 | |
21050 anonymous function argument
21051 @end group
21052 @end smallexample
21053 @end iftex
21054 @end ifclear
21055
21056 @need 1250
21057 @noindent
21058 If we want to divide 100 by 50, we can write:
21059
21060 @c lambda example diagram #3
21061 @ifnottex
21062 @smallexample
21063 @group
21064 ((lambda (arg) (/ arg 50)) 100)
21065 \______________________/ \_/
21066 | |
21067 anonymous function argument
21068 @end group
21069 @end smallexample
21070 @end ifnottex
21071 @ifset print-postscript-figures
21072 @sp 1
21073 @tex
21074 @center @image{lambda-3}
21075 %%%% old method of including an image
21076 % \input /usr/local/lib/tex/inputs/psfig.tex
21077 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
21078 % \catcode`\@=0 %
21079 @end tex
21080 @sp 1
21081 @end ifset
21082 @ifclear print-postscript-figures
21083 @iftex
21084 @smallexample
21085 @group
21086 ((lambda (arg) (/ arg 50)) 100)
21087 \______________________/ \_/
21088 | |
21089 anonymous function argument
21090 @end group
21091 @end smallexample
21092 @end iftex
21093 @end ifclear
21094
21095 @noindent
21096 This expression returns 2. The 100 is passed to the function, which
21097 divides that number by 50.
21098
21099 @xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
21100 Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
21101 expressions derive from the Lambda Calculus.
21102
21103 @node mapcar
21104 @appendixsubsec The @code{mapcar} Function
21105 @findex mapcar
21106
21107 @code{mapcar} is a function that calls its first argument with each
21108 element of its second argument, in turn. The second argument must be
21109 a sequence.
21110
21111 The @samp{map} part of the name comes from the mathematical phrase,
21112 `mapping over a domain', meaning to apply a function to each of the
21113 elements in a domain. The mathematical phrase is based on the
21114 metaphor of a surveyor walking, one step at a time, over an area he is
21115 mapping. And @samp{car}, of course, comes from the Lisp notion of the
21116 first of a list.
21117
21118 @need 1250
21119 @noindent
21120 For example,
21121
21122 @smallexample
21123 @group
21124 (mapcar '1+ '(2 4 6))
21125 @result{} (3 5 7)
21126 @end group
21127 @end smallexample
21128
21129 @noindent
21130 The function @code{1+} which adds one to its argument, is executed on
21131 @emph{each} element of the list, and a new list is returned.
21132
21133 Contrast this with @code{apply}, which applies its first argument to
21134 all the remaining.
21135 (@xref{Readying a Graph, , Readying a Graph}, for a explanation of
21136 @code{apply}.)
21137
21138 @need 1250
21139 In the definition of @code{one-fiftieth}, the first argument is the
21140 anonymous function:
21141
21142 @smallexample
21143 (lambda (arg) (/ arg 50))
21144 @end smallexample
21145
21146 @noindent
21147 and the second argument is @code{full-range}, which will be bound to
21148 @code{list-for-graph}.
21149
21150 @need 1250
21151 The whole expression looks like this:
21152
21153 @smallexample
21154 (mapcar (lambda (arg) (/ arg 50)) full-range))
21155 @end smallexample
21156
21157 @xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
21158 Lisp Reference Manual}, for more about @code{mapcar}.
21159
21160 Using the @code{one-fiftieth} function, we can generate a list in
21161 which each element is one-fiftieth the size of the corresponding
21162 element in @code{list-for-graph}.
21163
21164 @smallexample
21165 @group
21166 (setq fiftieth-list-for-graph
21167 (one-fiftieth list-for-graph))
21168 @end group
21169 @end smallexample
21170
21171 @need 1250
21172 The resulting list looks like this:
21173
21174 @smallexample
21175 @group
21176 (10 20 19 15 11 9 6 5 4 3 3 2 2
21177 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
21178 @end group
21179 @end smallexample
21180
21181 @noindent
21182 This, we are almost ready to print! (We also notice the loss of
21183 information: many of the higher ranges are 0, meaning that fewer than
21184 50 defuns had that many words or symbols---but not necessarily meaning
21185 that none had that many words or symbols.)
21186
21187 @node Another Bug
21188 @appendixsubsec Another Bug @dots{} Most Insidious
21189 @cindex Bug, most insidious type
21190 @cindex Insidious type of bug
21191
21192 I said `almost ready to print'! Of course, there is a bug in the
21193 @code{print-graph} function @dots{} It has a @code{vertical-step}
21194 option, but not a @code{horizontal-step} option. The
21195 @code{top-of-range} scale goes from 10 to 300 by tens. But the
21196 @code{print-graph} function will print only by ones.
21197
21198 This is a classic example of what some consider the most insidious
21199 type of bug, the bug of omission. This is not the kind of bug you can
21200 find by studying the code, for it is not in the code; it is an omitted
21201 feature. Your best actions are to try your program early and often;
21202 and try to arrange, as much as you can, to write code that is easy to
21203 understand and easy to change. Try to be aware, whenever you can,
21204 that whatever you have written, @emph{will} be rewritten, if not soon,
21205 eventually. A hard maxim to follow.
21206
21207 It is the @code{print-X-axis-numbered-line} function that needs the
21208 work; and then the @code{print-X-axis} and the @code{print-graph}
21209 functions need to be adapted. Not much needs to be done; there is one
21210 nicety: the numbers ought to line up under the tic marks. This takes
21211 a little thought.
21212
21213 @need 1250
21214 Here is the corrected @code{print-X-axis-numbered-line}:
21215
21216 @smallexample
21217 @group
21218 (defun print-X-axis-numbered-line
21219 (number-of-X-tics X-axis-leading-spaces
21220 &optional horizontal-step)
21221 "Print line of X-axis numbers"
21222 (let ((number X-axis-label-spacing)
21223 (horizontal-step (or horizontal-step 1)))
21224 @end group
21225 @group
21226 (insert X-axis-leading-spaces)
21227 ;; @r{Delete extra leading spaces.}
21228 (delete-char
21229 (- (1-
21230 (length (number-to-string horizontal-step)))))
21231 (insert (concat
21232 (make-string
21233 @end group
21234 @group
21235 ;; @r{Insert white space.}
21236 (- (* symbol-width
21237 X-axis-label-spacing)
21238 (1-
21239 (length
21240 (number-to-string horizontal-step)))
21241 2)
21242 ? )
21243 (number-to-string
21244 (* number horizontal-step))))
21245 @end group
21246 @group
21247 ;; @r{Insert remaining numbers.}
21248 (setq number (+ number X-axis-label-spacing))
21249 (while (> number-of-X-tics 1)
21250 (insert (X-axis-element
21251 (* number horizontal-step)))
21252 (setq number (+ number X-axis-label-spacing))
21253 (setq number-of-X-tics (1- number-of-X-tics)))))
21254 @end group
21255 @end smallexample
21256
21257 @need 1500
21258 If you are reading this in Info, you can see the new versions of
21259 @code{print-X-axis} @code{print-graph} and evaluate them. If you are
21260 reading this in a printed book, you can see the changed lines here
21261 (the full text is too much to print).
21262
21263 @iftex
21264 @smallexample
21265 @group
21266 (defun print-X-axis (numbers-list horizontal-step)
21267 @dots{}
21268 (print-X-axis-numbered-line
21269 tic-number leading-spaces horizontal-step))
21270 @end group
21271 @end smallexample
21272
21273 @smallexample
21274 @group
21275 (defun print-graph
21276 (numbers-list
21277 &optional vertical-step horizontal-step)
21278 @dots{}
21279 (print-X-axis numbers-list horizontal-step))
21280 @end group
21281 @end smallexample
21282 @end iftex
21283
21284 @ifnottex
21285 @smallexample
21286 @group
21287 (defun print-X-axis (numbers-list horizontal-step)
21288 "Print X axis labels to length of NUMBERS-LIST.
21289 Optionally, HORIZONTAL-STEP, a positive integer,
21290 specifies how much an X axis label increments for
21291 each column."
21292 @end group
21293 @group
21294 ;; Value of symbol-width and full-Y-label-width
21295 ;; are passed by `print-graph'.
21296 (let* ((leading-spaces
21297 (make-string full-Y-label-width ? ))
21298 ;; symbol-width @r{is provided by} graph-body-print
21299 (tic-width (* symbol-width X-axis-label-spacing))
21300 (X-length (length numbers-list))
21301 @end group
21302 @group
21303 (X-tic
21304 (concat
21305 (make-string
21306 ;; @r{Make a string of blanks.}
21307 (- (* symbol-width X-axis-label-spacing)
21308 (length X-axis-tic-symbol))
21309 ? )
21310 @end group
21311 @group
21312 ;; @r{Concatenate blanks with tic symbol.}
21313 X-axis-tic-symbol))
21314 (tic-number
21315 (if (zerop (% X-length tic-width))
21316 (/ X-length tic-width)
21317 (1+ (/ X-length tic-width)))))
21318 @end group
21319
21320 @group
21321 (print-X-axis-tic-line
21322 tic-number leading-spaces X-tic)
21323 (insert "\n")
21324 (print-X-axis-numbered-line
21325 tic-number leading-spaces horizontal-step)))
21326 @end group
21327 @end smallexample
21328
21329 @smallexample
21330 @group
21331 (defun print-graph
21332 (numbers-list &optional vertical-step horizontal-step)
21333 "Print labeled bar graph of the NUMBERS-LIST.
21334 The numbers-list consists of the Y-axis values.
21335 @end group
21336
21337 @group
21338 Optionally, VERTICAL-STEP, a positive integer,
21339 specifies how much a Y axis label increments for
21340 each line. For example, a step of 5 means that
21341 each row is five units.
21342 @end group
21343
21344 @group
21345 Optionally, HORIZONTAL-STEP, a positive integer,
21346 specifies how much an X axis label increments for
21347 each column."
21348 (let* ((symbol-width (length graph-blank))
21349 ;; @code{height} @r{is both the largest number}
21350 ;; @r{and the number with the most digits.}
21351 (height (apply 'max numbers-list))
21352 @end group
21353 @group
21354 (height-of-top-line
21355 (if (zerop (% height Y-axis-label-spacing))
21356 height
21357 ;; @r{else}
21358 (* (1+ (/ height Y-axis-label-spacing))
21359 Y-axis-label-spacing)))
21360 @end group
21361 @group
21362 (vertical-step (or vertical-step 1))
21363 (full-Y-label-width
21364 (length
21365 (concat
21366 (number-to-string
21367 (* height-of-top-line vertical-step))
21368 Y-axis-tic))))
21369 @end group
21370 @group
21371 (print-Y-axis
21372 height-of-top-line full-Y-label-width vertical-step)
21373 (graph-body-print
21374 numbers-list height-of-top-line symbol-width)
21375 (print-X-axis numbers-list horizontal-step)))
21376 @end group
21377 @end smallexample
21378 @end ifnottex
21379
21380 @c qqq
21381 @ignore
21382 Graphing Definitions Re-listed
21383
21384 @need 1250
21385 Here are all the graphing definitions in their final form:
21386
21387 @smallexample
21388 @group
21389 (defvar top-of-ranges
21390 '(10 20 30 40 50
21391 60 70 80 90 100
21392 110 120 130 140 150
21393 160 170 180 190 200
21394 210 220 230 240 250)
21395 "List specifying ranges for `defuns-per-range'.")
21396 @end group
21397
21398 @group
21399 (defvar graph-symbol "*"
21400 "String used as symbol in graph, usually an asterisk.")
21401 @end group
21402
21403 @group
21404 (defvar graph-blank " "
21405 "String used as blank in graph, usually a blank space.
21406 graph-blank must be the same number of columns wide
21407 as graph-symbol.")
21408 @end group
21409
21410 @group
21411 (defvar Y-axis-tic " - "
21412 "String that follows number in a Y axis label.")
21413 @end group
21414
21415 @group
21416 (defvar Y-axis-label-spacing 5
21417 "Number of lines from one Y axis label to next.")
21418 @end group
21419
21420 @group
21421 (defvar X-axis-tic-symbol "|"
21422 "String to insert to point to a column in X axis.")
21423 @end group
21424
21425 @group
21426 (defvar X-axis-label-spacing
21427 (if (boundp 'graph-blank)
21428 (* 5 (length graph-blank)) 5)
21429 "Number of units from one X axis label to next.")
21430 @end group
21431 @end smallexample
21432
21433 @smallexample
21434 @group
21435 (defun count-words-in-defun ()
21436 "Return the number of words and symbols in a defun."
21437 (beginning-of-defun)
21438 (let ((count 0)
21439 (end (save-excursion (end-of-defun) (point))))
21440 @end group
21441
21442 @group
21443 (while
21444 (and (< (point) end)
21445 (re-search-forward
21446 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
21447 end t))
21448 (setq count (1+ count)))
21449 count))
21450 @end group
21451 @end smallexample
21452
21453 @smallexample
21454 @group
21455 (defun lengths-list-file (filename)
21456 "Return list of definitions' lengths within FILE.
21457 The returned list is a list of numbers.
21458 Each number is the number of words or
21459 symbols in one function definition."
21460 @end group
21461
21462 @group
21463 (message "Working on `%s' ... " filename)
21464 (save-excursion
21465 (let ((buffer (find-file-noselect filename))
21466 (lengths-list))
21467 (set-buffer buffer)
21468 (setq buffer-read-only t)
21469 (widen)
21470 (goto-char (point-min))
21471 @end group
21472
21473 @group
21474 (while (re-search-forward "^(defun" nil t)
21475 (setq lengths-list
21476 (cons (count-words-in-defun) lengths-list)))
21477 (kill-buffer buffer)
21478 lengths-list)))
21479 @end group
21480 @end smallexample
21481
21482 @smallexample
21483 @group
21484 (defun lengths-list-many-files (list-of-files)
21485 "Return list of lengths of defuns in LIST-OF-FILES."
21486 (let (lengths-list)
21487 ;;; @r{true-or-false-test}
21488 (while list-of-files
21489 (setq lengths-list
21490 (append
21491 lengths-list
21492 @end group
21493 @group
21494 ;;; @r{Generate a lengths' list.}
21495 (lengths-list-file
21496 (expand-file-name (car list-of-files)))))
21497 ;;; @r{Make files' list shorter.}
21498 (setq list-of-files (cdr list-of-files)))
21499 ;;; @r{Return final value of lengths' list.}
21500 lengths-list))
21501 @end group
21502 @end smallexample
21503
21504 @smallexample
21505 @group
21506 (defun defuns-per-range (sorted-lengths top-of-ranges)
21507 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
21508 (let ((top-of-range (car top-of-ranges))
21509 (number-within-range 0)
21510 defuns-per-range-list)
21511 @end group
21512
21513 @group
21514 ;; @r{Outer loop.}
21515 (while top-of-ranges
21516
21517 ;; @r{Inner loop.}
21518 (while (and
21519 ;; @r{Need number for numeric test.}
21520 (car sorted-lengths)
21521 (< (car sorted-lengths) top-of-range))
21522
21523 ;; @r{Count number of definitions within current range.}
21524 (setq number-within-range (1+ number-within-range))
21525 (setq sorted-lengths (cdr sorted-lengths)))
21526 @end group
21527
21528 @group
21529 ;; @r{Exit inner loop but remain within outer loop.}
21530
21531 (setq defuns-per-range-list
21532 (cons number-within-range defuns-per-range-list))
21533 (setq number-within-range 0) ; @r{Reset count to zero.}
21534
21535 ;; @r{Move to next range.}
21536 (setq top-of-ranges (cdr top-of-ranges))
21537 ;; @r{Specify next top of range value.}
21538 (setq top-of-range (car top-of-ranges)))
21539 @end group
21540
21541 @group
21542 ;; @r{Exit outer loop and count the number of defuns larger than}
21543 ;; @r{ the largest top-of-range value.}
21544 (setq defuns-per-range-list
21545 (cons
21546 (length sorted-lengths)
21547 defuns-per-range-list))
21548
21549 ;; @r{Return a list of the number of definitions within each range,}
21550 ;; @r{ smallest to largest.}
21551 (nreverse defuns-per-range-list)))
21552 @end group
21553 @end smallexample
21554
21555 @smallexample
21556 @group
21557 (defun column-of-graph (max-graph-height actual-height)
21558 "Return list of MAX-GRAPH-HEIGHT strings;
21559 ACTUAL-HEIGHT are graph-symbols.
21560 The graph-symbols are contiguous entries at the end
21561 of the list.
21562 The list will be inserted as one column of a graph.
21563 The strings are either graph-blank or graph-symbol."
21564 @end group
21565
21566 @group
21567 (let ((insert-list nil)
21568 (number-of-top-blanks
21569 (- max-graph-height actual-height)))
21570
21571 ;; @r{Fill in @code{graph-symbols}.}
21572 (while (> actual-height 0)
21573 (setq insert-list (cons graph-symbol insert-list))
21574 (setq actual-height (1- actual-height)))
21575 @end group
21576
21577 @group
21578 ;; @r{Fill in @code{graph-blanks}.}
21579 (while (> number-of-top-blanks 0)
21580 (setq insert-list (cons graph-blank insert-list))
21581 (setq number-of-top-blanks
21582 (1- number-of-top-blanks)))
21583
21584 ;; @r{Return whole list.}
21585 insert-list))
21586 @end group
21587 @end smallexample
21588
21589 @smallexample
21590 @group
21591 (defun Y-axis-element (number full-Y-label-width)
21592 "Construct a NUMBERed label element.
21593 A numbered element looks like this ` 5 - ',
21594 and is padded as needed so all line up with
21595 the element for the largest number."
21596 @end group
21597 @group
21598 (let* ((leading-spaces
21599 (- full-Y-label-width
21600 (length
21601 (concat (number-to-string number)
21602 Y-axis-tic)))))
21603 @end group
21604 @group
21605 (concat
21606 (make-string leading-spaces ? )
21607 (number-to-string number)
21608 Y-axis-tic)))
21609 @end group
21610 @end smallexample
21611
21612 @smallexample
21613 @group
21614 (defun print-Y-axis
21615 (height full-Y-label-width &optional vertical-step)
21616 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
21617 Height must be the maximum height of the graph.
21618 Full width is the width of the highest label element.
21619 Optionally, print according to VERTICAL-STEP."
21620 @end group
21621 @group
21622 ;; Value of height and full-Y-label-width
21623 ;; are passed by `print-graph'.
21624 (let ((start (point)))
21625 (insert-rectangle
21626 (Y-axis-column height full-Y-label-width vertical-step))
21627 @end group
21628 @group
21629 ;; @r{Place point ready for inserting graph.}
21630 (goto-char start)
21631 ;; @r{Move point forward by value of} full-Y-label-width
21632 (forward-char full-Y-label-width)))
21633 @end group
21634 @end smallexample
21635
21636 @smallexample
21637 @group
21638 (defun print-X-axis-tic-line
21639 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
21640 "Print ticks for X axis."
21641 (insert X-axis-leading-spaces)
21642 (insert X-axis-tic-symbol) ; @r{Under first column.}
21643 @end group
21644 @group
21645 ;; @r{Insert second tic in the right spot.}
21646 (insert (concat
21647 (make-string
21648 (- (* symbol-width X-axis-label-spacing)
21649 ;; @r{Insert white space up to second tic symbol.}
21650 (* 2 (length X-axis-tic-symbol)))
21651 ? )
21652 X-axis-tic-symbol))
21653 @end group
21654 @group
21655 ;; @r{Insert remaining ticks.}
21656 (while (> number-of-X-tics 1)
21657 (insert X-axis-tic-element)
21658 (setq number-of-X-tics (1- number-of-X-tics))))
21659 @end group
21660 @end smallexample
21661
21662 @smallexample
21663 @group
21664 (defun X-axis-element (number)
21665 "Construct a numbered X axis element."
21666 (let ((leading-spaces
21667 (- (* symbol-width X-axis-label-spacing)
21668 (length (number-to-string number)))))
21669 (concat (make-string leading-spaces ? )
21670 (number-to-string number))))
21671 @end group
21672 @end smallexample
21673
21674 @smallexample
21675 @group
21676 (defun graph-body-print (numbers-list height symbol-width)
21677 "Print a bar graph of the NUMBERS-LIST.
21678 The numbers-list consists of the Y-axis values.
21679 HEIGHT is maximum height of graph.
21680 SYMBOL-WIDTH is number of each column."
21681 @end group
21682 @group
21683 (let (from-position)
21684 (while numbers-list
21685 (setq from-position (point))
21686 (insert-rectangle
21687 (column-of-graph height (car numbers-list)))
21688 (goto-char from-position)
21689 (forward-char symbol-width)
21690 @end group
21691 @group
21692 ;; @r{Draw graph column by column.}
21693 (sit-for 0)
21694 (setq numbers-list (cdr numbers-list)))
21695 ;; @r{Place point for X axis labels.}
21696 (forward-line height)
21697 (insert "\n")))
21698 @end group
21699 @end smallexample
21700
21701 @smallexample
21702 @group
21703 (defun Y-axis-column
21704 (height width-of-label &optional vertical-step)
21705 "Construct list of labels for Y axis.
21706 HEIGHT is maximum height of graph.
21707 WIDTH-OF-LABEL is maximum width of label.
21708 @end group
21709 @group
21710 VERTICAL-STEP, an option, is a positive integer
21711 that specifies how much a Y axis label increments
21712 for each line. For example, a step of 5 means
21713 that each line is five units of the graph."
21714 (let (Y-axis
21715 (number-per-line (or vertical-step 1)))
21716 @end group
21717 @group
21718 (while (> height 1)
21719 (if (zerop (% height Y-axis-label-spacing))
21720 ;; @r{Insert label.}
21721 (setq Y-axis
21722 (cons
21723 (Y-axis-element
21724 (* height number-per-line)
21725 width-of-label)
21726 Y-axis))
21727 @end group
21728 @group
21729 ;; @r{Else, insert blanks.}
21730 (setq Y-axis
21731 (cons
21732 (make-string width-of-label ? )
21733 Y-axis)))
21734 (setq height (1- height)))
21735 @end group
21736 @group
21737 ;; @r{Insert base line.}
21738 (setq Y-axis (cons (Y-axis-element
21739 (or vertical-step 1)
21740 width-of-label)
21741 Y-axis))
21742 (nreverse Y-axis)))
21743 @end group
21744 @end smallexample
21745
21746 @smallexample
21747 @group
21748 (defun print-X-axis-numbered-line
21749 (number-of-X-tics X-axis-leading-spaces
21750 &optional horizontal-step)
21751 "Print line of X-axis numbers"
21752 (let ((number X-axis-label-spacing)
21753 (horizontal-step (or horizontal-step 1)))
21754 @end group
21755 @group
21756 (insert X-axis-leading-spaces)
21757 ;; line up number
21758 (delete-char (- (1- (length (number-to-string horizontal-step)))))
21759 (insert (concat
21760 (make-string
21761 ;; @r{Insert white space up to next number.}
21762 (- (* symbol-width X-axis-label-spacing)
21763 (1- (length (number-to-string horizontal-step)))
21764 2)
21765 ? )
21766 (number-to-string (* number horizontal-step))))
21767 @end group
21768 @group
21769 ;; @r{Insert remaining numbers.}
21770 (setq number (+ number X-axis-label-spacing))
21771 (while (> number-of-X-tics 1)
21772 (insert (X-axis-element (* number horizontal-step)))
21773 (setq number (+ number X-axis-label-spacing))
21774 (setq number-of-X-tics (1- number-of-X-tics)))))
21775 @end group
21776 @end smallexample
21777
21778 @smallexample
21779 @group
21780 (defun print-X-axis (numbers-list horizontal-step)
21781 "Print X axis labels to length of NUMBERS-LIST.
21782 Optionally, HORIZONTAL-STEP, a positive integer,
21783 specifies how much an X axis label increments for
21784 each column."
21785 @end group
21786 @group
21787 ;; Value of symbol-width and full-Y-label-width
21788 ;; are passed by `print-graph'.
21789 (let* ((leading-spaces
21790 (make-string full-Y-label-width ? ))
21791 ;; symbol-width @r{is provided by} graph-body-print
21792 (tic-width (* symbol-width X-axis-label-spacing))
21793 (X-length (length numbers-list))
21794 @end group
21795 @group
21796 (X-tic
21797 (concat
21798 (make-string
21799 ;; @r{Make a string of blanks.}
21800 (- (* symbol-width X-axis-label-spacing)
21801 (length X-axis-tic-symbol))
21802 ? )
21803 @end group
21804 @group
21805 ;; @r{Concatenate blanks with tic symbol.}
21806 X-axis-tic-symbol))
21807 (tic-number
21808 (if (zerop (% X-length tic-width))
21809 (/ X-length tic-width)
21810 (1+ (/ X-length tic-width)))))
21811 @end group
21812
21813 @group
21814 (print-X-axis-tic-line
21815 tic-number leading-spaces X-tic)
21816 (insert "\n")
21817 (print-X-axis-numbered-line
21818 tic-number leading-spaces horizontal-step)))
21819 @end group
21820 @end smallexample
21821
21822 @smallexample
21823 @group
21824 (defun one-fiftieth (full-range)
21825 "Return list, each number of which is 1/50th previous."
21826 (mapcar (lambda (arg) (/ arg 50)) full-range))
21827 @end group
21828 @end smallexample
21829
21830 @smallexample
21831 @group
21832 (defun print-graph
21833 (numbers-list &optional vertical-step horizontal-step)
21834 "Print labeled bar graph of the NUMBERS-LIST.
21835 The numbers-list consists of the Y-axis values.
21836 @end group
21837
21838 @group
21839 Optionally, VERTICAL-STEP, a positive integer,
21840 specifies how much a Y axis label increments for
21841 each line. For example, a step of 5 means that
21842 each row is five units.
21843 @end group
21844
21845 @group
21846 Optionally, HORIZONTAL-STEP, a positive integer,
21847 specifies how much an X axis label increments for
21848 each column."
21849 (let* ((symbol-width (length graph-blank))
21850 ;; @code{height} @r{is both the largest number}
21851 ;; @r{and the number with the most digits.}
21852 (height (apply 'max numbers-list))
21853 @end group
21854 @group
21855 (height-of-top-line
21856 (if (zerop (% height Y-axis-label-spacing))
21857 height
21858 ;; @r{else}
21859 (* (1+ (/ height Y-axis-label-spacing))
21860 Y-axis-label-spacing)))
21861 @end group
21862 @group
21863 (vertical-step (or vertical-step 1))
21864 (full-Y-label-width
21865 (length
21866 (concat
21867 (number-to-string
21868 (* height-of-top-line vertical-step))
21869 Y-axis-tic))))
21870 @end group
21871 @group
21872
21873 (print-Y-axis
21874 height-of-top-line full-Y-label-width vertical-step)
21875 (graph-body-print
21876 numbers-list height-of-top-line symbol-width)
21877 (print-X-axis numbers-list horizontal-step)))
21878 @end group
21879 @end smallexample
21880 @c qqq
21881 @end ignore
21882
21883 @page
21884 @node Final printed graph
21885 @appendixsubsec The Printed Graph
21886
21887 When made and installed, you can call the @code{print-graph} command
21888 like this:
21889 @sp 1
21890
21891 @smallexample
21892 @group
21893 (print-graph fiftieth-list-for-graph 50 10)
21894 @end group
21895 @end smallexample
21896 @sp 1
21897
21898 @noindent
21899 Here is the graph:
21900 @sp 2
21901
21902 @smallexample
21903 @group
21904 1000 - *
21905 **
21906 **
21907 **
21908 **
21909 750 - ***
21910 ***
21911 ***
21912 ***
21913 ****
21914 500 - *****
21915 ******
21916 ******
21917 ******
21918 *******
21919 250 - ********
21920 ********* *
21921 *********** *
21922 ************* *
21923 50 - ***************** * *
21924 | | | | | | | |
21925 10 50 100 150 200 250 300 350
21926 @end group
21927 @end smallexample
21928
21929 @sp 2
21930
21931 @noindent
21932 The largest group of functions contain 10--19 words and symbols each.
21933
21934 @node Free Software and Free Manuals
21935 @appendix Free Software and Free Manuals
21936
21937 @strong{by Richard M. Stallman}
21938 @sp 1
21939
21940 The biggest deficiency in free operating systems is not in the
21941 software---it is the lack of good free manuals that we can include in
21942 these systems. Many of our most important programs do not come with
21943 full manuals. Documentation is an essential part of any software
21944 package; when an important free software package does not come with a
21945 free manual, that is a major gap. We have many such gaps today.
21946
21947 Once upon a time, many years ago, I thought I would learn Perl. I got
21948 a copy of a free manual, but I found it hard to read. When I asked
21949 Perl users about alternatives, they told me that there were better
21950 introductory manuals---but those were not free.
21951
21952 Why was this? The authors of the good manuals had written them for
21953 O'Reilly Associates, which published them with restrictive terms---no
21954 copying, no modification, source files not available---which exclude
21955 them from the free software community.
21956
21957 That wasn't the first time this sort of thing has happened, and (to
21958 our community's great loss) it was far from the last. Proprietary
21959 manual publishers have enticed a great many authors to restrict their
21960 manuals since then. Many times I have heard a GNU user eagerly tell me
21961 about a manual that he is writing, with which he expects to help the
21962 GNU project---and then had my hopes dashed, as he proceeded to explain
21963 that he had signed a contract with a publisher that would restrict it
21964 so that we cannot use it.
21965
21966 Given that writing good English is a rare skill among programmers, we
21967 can ill afford to lose manuals this way.
21968
21969 Free documentation, like free software, is a matter of freedom, not
21970 price. The problem with these manuals was not that O'Reilly Associates
21971 charged a price for printed copies---that in itself is fine. The Free
21972 Software Foundation @uref{http://shop.fsf.org, sells printed copies} of
21973 free @uref{http://www.gnu.org/doc/doc.html, GNU manuals}, too.
21974 But GNU manuals are available in source code form, while these manuals
21975 are available only on paper. GNU manuals come with permission to copy
21976 and modify; the Perl manuals do not. These restrictions are the
21977 problems.
21978
21979 The criterion for a free manual is pretty much the same as for free
21980 software: it is a matter of giving all users certain
21981 freedoms. Redistribution (including commercial redistribution) must be
21982 permitted, so that the manual can accompany every copy of the program,
21983 on-line or on paper. Permission for modification is crucial too.
21984
21985 As a general rule, I don't believe that it is essential for people to
21986 have permission to modify all sorts of articles and books. The issues
21987 for writings are not necessarily the same as those for software. For
21988 example, I don't think you or I are obliged to give permission to
21989 modify articles like this one, which describe our actions and our
21990 views.
21991
21992 But there is a particular reason why the freedom to modify is crucial
21993 for documentation for free software. When people exercise their right
21994 to modify the software, and add or change its features, if they are
21995 conscientious they will change the manual too---so they can provide
21996 accurate and usable documentation with the modified program. A manual
21997 which forbids programmers to be conscientious and finish the job, or
21998 more precisely requires them to write a new manual from scratch if
21999 they change the program, does not fill our community's needs.
22000
22001 While a blanket prohibition on modification is unacceptable, some
22002 kinds of limits on the method of modification pose no problem. For
22003 example, requirements to preserve the original author's copyright
22004 notice, the distribution terms, or the list of authors, are ok. It is
22005 also no problem to require modified versions to include notice that
22006 they were modified, even to have entire sections that may not be
22007 deleted or changed, as long as these sections deal with nontechnical
22008 topics. (Some GNU manuals have them.)
22009
22010 These kinds of restrictions are not a problem because, as a practical
22011 matter, they don't stop the conscientious programmer from adapting the
22012 manual to fit the modified program. In other words, they don't block
22013 the free software community from making full use of the manual.
22014
22015 However, it must be possible to modify all the technical content of
22016 the manual, and then distribute the result in all the usual media,
22017 through all the usual channels; otherwise, the restrictions do block
22018 the community, the manual is not free, and so we need another manual.
22019
22020 Unfortunately, it is often hard to find someone to write another
22021 manual when a proprietary manual exists. The obstacle is that many
22022 users think that a proprietary manual is good enough---so they don't
22023 see the need to write a free manual. They do not see that the free
22024 operating system has a gap that needs filling.
22025
22026 Why do users think that proprietary manuals are good enough? Some have
22027 not considered the issue. I hope this article will do something to
22028 change that.
22029
22030 Other users consider proprietary manuals acceptable for the same
22031 reason so many people consider proprietary software acceptable: they
22032 judge in purely practical terms, not using freedom as a
22033 criterion. These people are entitled to their opinions, but since
22034 those opinions spring from values which do not include freedom, they
22035 are no guide for those of us who do value freedom.
22036
22037 Please spread the word about this issue. We continue to lose manuals
22038 to proprietary publishing. If we spread the word that proprietary
22039 manuals are not sufficient, perhaps the next person who wants to help
22040 GNU by writing documentation will realize, before it is too late, that
22041 he must above all make it free.
22042
22043 We can also encourage commercial publishers to sell free, copylefted
22044 manuals instead of proprietary ones. One way you can help this is to
22045 check the distribution terms of a manual before you buy it, and prefer
22046 copylefted manuals to non-copylefted ones.
22047
22048 @sp 2
22049 @noindent
22050 Note: The Free Software Foundation maintains a page on its Web site
22051 that lists free books available from other publishers:@*
22052 @uref{http://www.gnu.org/doc/other-free-books.html}
22053
22054 @node GNU Free Documentation License
22055 @appendix GNU Free Documentation License
22056
22057 @cindex FDL, GNU Free Documentation License
22058 @include doclicense.texi
22059
22060 @node Index
22061 @unnumbered Index
22062
22063 @ignore
22064 MENU ENTRY: NODE NAME.
22065 @end ignore
22066
22067 @printindex cp
22068
22069 @iftex
22070 @c Place biographical information on right-hand (verso) page
22071
22072 @tex
22073 \par\vfill\supereject
22074 \ifodd\pageno
22075 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22076 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
22077 %\page\hbox{}\page
22078 \else
22079 % \par\vfill\supereject
22080 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22081 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
22082 %\page\hbox{}%\page
22083 %\page\hbox{}%\page
22084 \fi
22085 @end tex
22086
22087 @c page
22088 @w{ }
22089
22090 @c ================ Biographical information ================
22091
22092 @w{ }
22093 @sp 8
22094 @center About the Author
22095 @sp 1
22096 @end iftex
22097
22098 @ifnottex
22099 @node About the Author
22100 @unnumbered About the Author
22101 @end ifnottex
22102
22103 @quotation
22104 Robert J. Chassell has worked with GNU Emacs since 1985. He writes
22105 and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
22106 world on software freedom. Chassell was a founding Director and
22107 Treasurer of the Free Software Foundation, Inc. He is co-author of
22108 the @cite{Texinfo} manual, and has edited more than a dozen other
22109 books. He graduated from Cambridge University, in England. He has an
22110 abiding interest in social and economic history and flies his own
22111 airplane.
22112 @end quotation
22113
22114 @c @page
22115 @c @w{ }
22116 @c
22117 @c @c Prevent page number on blank verso, so eject it first.
22118 @c @tex
22119 @c \par\vfill\supereject
22120 @c @end tex
22121
22122 @c @iftex
22123 @c @headings off
22124 @c @evenheading @thispage @| @| @thistitle
22125 @c @oddheading @| @| @thispage
22126 @c @end iftex
22127
22128 @bye