]> code.delx.au - gnu-emacs/blob - doc/lispintro/emacs-lisp-intro.texi
Merge from emacs-24; up to 2012-05-08T15:19:18Z!monnier@iro.umontreal.ca
[gnu-emacs] / doc / lispintro / emacs-lisp-intro.texi
1 \input texinfo @c -*-texinfo-*-
2 @comment %**start of header
3 @setfilename ../../info/eintr
4 @c setfilename emacs-lisp-intro.info
5 @c sethtmlfilename emacs-lisp-intro.html
6 @settitle Programming in Emacs Lisp
7 @syncodeindex vr cp
8 @syncodeindex fn cp
9 @finalout
10
11 @c ---------
12 @c <<<< For hard copy printing, this file is now
13 @c set for smallbook, which works for all sizes
14 @c of paper, and with PostScript figures >>>>
15 @set smallbook
16 @ifset smallbook
17 @smallbook
18 @clear largebook
19 @end ifset
20 @set print-postscript-figures
21 @c set largebook
22 @c clear print-postscript-figures
23 @c ---------
24
25 @comment %**end of header
26
27 @c per rms and peterb, use 10pt fonts for the main text, mostly to
28 @c save on paper cost.
29 @c Do this inside @tex for now, so current makeinfo does not complain.
30 @tex
31 @ifset smallbook
32 @fonttextsize 10
33
34 @end ifset
35 \global\hbadness=6666 % don't worry about not-too-underfull boxes
36 @end tex
37
38 @set edition-number 3.10
39 @set update-date 28 October 2009
40
41 @ignore
42 ## Summary of shell commands to create various output formats:
43
44 pushd /usr/local/src/emacs/lispintro/
45 ## pushd /u/intro/
46
47 ## Info output
48 makeinfo --paragraph-indent=0 --verbose emacs-lisp-intro.texi
49
50 ## ;; (progn (when (bufferp (get-buffer "*info*")) (kill-buffer "*info*")) (info "/usr/local/src/emacs/info/eintr"))
51
52 ## DVI output
53 texi2dvi emacs-lisp-intro.texi
54
55 ## xdvi -margins 24pt -topmargin 4pt -offsets 24pt -geometry 760x1140 -s 5 -useTeXpages -mousemode 1 emacs-lisp-intro.dvi &
56
57 ## HTML output
58 makeinfo --html --no-split --verbose emacs-lisp-intro.texi
59
60 ## galeon emacs-lisp-intro.html
61
62 ## Plain text output
63 makeinfo --fill-column=70 --no-split --paragraph-indent=0 \
64 --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi
65
66 popd
67
68 # as user `root'
69 # insert thumbdrive
70 mtusb # mount -v -t ext3 /dev/sda /mnt
71 cp -v /u/intro/emacs-lisp-intro.texi /mnt/backup/intro/emacs-lisp-intro.texi
72 umtusb # umount -v /mnt
73 # remove thumbdrive
74
75 ## Other shell commands
76
77 pushd /usr/local/src/emacs/lispintro/
78 ## pushd /u/intro/
79
80 ## PDF
81 texi2dvi --pdf emacs-lisp-intro.texi
82 # xpdf emacs-lisp-intro.pdf &
83
84 ## DocBook -- note file extension
85 makeinfo --docbook --no-split --paragraph-indent=0 \
86 --verbose --output=emacs-lisp-intro.docbook emacs-lisp-intro.texi
87
88 ## XML with a Texinfo DTD -- note file extension
89 makeinfo --xml --no-split --paragraph-indent=0 \
90 --verbose --output=emacs-lisp-intro.texinfoxml emacs-lisp-intro.texi
91
92 ## PostScript (needs DVI)
93 # gv emacs-lisp-intro.ps &
94 # Create DVI if we lack it
95 # texi2dvi emacs-lisp-intro.texi
96 dvips emacs-lisp-intro.dvi -o emacs-lisp-intro.ps
97
98 ## RTF (needs HTML)
99 # Use OpenOffice to view RTF
100 # Create HTML if we lack it
101 # makeinfo --no-split --html emacs-lisp-intro.texi
102 /usr/local/src/html2rtf.pl emacs-lisp-intro.html
103
104 ## LaTeX (needs RTF)
105 /usr/bin/rtf2latex emacs-lisp-intro.rtf
106
107 popd
108
109 @end ignore
110
111 @c ================ Included Figures ================
112
113 @c Set print-postscript-figures if you print PostScript figures.
114 @c If you clear this, the ten figures will be printed as ASCII diagrams.
115 @c (This is not relevant to Info, since Info only handles ASCII.)
116 @c Your site may require editing changes to print PostScript; in this
117 @c case, search for `print-postscript-figures' and make appropriate changes.
118
119 @c ================ How to Create an Info file ================
120
121 @c If you have `makeinfo' installed, run the following command
122
123 @c makeinfo emacs-lisp-intro.texi
124
125 @c or, if you want a single, large Info file, and no paragraph indents:
126 @c makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
127
128 @c After creating the Info file, edit your Info `dir' file, if the
129 @c `dircategory' section below does not enable your system to
130 @c install the manual automatically.
131 @c (The `dir' file is often in the `/usr/local/share/info/' directory.)
132
133 @c ================ How to Create an HTML file ================
134
135 @c To convert to HTML format
136 @c makeinfo --html --no-split --verbose emacs-lisp-intro.texi
137
138 @c ================ How to Print a Book in Various Sizes ================
139
140 @c This book can be printed in any of three different sizes.
141 @c In the above header, set @-commands appropriately.
142
143 @c 7 by 9.25 inches:
144 @c @smallbook
145 @c @clear largebook
146
147 @c 8.5 by 11 inches:
148 @c @c smallbook
149 @c @set largebook
150
151 @c European A4 size paper:
152 @c @c smallbook
153 @c @afourpaper
154 @c @set largebook
155
156 @c ================ How to Typeset and Print ================
157
158 @c If you do not include PostScript figures, run either of the
159 @c following command sequences, or similar commands suited to your
160 @c system:
161
162 @c texi2dvi emacs-lisp-intro.texi
163 @c lpr -d emacs-lisp-intro.dvi
164
165 @c or else:
166
167 @c tex emacs-lisp-intro.texi
168 @c texindex emacs-lisp-intro.??
169 @c tex emacs-lisp-intro.texi
170 @c lpr -d emacs-lisp-intro.dvi
171
172 @c If you include the PostScript figures, and you have old software,
173 @c you may need to convert the .dvi file to a .ps file before
174 @c printing. Run either of the following command sequences, or one
175 @c similar:
176 @c
177 @c dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
178 @c
179 @c or else:
180 @c
181 @c postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
182 @c
183
184 @c (Note: if you edit the book so as to change the length of the
185 @c table of contents, you may have to change the value of `pageno' below.)
186
187 @c ================ End of Formatting Sections ================
188
189 @c For next or subsequent edition:
190 @c create function using with-output-to-temp-buffer
191 @c create a major mode, with keymaps
192 @c run an asynchronous process, like grep or diff
193
194 @c For 8.5 by 11 inch format: do not use such a small amount of
195 @c whitespace between paragraphs as smallbook format
196 @ifset largebook
197 @tex
198 \global\parskip 6pt plus 1pt
199 @end tex
200 @end ifset
201
202 @c For all sized formats: print within-book cross
203 @c reference with ``...'' rather than [...]
204
205 @c This works with the texinfo.tex file, version 2003-05-04.08,
206 @c in the Texinfo version 4.6 of the 2003 Jun 13 distribution.
207
208 @tex
209 \if \xrefprintnodename
210 \global\def\xrefprintnodename#1{\unskip, ``#1''}
211 \else
212 \global\def\xrefprintnodename#1{ ``#1''}
213 \fi
214 % \global\def\xrefprintnodename#1{, ``#1''}
215 @end tex
216
217 @c ----------------------------------------------------
218
219 @dircategory GNU Emacs Lisp
220 @direntry
221 * Emacs Lisp Intro: (eintr).
222 A simple introduction to Emacs Lisp programming.
223 @end direntry
224
225 @copying
226 This is an @cite{Introduction to Programming in Emacs Lisp}, for
227 people who are not programmers.
228 @sp 1
229 Edition @value{edition-number}, @value{update-date}
230 @sp 1
231 Copyright @copyright{} 1990-1995, 1997, 2001-2012 Free Software Foundation, Inc.
232 @sp 1
233
234 @iftex
235 Published by the:@*
236
237 GNU Press, @hfill @uref{http://www.fsf.org/campaigns/gnu-press/}@*
238 a division of the @hfill email: @email{sales@@fsf.org}@*
239 Free Software Foundation, Inc. @hfill Tel: +1 (617) 542-5942@*
240 51 Franklin Street, Fifth Floor @hfill Fax: +1 (617) 542-2652@*
241 Boston, MA 02110-1301 USA
242 @end iftex
243
244 @ifnottex
245 Published by the:
246
247 @example
248 GNU Press, http://www.fsf.org/campaigns/gnu-press/
249 a division of the email: sales@@fsf.org
250 Free Software Foundation, Inc. Tel: +1 (617) 542-5942
251 51 Franklin Street, Fifth Floor Fax: +1 (617) 542-2652
252 Boston, MA 02110-1301 USA
253 @end example
254 @end ifnottex
255
256 @sp 1
257 @c Printed copies are available from @uref{http://shop.fsf.org/} for $35 each.@*
258 ISBN 1-882114-43-4
259
260 Permission is granted to copy, distribute and/or modify this document
261 under the terms of the GNU Free Documentation License, Version 1.3 or
262 any later version published by the Free Software Foundation; there
263 being no Invariant Section, with the Front-Cover Texts being ``A GNU
264 Manual'', and with the Back-Cover Texts as in (a) below. A copy of
265 the license is included in the section entitled ``GNU Free
266 Documentation License''.
267
268 (a) The FSF's Back-Cover Text is: ``You have the freedom to
269 copy and modify this GNU manual. Buying copies from the FSF
270 supports it in developing GNU and promoting software freedom.''
271 @end copying
272
273 @c half title; two lines here, so do not use `shorttitlepage'
274 @tex
275 {\begingroup%
276 \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
277 \endgroup}%
278 {\begingroup\hbox{}\vskip 0.25in \chaprm%
279 \centerline{Programming in Emacs Lisp}%
280 \endgroup\page\hbox{}\page}
281 @end tex
282
283 @titlepage
284 @sp 6
285 @center @titlefont{An Introduction to}
286 @sp 2
287 @center @titlefont{Programming in Emacs Lisp}
288 @sp 2
289 @center Revised Third Edition
290 @sp 4
291 @center by Robert J. Chassell
292
293 @page
294 @vskip 0pt plus 1filll
295 @insertcopying
296 @end titlepage
297
298 @iftex
299 @headings off
300 @evenheading @thispage @| @| @thischapter
301 @oddheading @thissection @| @| @thispage
302 @end iftex
303
304 @ifnothtml
305 @c Keep T.O.C. short by tightening up for largebook
306 @ifset largebook
307 @tex
308 \global\parskip 2pt plus 1pt
309 \global\advance\baselineskip by -1pt
310 @end tex
311 @end ifset
312 @end ifnothtml
313
314 @shortcontents
315 @contents
316
317 @ifnottex
318 @node Top
319 @top An Introduction to Programming in Emacs Lisp
320
321 @insertcopying
322
323 This master menu first lists each chapter and index; then it lists
324 every node in every chapter.
325 @end ifnottex
326
327 @c >>>> Set pageno appropriately <<<<
328
329 @c The first page of the Preface is a roman numeral; it is the first
330 @c right handed page after the Table of Contents; hence the following
331 @c setting must be for an odd negative number.
332
333 @c iftex
334 @c global@pageno = -11
335 @c end iftex
336
337 @set COUNT-WORDS count-words-example
338 @c Length of variable name chosen so that things still line up when expanded.
339
340 @menu
341 * Preface:: What to look for.
342 * List Processing:: What is Lisp?
343 * Practicing Evaluation:: Running several programs.
344 * Writing Defuns:: How to write function definitions.
345 * Buffer Walk Through:: Exploring a few buffer-related functions.
346 * More Complex:: A few, even more complex functions.
347 * Narrowing & Widening:: Restricting your and Emacs attention to
348 a region.
349 * car cdr & cons:: Fundamental functions in Lisp.
350 * Cutting & Storing Text:: Removing text and saving it.
351 * List Implementation:: How lists are implemented in the computer.
352 * Yanking:: Pasting stored text.
353 * Loops & Recursion:: How to repeat a process.
354 * Regexp Search:: Regular expression searches.
355 * Counting Words:: A review of repetition and regexps.
356 * Words in a defun:: Counting words in a @code{defun}.
357 * Readying a Graph:: A prototype graph printing function.
358 * Emacs Initialization:: How to write a @file{.emacs} file.
359 * Debugging:: How to run the Emacs Lisp debuggers.
360 * Conclusion:: Now you have the basics.
361 * the-the:: An appendix: how to find reduplicated words.
362 * Kill Ring:: An appendix: how the kill ring works.
363 * Full Graph:: How to create a graph with labeled axes.
364 * Free Software and Free Manuals::
365 * GNU Free Documentation License::
366 * Index::
367 * About the Author::
368
369 @detailmenu
370 --- The Detailed Node Listing ---
371
372 Preface
373
374 * Why:: Why learn Emacs Lisp?
375 * On Reading this Text:: Read, gain familiarity, pick up habits....
376 * Who You Are:: For whom this is written.
377 * Lisp History::
378 * Note for Novices:: You can read this as a novice.
379 * Thank You::
380
381 List Processing
382
383 * Lisp Lists:: What are lists?
384 * Run a Program:: Any list in Lisp is a program ready to run.
385 * Making Errors:: Generating an error message.
386 * Names & Definitions:: Names of symbols and function definitions.
387 * Lisp Interpreter:: What the Lisp interpreter does.
388 * Evaluation:: Running a program.
389 * Variables:: Returning a value from a variable.
390 * Arguments:: Passing information to a function.
391 * set & setq:: Setting the value of a variable.
392 * Summary:: The major points.
393 * Error Message Exercises::
394
395 Lisp Lists
396
397 * Numbers Lists:: List have numbers, other lists, in them.
398 * Lisp Atoms:: Elemental entities.
399 * Whitespace in Lists:: Formatting lists to be readable.
400 * Typing Lists:: How GNU Emacs helps you type lists.
401
402 The Lisp Interpreter
403
404 * Complications:: Variables, Special forms, Lists within.
405 * Byte Compiling:: Specially processing code for speed.
406
407 Evaluation
408
409 * How the Interpreter Acts:: Returns and Side Effects...
410 * Evaluating Inner Lists:: Lists within lists...
411
412 Variables
413
414 * fill-column Example::
415 * Void Function:: The error message for a symbol
416 without a function.
417 * Void Variable:: The error message for a symbol without a value.
418
419 Arguments
420
421 * Data types:: Types of data passed to a function.
422 * Args as Variable or List:: An argument can be the value
423 of a variable or list.
424 * Variable Number of Arguments:: Some functions may take a
425 variable number of arguments.
426 * Wrong Type of Argument:: Passing an argument of the wrong type
427 to a function.
428 * message:: A useful function for sending messages.
429
430 Setting the Value of a Variable
431
432 * Using set:: Setting values.
433 * Using setq:: Setting a quoted value.
434 * Counting:: Using @code{setq} to count.
435
436 Practicing Evaluation
437
438 * How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
439 causes evaluation.
440 * Buffer Names:: Buffers and files are different.
441 * Getting Buffers:: Getting a buffer itself, not merely its name.
442 * Switching Buffers:: How to change to another buffer.
443 * Buffer Size & Locations:: Where point is located and the size of
444 the buffer.
445 * Evaluation Exercise::
446
447 How To Write Function Definitions
448
449 * Primitive Functions::
450 * defun:: The @code{defun} special form.
451 * Install:: Install a function definition.
452 * Interactive:: Making a function interactive.
453 * Interactive Options:: Different options for @code{interactive}.
454 * Permanent Installation:: Installing code permanently.
455 * let:: Creating and initializing local variables.
456 * if:: What if?
457 * else:: If--then--else expressions.
458 * Truth & Falsehood:: What Lisp considers false and true.
459 * save-excursion:: Keeping track of point, mark, and buffer.
460 * Review::
461 * defun Exercises::
462
463 Install a Function Definition
464
465 * Effect of installation::
466 * Change a defun:: How to change a function definition.
467
468 Make a Function Interactive
469
470 * Interactive multiply-by-seven:: An overview.
471 * multiply-by-seven in detail:: The interactive version.
472
473 @code{let}
474
475 * Prevent confusion::
476 * Parts of let Expression::
477 * Sample let Expression::
478 * Uninitialized let Variables::
479
480 The @code{if} Special Form
481
482 * if in more detail::
483 * type-of-animal in detail:: An example of an @code{if} expression.
484
485 Truth and Falsehood in Emacs Lisp
486
487 * nil explained:: @code{nil} has two meanings.
488
489 @code{save-excursion}
490
491 * Point and mark:: A review of various locations.
492 * Template for save-excursion::
493
494 A Few Buffer--Related Functions
495
496 * Finding More:: How to find more information.
497 * simplified-beginning-of-buffer:: Shows @code{goto-char},
498 @code{point-min}, and @code{push-mark}.
499 * mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
500 * append-to-buffer:: Uses @code{save-excursion} and
501 @code{insert-buffer-substring}.
502 * Buffer Related Review:: Review.
503 * Buffer Exercises::
504
505 The Definition of @code{mark-whole-buffer}
506
507 * mark-whole-buffer overview::
508 * Body of mark-whole-buffer:: Only three lines of code.
509
510 The Definition of @code{append-to-buffer}
511
512 * append-to-buffer overview::
513 * append interactive:: A two part interactive expression.
514 * append-to-buffer body:: Incorporates a @code{let} expression.
515 * append save-excursion:: How the @code{save-excursion} works.
516
517 A Few More Complex Functions
518
519 * copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
520 * insert-buffer:: Read-only, and with @code{or}.
521 * beginning-of-buffer:: Shows @code{goto-char},
522 @code{point-min}, and @code{push-mark}.
523 * Second Buffer Related Review::
524 * optional Exercise::
525
526 The Definition of @code{insert-buffer}
527
528 * insert-buffer code::
529 * insert-buffer interactive:: When you can read, but not write.
530 * insert-buffer body:: The body has an @code{or} and a @code{let}.
531 * if & or:: Using an @code{if} instead of an @code{or}.
532 * Insert or:: How the @code{or} expression works.
533 * Insert let:: Two @code{save-excursion} expressions.
534 * New insert-buffer::
535
536 The Interactive Expression in @code{insert-buffer}
537
538 * Read-only buffer:: When a buffer cannot be modified.
539 * b for interactive:: An existing buffer or else its name.
540
541 Complete Definition of @code{beginning-of-buffer}
542
543 * Optional Arguments::
544 * beginning-of-buffer opt arg:: Example with optional argument.
545 * beginning-of-buffer complete::
546
547 @code{beginning-of-buffer} with an Argument
548
549 * Disentangle beginning-of-buffer::
550 * Large buffer case::
551 * Small buffer case::
552
553 Narrowing and Widening
554
555 * Narrowing advantages:: The advantages of narrowing
556 * save-restriction:: The @code{save-restriction} special form.
557 * what-line:: The number of the line that point is on.
558 * narrow Exercise::
559
560 @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
561
562 * Strange Names:: An historical aside: why the strange names?
563 * car & cdr:: Functions for extracting part of a list.
564 * cons:: Constructing a list.
565 * nthcdr:: Calling @code{cdr} repeatedly.
566 * nth::
567 * setcar:: Changing the first element of a list.
568 * setcdr:: Changing the rest of a list.
569 * cons Exercise::
570
571 @code{cons}
572
573 * Build a list::
574 * length:: How to find the length of a list.
575
576 Cutting and Storing Text
577
578 * Storing Text:: Text is stored in a list.
579 * zap-to-char:: Cutting out text up to a character.
580 * kill-region:: Cutting text out of a region.
581 * copy-region-as-kill:: A definition for copying text.
582 * Digression into C:: Minor note on C programming language macros.
583 * defvar:: How to give a variable an initial value.
584 * cons & search-fwd Review::
585 * search Exercises::
586
587 @code{zap-to-char}
588
589 * Complete zap-to-char:: The complete implementation.
590 * zap-to-char interactive:: A three part interactive expression.
591 * zap-to-char body:: A short overview.
592 * search-forward:: How to search for a string.
593 * progn:: The @code{progn} special form.
594 * Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
595
596 @code{kill-region}
597
598 * Complete kill-region:: The function definition.
599 * condition-case:: Dealing with a problem.
600 * Lisp macro::
601
602 @code{copy-region-as-kill}
603
604 * Complete copy-region-as-kill:: The complete function definition.
605 * copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
606
607 The Body of @code{copy-region-as-kill}
608
609 * last-command & this-command::
610 * kill-append function::
611 * kill-new function::
612
613 Initializing a Variable with @code{defvar}
614
615 * See variable current value::
616 * defvar and asterisk::
617
618 How Lists are Implemented
619
620 * Lists diagrammed::
621 * Symbols as Chest:: Exploring a powerful metaphor.
622 * List Exercise::
623
624 Yanking Text Back
625
626 * Kill Ring Overview::
627 * kill-ring-yank-pointer:: The kill ring is a list.
628 * yank nthcdr Exercises:: The @code{kill-ring-yank-pointer} variable.
629
630 Loops and Recursion
631
632 * while:: Causing a stretch of code to repeat.
633 * dolist dotimes::
634 * Recursion:: Causing a function to call itself.
635 * Looping exercise::
636
637 @code{while}
638
639 * Looping with while:: Repeat so long as test returns true.
640 * Loop Example:: A @code{while} loop that uses a list.
641 * print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
642 * Incrementing Loop:: A loop with an incrementing counter.
643 * Incrementing Loop Details::
644 * Decrementing Loop:: A loop with a decrementing counter.
645
646 Details of an Incrementing Loop
647
648 * Incrementing Example:: Counting pebbles in a triangle.
649 * Inc Example parts:: The parts of the function definition.
650 * Inc Example altogether:: Putting the function definition together.
651
652 Loop with a Decrementing Counter
653
654 * Decrementing Example:: More pebbles on the beach.
655 * Dec Example parts:: The parts of the function definition.
656 * Dec Example altogether:: Putting the function definition together.
657
658 Save your time: @code{dolist} and @code{dotimes}
659
660 * dolist::
661 * dotimes::
662
663 Recursion
664
665 * Building Robots:: Same model, different serial number ...
666 * Recursive Definition Parts:: Walk until you stop ...
667 * Recursion with list:: Using a list as the test whether to recurse.
668 * Recursive triangle function::
669 * Recursion with cond::
670 * Recursive Patterns:: Often used templates.
671 * No Deferment:: Don't store up work ...
672 * No deferment solution::
673
674 Recursion in Place of a Counter
675
676 * Recursive Example arg of 1 or 2::
677 * Recursive Example arg of 3 or 4::
678
679 Recursive Patterns
680
681 * Every::
682 * Accumulate::
683 * Keep::
684
685 Regular Expression Searches
686
687 * sentence-end:: The regular expression for @code{sentence-end}.
688 * re-search-forward:: Very similar to @code{search-forward}.
689 * forward-sentence:: A straightforward example of regexp search.
690 * forward-paragraph:: A somewhat complex example.
691 * etags:: How to create your own @file{TAGS} table.
692 * Regexp Review::
693 * re-search Exercises::
694
695 @code{forward-sentence}
696
697 * Complete forward-sentence::
698 * fwd-sentence while loops:: Two @code{while} loops.
699 * fwd-sentence re-search:: A regular expression search.
700
701 @code{forward-paragraph}: a Goldmine of Functions
702
703 * forward-paragraph in brief:: Key parts of the function definition.
704 * fwd-para let:: The @code{let*} expression.
705 * fwd-para while:: The forward motion @code{while} loop.
706
707 Counting: Repetition and Regexps
708
709 * Why Count Words::
710 * @value{COUNT-WORDS}:: Use a regexp, but find a problem.
711 * recursive-count-words:: Start with case of no words in region.
712 * Counting Exercise::
713
714 The @code{@value{COUNT-WORDS}} Function
715
716 * Design @value{COUNT-WORDS}:: The definition using a @code{while} loop.
717 * Whitespace Bug:: The Whitespace Bug in @code{@value{COUNT-WORDS}}.
718
719 Counting Words in a @code{defun}
720
721 * Divide and Conquer::
722 * Words and Symbols:: What to count?
723 * Syntax:: What constitutes a word or symbol?
724 * count-words-in-defun:: Very like @code{@value{COUNT-WORDS}}.
725 * Several defuns:: Counting several defuns in a file.
726 * Find a File:: Do you want to look at a file?
727 * lengths-list-file:: A list of the lengths of many definitions.
728 * Several files:: Counting in definitions in different files.
729 * Several files recursively:: Recursively counting in different files.
730 * Prepare the data:: Prepare the data for display in a graph.
731
732 Count Words in @code{defuns} in Different Files
733
734 * lengths-list-many-files:: Return a list of the lengths of defuns.
735 * append:: Attach one list to another.
736
737 Prepare the Data for Display in a Graph
738
739 * Data for Display in Detail::
740 * Sorting:: Sorting lists.
741 * Files List:: Making a list of files.
742 * Counting function definitions::
743
744 Readying a Graph
745
746 * Columns of a graph::
747 * graph-body-print:: How to print the body of a graph.
748 * recursive-graph-body-print::
749 * Printed Axes::
750 * Line Graph Exercise::
751
752 Your @file{.emacs} File
753
754 * Default Configuration::
755 * Site-wide Init:: You can write site-wide init files.
756 * defcustom:: Emacs will write code for you.
757 * Beginning a .emacs File:: How to write a @code{.emacs file}.
758 * Text and Auto-fill:: Automatically wrap lines.
759 * Mail Aliases:: Use abbreviations for email addresses.
760 * Indent Tabs Mode:: Don't use tabs with @TeX{}
761 * Keybindings:: Create some personal keybindings.
762 * Keymaps:: More about key binding.
763 * Loading Files:: Load (i.e., evaluate) files automatically.
764 * Autoload:: Make functions available.
765 * Simple Extension:: Define a function; bind it to a key.
766 * X11 Colors:: Colors in X.
767 * Miscellaneous::
768 * Mode Line:: How to customize your mode line.
769
770 Debugging
771
772 * debug:: How to use the built-in debugger.
773 * debug-on-entry:: Start debugging when you call a function.
774 * debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
775 * edebug:: How to use Edebug, a source level debugger.
776 * Debugging Exercises::
777
778 Handling the Kill Ring
779
780 * What the Kill Ring Does::
781 * current-kill::
782 * yank:: Paste a copy of a clipped element.
783 * yank-pop:: Insert element pointed to.
784 * ring file::
785
786 The @code{current-kill} Function
787
788 * Code for current-kill::
789 * Understanding current-kill::
790
791 @code{current-kill} in Outline
792
793 * Body of current-kill::
794 * Digression concerning error:: How to mislead humans, but not computers.
795 * Determining the Element::
796
797 A Graph with Labeled Axes
798
799 * Labeled Example::
800 * print-graph Varlist:: @code{let} expression in @code{print-graph}.
801 * print-Y-axis:: Print a label for the vertical axis.
802 * print-X-axis:: Print a horizontal label.
803 * Print Whole Graph:: The function to print a complete graph.
804
805 The @code{print-Y-axis} Function
806
807 * print-Y-axis in Detail::
808 * Height of label:: What height for the Y axis?
809 * Compute a Remainder:: How to compute the remainder of a division.
810 * Y Axis Element:: Construct a line for the Y axis.
811 * Y-axis-column:: Generate a list of Y axis labels.
812 * print-Y-axis Penultimate:: A not quite final version.
813
814 The @code{print-X-axis} Function
815
816 * Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
817 * X Axis Tic Marks:: Create tic marks for the horizontal axis.
818
819 Printing the Whole Graph
820
821 * The final version:: A few changes.
822 * Test print-graph:: Run a short test.
823 * Graphing words in defuns:: Executing the final code.
824 * lambda:: How to write an anonymous function.
825 * mapcar:: Apply a function to elements of a list.
826 * Another Bug:: Yet another bug @dots{} most insidious.
827 * Final printed graph:: The graph itself!
828
829 @end detailmenu
830 @end menu
831
832 @node Preface
833 @unnumbered Preface
834
835 Most of the GNU Emacs integrated environment is written in the programming
836 language called Emacs Lisp. The code written in this programming
837 language is the software---the sets of instructions---that tell the
838 computer what to do when you give it commands. Emacs is designed so
839 that you can write new code in Emacs Lisp and easily install it as an
840 extension to the editor.
841
842 (GNU Emacs is sometimes called an ``extensible editor'', but it does
843 much more than provide editing capabilities. It is better to refer to
844 Emacs as an ``extensible computing environment''. However, that
845 phrase is quite a mouthful. It is easier to refer to Emacs simply as
846 an editor. Moreover, everything you do in Emacs---find the Mayan date
847 and phases of the moon, simplify polynomials, debug code, manage
848 files, read letters, write books---all these activities are kinds of
849 editing in the most general sense of the word.)
850
851 @menu
852 * Why:: Why learn Emacs Lisp?
853 * On Reading this Text:: Read, gain familiarity, pick up habits....
854 * Who You Are:: For whom this is written.
855 * Lisp History::
856 * Note for Novices:: You can read this as a novice.
857 * Thank You::
858 @end menu
859
860 @ifnottex
861 @node Why
862 @unnumberedsec Why Study Emacs Lisp?
863 @end ifnottex
864
865 Although Emacs Lisp is usually thought of in association only with Emacs,
866 it is a full computer programming language. You can use Emacs Lisp as
867 you would any other programming language.
868
869 Perhaps you want to understand programming; perhaps you want to extend
870 Emacs; or perhaps you want to become a programmer. This introduction to
871 Emacs Lisp is designed to get you started: to guide you in learning the
872 fundamentals of programming, and more importantly, to show you how you
873 can teach yourself to go further.
874
875 @node On Reading this Text
876 @unnumberedsec On Reading this Text
877
878 All through this document, you will see little sample programs you can
879 run inside of Emacs. If you read this document in Info inside of GNU
880 Emacs, you can run the programs as they appear. (This is easy to do and
881 is explained when the examples are presented.) Alternatively, you can
882 read this introduction as a printed book while sitting beside a computer
883 running Emacs. (This is what I like to do; I like printed books.) If
884 you don't have a running Emacs beside you, you can still read this book,
885 but in this case, it is best to treat it as a novel or as a travel guide
886 to a country not yet visited: interesting, but not the same as being
887 there.
888
889 Much of this introduction is dedicated to walkthroughs or guided tours
890 of code used in GNU Emacs. These tours are designed for two purposes:
891 first, to give you familiarity with real, working code (code you use
892 every day); and, second, to give you familiarity with the way Emacs
893 works. It is interesting to see how a working environment is
894 implemented.
895 Also, I
896 hope that you will pick up the habit of browsing through source code.
897 You can learn from it and mine it for ideas. Having GNU Emacs is like
898 having a dragon's cave of treasures.
899
900 In addition to learning about Emacs as an editor and Emacs Lisp as a
901 programming language, the examples and guided tours will give you an
902 opportunity to get acquainted with Emacs as a Lisp programming
903 environment. GNU Emacs supports programming and provides tools that
904 you will want to become comfortable using, such as @kbd{M-.} (the key
905 which invokes the @code{find-tag} command). You will also learn about
906 buffers and other objects that are part of the environment.
907 Learning about these features of Emacs is like learning new routes
908 around your home town.
909
910 @ignore
911 In addition, I have written several programs as extended examples.
912 Although these are examples, the programs are real. I use them.
913 Other people use them. You may use them. Beyond the fragments of
914 programs used for illustrations, there is very little in here that is
915 `just for teaching purposes'; what you see is used. This is a great
916 advantage of Emacs Lisp: it is easy to learn to use it for work.
917 @end ignore
918
919 Finally, I hope to convey some of the skills for using Emacs to
920 learn aspects of programming that you don't know. You can often use
921 Emacs to help you understand what puzzles you or to find out how to do
922 something new. This self-reliance is not only a pleasure, but an
923 advantage.
924
925 @node Who You Are
926 @unnumberedsec For Whom This is Written
927
928 This text is written as an elementary introduction for people who are
929 not programmers. If you are a programmer, you may not be satisfied with
930 this primer. The reason is that you may have become expert at reading
931 reference manuals and be put off by the way this text is organized.
932
933 An expert programmer who reviewed this text said to me:
934
935 @quotation
936 @i{I prefer to learn from reference manuals. I ``dive into'' each
937 paragraph, and ``come up for air'' between paragraphs.}
938
939 @i{When I get to the end of a paragraph, I assume that that subject is
940 done, finished, that I know everything I need (with the
941 possible exception of the case when the next paragraph starts talking
942 about it in more detail). I expect that a well written reference manual
943 will not have a lot of redundancy, and that it will have excellent
944 pointers to the (one) place where the information I want is.}
945 @end quotation
946
947 This introduction is not written for this person!
948
949 Firstly, I try to say everything at least three times: first, to
950 introduce it; second, to show it in context; and third, to show it in a
951 different context, or to review it.
952
953 Secondly, I hardly ever put all the information about a subject in one
954 place, much less in one paragraph. To my way of thinking, that imposes
955 too heavy a burden on the reader. Instead I try to explain only what
956 you need to know at the time. (Sometimes I include a little extra
957 information so you won't be surprised later when the additional
958 information is formally introduced.)
959
960 When you read this text, you are not expected to learn everything the
961 first time. Frequently, you need only make, as it were, a `nodding
962 acquaintance' with some of the items mentioned. My hope is that I have
963 structured the text and given you enough hints that you will be alert to
964 what is important, and concentrate on it.
965
966 You will need to ``dive into'' some paragraphs; there is no other way
967 to read them. But I have tried to keep down the number of such
968 paragraphs. This book is intended as an approachable hill, rather than
969 as a daunting mountain.
970
971 This introduction to @cite{Programming in Emacs Lisp} has a companion
972 document,
973 @iftex
974 @cite{The GNU Emacs Lisp Reference Manual}.
975 @end iftex
976 @ifnottex
977 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
978 Emacs Lisp Reference Manual}.
979 @end ifnottex
980 The reference manual has more detail than this introduction. In the
981 reference manual, all the information about one topic is concentrated
982 in one place. You should turn to it if you are like the programmer
983 quoted above. And, of course, after you have read this
984 @cite{Introduction}, you will find the @cite{Reference Manual} useful
985 when you are writing your own programs.
986
987 @node Lisp History
988 @unnumberedsec Lisp History
989 @cindex Lisp history
990
991 Lisp was first developed in the late 1950s at the Massachusetts
992 Institute of Technology for research in artificial intelligence. The
993 great power of the Lisp language makes it superior for other purposes as
994 well, such as writing editor commands and integrated environments.
995
996 @cindex Maclisp
997 @cindex Common Lisp
998 GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
999 in the 1960s. It is somewhat inspired by Common Lisp, which became a
1000 standard in the 1980s. However, Emacs Lisp is much simpler than Common
1001 Lisp. (The standard Emacs distribution contains an optional extensions
1002 file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1003
1004 @node Note for Novices
1005 @unnumberedsec A Note for Novices
1006
1007 If you don't know GNU Emacs, you can still read this document
1008 profitably. However, I recommend you learn Emacs, if only to learn to
1009 move around your computer screen. You can teach yourself how to use
1010 Emacs with the on-line tutorial. To use it, type @kbd{C-h t}. (This
1011 means you press and release the @key{CTRL} key and the @kbd{h} at the
1012 same time, and then press and release @kbd{t}.)
1013
1014 Also, I often refer to one of Emacs's standard commands by listing the
1015 keys which you press to invoke the command and then giving the name of
1016 the command in parentheses, like this: @kbd{M-C-\}
1017 (@code{indent-region}). What this means is that the
1018 @code{indent-region} command is customarily invoked by typing
1019 @kbd{M-C-\}. (You can, if you wish, change the keys that are typed to
1020 invoke the command; this is called @dfn{rebinding}. @xref{Keymaps, ,
1021 Keymaps}.) The abbreviation @kbd{M-C-\} means that you type your
1022 @key{META} key, @key{CTRL} key and @key{\} key all at the same time.
1023 (On many modern keyboards the @key{META} key is labeled
1024 @key{ALT}.)
1025 Sometimes a combination like this is called a keychord, since it is
1026 similar to the way you play a chord on a piano. If your keyboard does
1027 not have a @key{META} key, the @key{ESC} key prefix is used in place
1028 of it. In this case, @kbd{M-C-\} means that you press and release your
1029 @key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1030 the same time. But usually @kbd{M-C-\} means press the @key{CTRL} key
1031 along with the key that is labeled @key{ALT} and, at the same time,
1032 press the @key{\} key.
1033
1034 In addition to typing a lone keychord, you can prefix what you type
1035 with @kbd{C-u}, which is called the `universal argument'. The
1036 @kbd{C-u} keychord passes an argument to the subsequent command.
1037 Thus, to indent a region of plain text by 6 spaces, mark the region,
1038 and then type @w{@kbd{C-u 6 M-C-\}}. (If you do not specify a number,
1039 Emacs either passes the number 4 to the command or otherwise runs the
1040 command differently than it would otherwise.) @xref{Arguments, ,
1041 Numeric Arguments, emacs, The GNU Emacs Manual}.
1042
1043 If you are reading this in Info using GNU Emacs, you can read through
1044 this whole document just by pressing the space bar, @key{SPC}.
1045 (To learn about Info, type @kbd{C-h i} and then select Info.)
1046
1047 A note on terminology: when I use the word Lisp alone, I often am
1048 referring to the various dialects of Lisp in general, but when I speak
1049 of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1050
1051 @node Thank You
1052 @unnumberedsec Thank You
1053
1054 My thanks to all who helped me with this book. My especial thanks to
1055 @r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1056 McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
1057 Stallman}, and @w{Melissa Weisshaus}. My thanks also go to both
1058 @w{Philip Johnson} and @w{David Stampe} for their patient
1059 encouragement. My mistakes are my own.
1060
1061 @flushright
1062 Robert J. Chassell
1063 @email{bob@@gnu.org}
1064 @end flushright
1065
1066 @c ================ Beginning of main text ================
1067
1068 @c Start main text on right-hand (verso) page
1069
1070 @tex
1071 \par\vfill\supereject
1072 \headings off
1073 \ifodd\pageno
1074 \par\vfill\supereject
1075 \else
1076 \par\vfill\supereject
1077 \page\hbox{}\page
1078 \par\vfill\supereject
1079 \fi
1080 @end tex
1081
1082 @c Note: this resetting of the page number back to 1 causes TeX to gripe
1083 @c about already having seen page numbers 1-4 before (in the preface):
1084 @c pdfTeX warning (ext4): destination with the same identifier (name{1})
1085 @c has been already used, duplicate ignored
1086 @c I guess that is harmless (what happens if a later part of the text
1087 @c makes a link to something in the first 4 pages though?).
1088 @c Note that eg the Emacs manual has a preface, but does not bother
1089 @c resetting the page numbers back to 1 after that.
1090 @iftex
1091 @headings off
1092 @evenheading @thispage @| @| @thischapter
1093 @oddheading @thissection @| @| @thispage
1094 @global@pageno = 1
1095 @end iftex
1096
1097 @node List Processing
1098 @chapter List Processing
1099
1100 To the untutored eye, Lisp is a strange programming language. In Lisp
1101 code there are parentheses everywhere. Some people even claim that
1102 the name stands for `Lots of Isolated Silly Parentheses'. But the
1103 claim is unwarranted. Lisp stands for LISt Processing, and the
1104 programming language handles @emph{lists} (and lists of lists) by
1105 putting them between parentheses. The parentheses mark the boundaries
1106 of the list. Sometimes a list is preceded by a single apostrophe or
1107 quotation mark, @samp{'}@footnote{The single apostrophe or quotation
1108 mark is an abbreviation for the function @code{quote}; you need not
1109 think about functions now; functions are defined in @ref{Making
1110 Errors, , Generate an Error Message}.} Lists are the basis of Lisp.
1111
1112 @menu
1113 * Lisp Lists:: What are lists?
1114 * Run a Program:: Any list in Lisp is a program ready to run.
1115 * Making Errors:: Generating an error message.
1116 * Names & Definitions:: Names of symbols and function definitions.
1117 * Lisp Interpreter:: What the Lisp interpreter does.
1118 * Evaluation:: Running a program.
1119 * Variables:: Returning a value from a variable.
1120 * Arguments:: Passing information to a function.
1121 * set & setq:: Setting the value of a variable.
1122 * Summary:: The major points.
1123 * Error Message Exercises::
1124 @end menu
1125
1126 @node Lisp Lists
1127 @section Lisp Lists
1128 @cindex Lisp Lists
1129
1130 In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1131 This list is preceded by a single apostrophe. It could just as well be
1132 written as follows, which looks more like the kind of list you are likely
1133 to be familiar with:
1134
1135 @smallexample
1136 @group
1137 '(rose
1138 violet
1139 daisy
1140 buttercup)
1141 @end group
1142 @end smallexample
1143
1144 @noindent
1145 The elements of this list are the names of the four different flowers,
1146 separated from each other by whitespace and surrounded by parentheses,
1147 like flowers in a field with a stone wall around them.
1148 @cindex Flowers in a field
1149
1150 @menu
1151 * Numbers Lists:: List have numbers, other lists, in them.
1152 * Lisp Atoms:: Elemental entities.
1153 * Whitespace in Lists:: Formatting lists to be readable.
1154 * Typing Lists:: How GNU Emacs helps you type lists.
1155 @end menu
1156
1157 @ifnottex
1158 @node Numbers Lists
1159 @unnumberedsubsec Numbers, Lists inside of Lists
1160 @end ifnottex
1161
1162 Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1163 This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1164 separated by whitespace.
1165
1166 In Lisp, both data and programs are represented the same way; that is,
1167 they are both lists of words, numbers, or other lists, separated by
1168 whitespace and surrounded by parentheses. (Since a program looks like
1169 data, one program may easily serve as data for another; this is a very
1170 powerful feature of Lisp.) (Incidentally, these two parenthetical
1171 remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1172 @samp{.} as punctuation marks.)
1173
1174 @need 1200
1175 Here is another list, this time with a list inside of it:
1176
1177 @smallexample
1178 '(this list has (a list inside of it))
1179 @end smallexample
1180
1181 The components of this list are the words @samp{this}, @samp{list},
1182 @samp{has}, and the list @samp{(a list inside of it)}. The interior
1183 list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1184 @samp{of}, @samp{it}.
1185
1186 @node Lisp Atoms
1187 @subsection Lisp Atoms
1188 @cindex Lisp Atoms
1189
1190 In Lisp, what we have been calling words are called @dfn{atoms}. This
1191 term comes from the historical meaning of the word atom, which means
1192 `indivisible'. As far as Lisp is concerned, the words we have been
1193 using in the lists cannot be divided into any smaller parts and still
1194 mean the same thing as part of a program; likewise with numbers and
1195 single character symbols like @samp{+}. On the other hand, unlike an
1196 ancient atom, a list can be split into parts. (@xref{car cdr & cons,
1197 , @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1198
1199 In a list, atoms are separated from each other by whitespace. They can be
1200 right next to a parenthesis.
1201
1202 @cindex @samp{empty list} defined
1203 Technically speaking, a list in Lisp consists of parentheses surrounding
1204 atoms separated by whitespace or surrounding other lists or surrounding
1205 both atoms and other lists. A list can have just one atom in it or
1206 have nothing in it at all. A list with nothing in it looks like this:
1207 @code{()}, and is called the @dfn{empty list}. Unlike anything else, an
1208 empty list is considered both an atom and a list at the same time.
1209
1210 @cindex Symbolic expressions, introduced
1211 @cindex @samp{expression} defined
1212 @cindex @samp{form} defined
1213 The printed representation of both atoms and lists are called
1214 @dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1215 The word @dfn{expression} by itself can refer to either the printed
1216 representation, or to the atom or list as it is held internally in the
1217 computer. Often, people use the term @dfn{expression}
1218 indiscriminately. (Also, in many texts, the word @dfn{form} is used
1219 as a synonym for expression.)
1220
1221 Incidentally, the atoms that make up our universe were named such when
1222 they were thought to be indivisible; but it has been found that physical
1223 atoms are not indivisible. Parts can split off an atom or it can
1224 fission into two parts of roughly equal size. Physical atoms were named
1225 prematurely, before their truer nature was found. In Lisp, certain
1226 kinds of atom, such as an array, can be separated into parts; but the
1227 mechanism for doing this is different from the mechanism for splitting a
1228 list. As far as list operations are concerned, the atoms of a list are
1229 unsplittable.
1230
1231 As in English, the meanings of the component letters of a Lisp atom
1232 are different from the meaning the letters make as a word. For
1233 example, the word for the South American sloth, the @samp{ai}, is
1234 completely different from the two words, @samp{a}, and @samp{i}.
1235
1236 There are many kinds of atom in nature but only a few in Lisp: for
1237 example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1238 as @samp{+}, @samp{foo}, or @samp{forward-line}. The words we have
1239 listed in the examples above are all symbols. In everyday Lisp
1240 conversation, the word ``atom'' is not often used, because programmers
1241 usually try to be more specific about what kind of atom they are dealing
1242 with. Lisp programming is mostly about symbols (and sometimes numbers)
1243 within lists. (Incidentally, the preceding three word parenthetical
1244 remark is a proper list in Lisp, since it consists of atoms, which in
1245 this case are symbols, separated by whitespace and enclosed by
1246 parentheses, without any non-Lisp punctuation.)
1247
1248 @need 1250
1249 Text between double quotation marks---even sentences or
1250 paragraphs---is also an atom. Here is an example:
1251 @cindex Text between double quotation marks
1252
1253 @smallexample
1254 '(this list includes "text between quotation marks.")
1255 @end smallexample
1256
1257 @cindex @samp{string} defined
1258 @noindent
1259 In Lisp, all of the quoted text including the punctuation mark and the
1260 blank spaces is a single atom. This kind of atom is called a
1261 @dfn{string} (for `string of characters') and is the sort of thing that
1262 is used for messages that a computer can print for a human to read.
1263 Strings are a different kind of atom than numbers or symbols and are
1264 used differently.
1265
1266 @node Whitespace in Lists
1267 @subsection Whitespace in Lists
1268 @cindex Whitespace in lists
1269
1270 @need 1200
1271 The amount of whitespace in a list does not matter. From the point of view
1272 of the Lisp language,
1273
1274 @smallexample
1275 @group
1276 '(this list
1277 looks like this)
1278 @end group
1279 @end smallexample
1280
1281 @need 800
1282 @noindent
1283 is exactly the same as this:
1284
1285 @smallexample
1286 '(this list looks like this)
1287 @end smallexample
1288
1289 Both examples show what to Lisp is the same list, the list made up of
1290 the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1291 @samp{this} in that order.
1292
1293 Extra whitespace and newlines are designed to make a list more readable
1294 by humans. When Lisp reads the expression, it gets rid of all the extra
1295 whitespace (but it needs to have at least one space between atoms in
1296 order to tell them apart.)
1297
1298 Odd as it seems, the examples we have seen cover almost all of what Lisp
1299 lists look like! Every other list in Lisp looks more or less like one
1300 of these examples, except that the list may be longer and more complex.
1301 In brief, a list is between parentheses, a string is between quotation
1302 marks, a symbol looks like a word, and a number looks like a number.
1303 (For certain situations, square brackets, dots and a few other special
1304 characters may be used; however, we will go quite far without them.)
1305
1306 @node Typing Lists
1307 @subsection GNU Emacs Helps You Type Lists
1308 @cindex Help typing lists
1309 @cindex Formatting help
1310
1311 When you type a Lisp expression in GNU Emacs using either Lisp
1312 Interaction mode or Emacs Lisp mode, you have available to you several
1313 commands to format the Lisp expression so it is easy to read. For
1314 example, pressing the @key{TAB} key automatically indents the line the
1315 cursor is on by the right amount. A command to properly indent the
1316 code in a region is customarily bound to @kbd{M-C-\}. Indentation is
1317 designed so that you can see which elements of a list belong to which
1318 list---elements of a sub-list are indented more than the elements of
1319 the enclosing list.
1320
1321 In addition, when you type a closing parenthesis, Emacs momentarily
1322 jumps the cursor back to the matching opening parenthesis, so you can
1323 see which one it is. This is very useful, since every list you type
1324 in Lisp must have its closing parenthesis match its opening
1325 parenthesis. (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1326 Manual}, for more information about Emacs's modes.)
1327
1328 @node Run a Program
1329 @section Run a Program
1330 @cindex Run a program
1331 @cindex Program, running one
1332
1333 @cindex @samp{evaluate} defined
1334 A list in Lisp---any list---is a program ready to run. If you run it
1335 (for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1336 of three things: do nothing except return to you the list itself; send
1337 you an error message; or, treat the first symbol in the list as a
1338 command to do something. (Usually, of course, it is the last of these
1339 three things that you really want!)
1340
1341 @c use code for the single apostrophe, not samp.
1342 The single apostrophe, @code{'}, that I put in front of some of the
1343 example lists in preceding sections is called a @dfn{quote}; when it
1344 precedes a list, it tells Lisp to do nothing with the list, other than
1345 take it as it is written. But if there is no quote preceding a list,
1346 the first item of the list is special: it is a command for the computer
1347 to obey. (In Lisp, these commands are called @emph{functions}.) The list
1348 @code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1349 understands that the @code{+} is an instruction to do something with the
1350 rest of the list: add the numbers that follow.
1351
1352 @need 1250
1353 If you are reading this inside of GNU Emacs in Info, here is how you can
1354 evaluate such a list: place your cursor immediately after the right
1355 hand parenthesis of the following list and then type @kbd{C-x C-e}:
1356
1357 @smallexample
1358 (+ 2 2)
1359 @end smallexample
1360
1361 @c use code for the number four, not samp.
1362 @noindent
1363 You will see the number @code{4} appear in the echo area. (In the
1364 jargon, what you have just done is ``evaluate the list.'' The echo area
1365 is the line at the bottom of the screen that displays or ``echoes''
1366 text.) Now try the same thing with a quoted list: place the cursor
1367 right after the following list and type @kbd{C-x C-e}:
1368
1369 @smallexample
1370 '(this is a quoted list)
1371 @end smallexample
1372
1373 @noindent
1374 You will see @code{(this is a quoted list)} appear in the echo area.
1375
1376 @cindex Lisp interpreter, explained
1377 @cindex Interpreter, Lisp, explained
1378 In both cases, what you are doing is giving a command to the program
1379 inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1380 interpreter a command to evaluate the expression. The name of the Lisp
1381 interpreter comes from the word for the task done by a human who comes
1382 up with the meaning of an expression---who ``interprets'' it.
1383
1384 You can also evaluate an atom that is not part of a list---one that is
1385 not surrounded by parentheses; again, the Lisp interpreter translates
1386 from the humanly readable expression to the language of the computer.
1387 But before discussing this (@pxref{Variables}), we will discuss what the
1388 Lisp interpreter does when you make an error.
1389
1390 @node Making Errors
1391 @section Generate an Error Message
1392 @cindex Generate an error message
1393 @cindex Error message generation
1394
1395 Partly so you won't worry if you do it accidentally, we will now give
1396 a command to the Lisp interpreter that generates an error message.
1397 This is a harmless activity; and indeed, we will often try to generate
1398 error messages intentionally. Once you understand the jargon, error
1399 messages can be informative. Instead of being called ``error''
1400 messages, they should be called ``help'' messages. They are like
1401 signposts to a traveler in a strange country; deciphering them can be
1402 hard, but once understood, they can point the way.
1403
1404 The error message is generated by a built-in GNU Emacs debugger. We
1405 will `enter the debugger'. You get out of the debugger by typing @code{q}.
1406
1407 What we will do is evaluate a list that is not quoted and does not
1408 have a meaningful command as its first element. Here is a list almost
1409 exactly the same as the one we just used, but without the single-quote
1410 in front of it. Position the cursor right after it and type @kbd{C-x
1411 C-e}:
1412
1413 @smallexample
1414 (this is an unquoted list)
1415 @end smallexample
1416
1417 @ignore
1418 @noindent
1419 What you see depends on which version of Emacs you are running. GNU
1420 Emacs version 22 provides more information than version 20 and before.
1421 First, the more recent result of generating an error; then the
1422 earlier, version 20 result.
1423
1424 @need 1250
1425 @noindent
1426 In GNU Emacs version 22, a @file{*Backtrace*} window will open up and
1427 you will see the following in it:
1428 @end ignore
1429
1430 A @file{*Backtrace*} window will open up and you should see the
1431 following in it:
1432
1433 @smallexample
1434 @group
1435 ---------- Buffer: *Backtrace* ----------
1436 Debugger entered--Lisp error: (void-function this)
1437 (this is an unquoted list)
1438 eval((this is an unquoted list))
1439 eval-last-sexp-1(nil)
1440 eval-last-sexp(nil)
1441 call-interactively(eval-last-sexp)
1442 ---------- Buffer: *Backtrace* ----------
1443 @end group
1444 @end smallexample
1445
1446 @need 1200
1447 @noindent
1448 Your cursor will be in this window (you may have to wait a few seconds
1449 before it becomes visible). To quit the debugger and make the
1450 debugger window go away, type:
1451
1452 @smallexample
1453 q
1454 @end smallexample
1455
1456 @noindent
1457 Please type @kbd{q} right now, so you become confident that you can
1458 get out of the debugger. Then, type @kbd{C-x C-e} again to re-enter
1459 it.
1460
1461 @cindex @samp{function} defined
1462 Based on what we already know, we can almost read this error message.
1463
1464 You read the @file{*Backtrace*} buffer from the bottom up; it tells
1465 you what Emacs did. When you typed @kbd{C-x C-e}, you made an
1466 interactive call to the command @code{eval-last-sexp}. @code{eval} is
1467 an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1468 `symbolic expression'. The command means `evaluate last symbolic
1469 expression', which is the expression just before your cursor.
1470
1471 Each line above tells you what the Lisp interpreter evaluated next.
1472 The most recent action is at the top. The buffer is called the
1473 @file{*Backtrace*} buffer because it enables you to track Emacs
1474 backwards.
1475
1476 @need 800
1477 At the top of the @file{*Backtrace*} buffer, you see the line:
1478
1479 @smallexample
1480 Debugger entered--Lisp error: (void-function this)
1481 @end smallexample
1482
1483 @noindent
1484 The Lisp interpreter tried to evaluate the first atom of the list, the
1485 word @samp{this}. It is this action that generated the error message
1486 @samp{void-function this}.
1487
1488 The message contains the words @samp{void-function} and @samp{this}.
1489
1490 @cindex @samp{function} defined
1491 The word @samp{function} was mentioned once before. It is a very
1492 important word. For our purposes, we can define it by saying that a
1493 @dfn{function} is a set of instructions to the computer that tell the
1494 computer to do something.
1495
1496 Now we can begin to understand the error message: @samp{void-function
1497 this}. The function (that is, the word @samp{this}) does not have a
1498 definition of any set of instructions for the computer to carry out.
1499
1500 The slightly odd word, @samp{void-function}, is designed to cover the
1501 way Emacs Lisp is implemented, which is that when a symbol does not
1502 have a function definition attached to it, the place that should
1503 contain the instructions is `void'.
1504
1505 On the other hand, since we were able to add 2 plus 2 successfully, by
1506 evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1507 have a set of instructions for the computer to obey and those
1508 instructions must be to add the numbers that follow the @code{+}.
1509
1510 It is possible to prevent Emacs entering the debugger in cases like
1511 this. We do not explain how to do that here, but we will mention what
1512 the result looks like, because you may encounter a similar situation
1513 if there is a bug in some Emacs code that you are using. In such
1514 cases, you will see only one line of error message; it will appear in
1515 the echo area and look like this:
1516
1517 @smallexample
1518 Symbol's function definition is void:@: this
1519 @end smallexample
1520
1521 @noindent
1522 @ignore
1523 (Also, your terminal may beep at you---some do, some don't; and others
1524 blink. This is just a device to get your attention.)
1525 @end ignore
1526 The message goes away as soon as you type a key, even just to
1527 move the cursor.
1528
1529 We know the meaning of the word @samp{Symbol}. It refers to the first
1530 atom of the list, the word @samp{this}. The word @samp{function}
1531 refers to the instructions that tell the computer what to do.
1532 (Technically, the symbol tells the computer where to find the
1533 instructions, but this is a complication we can ignore for the
1534 moment.)
1535
1536 The error message can be understood: @samp{Symbol's function
1537 definition is void:@: this}. The symbol (that is, the word
1538 @samp{this}) lacks instructions for the computer to carry out.
1539
1540 @node Names & Definitions
1541 @section Symbol Names and Function Definitions
1542 @cindex Symbol names
1543
1544 We can articulate another characteristic of Lisp based on what we have
1545 discussed so far---an important characteristic: a symbol, like
1546 @code{+}, is not itself the set of instructions for the computer to
1547 carry out. Instead, the symbol is used, perhaps temporarily, as a way
1548 of locating the definition or set of instructions. What we see is the
1549 name through which the instructions can be found. Names of people
1550 work the same way. I can be referred to as @samp{Bob}; however, I am
1551 not the letters @samp{B}, @samp{o}, @samp{b} but am, or was, the
1552 consciousness consistently associated with a particular life-form.
1553 The name is not me, but it can be used to refer to me.
1554
1555 In Lisp, one set of instructions can be attached to several names.
1556 For example, the computer instructions for adding numbers can be
1557 linked to the symbol @code{plus} as well as to the symbol @code{+}
1558 (and are in some dialects of Lisp). Among humans, I can be referred
1559 to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1560
1561 On the other hand, a symbol can have only one function definition
1562 attached to it at a time. Otherwise, the computer would be confused as
1563 to which definition to use. If this were the case among people, only
1564 one person in the world could be named @samp{Bob}. However, the function
1565 definition to which the name refers can be changed readily.
1566 (@xref{Install, , Install a Function Definition}.)
1567
1568 Since Emacs Lisp is large, it is customary to name symbols in a way
1569 that identifies the part of Emacs to which the function belongs.
1570 Thus, all the names for functions that deal with Texinfo start with
1571 @samp{texinfo-} and those for functions that deal with reading mail
1572 start with @samp{rmail-}.
1573
1574 @node Lisp Interpreter
1575 @section The Lisp Interpreter
1576 @cindex Lisp interpreter, what it does
1577 @cindex Interpreter, what it does
1578
1579 Based on what we have seen, we can now start to figure out what the
1580 Lisp interpreter does when we command it to evaluate a list.
1581 First, it looks to see whether there is a quote before the list; if
1582 there is, the interpreter just gives us the list. On the other
1583 hand, if there is no quote, the interpreter looks at the first element
1584 in the list and sees whether it has a function definition. If it does,
1585 the interpreter carries out the instructions in the function definition.
1586 Otherwise, the interpreter prints an error message.
1587
1588 This is how Lisp works. Simple. There are added complications which we
1589 will get to in a minute, but these are the fundamentals. Of course, to
1590 write Lisp programs, you need to know how to write function definitions
1591 and attach them to names, and how to do this without confusing either
1592 yourself or the computer.
1593
1594 @menu
1595 * Complications:: Variables, Special forms, Lists within.
1596 * Byte Compiling:: Specially processing code for speed.
1597 @end menu
1598
1599 @ifnottex
1600 @node Complications
1601 @unnumberedsubsec Complications
1602 @end ifnottex
1603
1604 Now, for the first complication. In addition to lists, the Lisp
1605 interpreter can evaluate a symbol that is not quoted and does not have
1606 parentheses around it. The Lisp interpreter will attempt to determine
1607 the symbol's value as a @dfn{variable}. This situation is described
1608 in the section on variables. (@xref{Variables}.)
1609
1610 @cindex Special form
1611 The second complication occurs because some functions are unusual and do
1612 not work in the usual manner. Those that don't are called @dfn{special
1613 forms}. They are used for special jobs, like defining a function, and
1614 there are not many of them. In the next few chapters, you will be
1615 introduced to several of the more important special forms.
1616
1617 The third and final complication is this: if the function that the
1618 Lisp interpreter is looking at is not a special form, and if it is part
1619 of a list, the Lisp interpreter looks to see whether the list has a list
1620 inside of it. If there is an inner list, the Lisp interpreter first
1621 figures out what it should do with the inside list, and then it works on
1622 the outside list. If there is yet another list embedded inside the
1623 inner list, it works on that one first, and so on. It always works on
1624 the innermost list first. The interpreter works on the innermost list
1625 first, to evaluate the result of that list. The result may be
1626 used by the enclosing expression.
1627
1628 Otherwise, the interpreter works left to right, from one expression to
1629 the next.
1630
1631 @node Byte Compiling
1632 @subsection Byte Compiling
1633 @cindex Byte compiling
1634
1635 One other aspect of interpreting: the Lisp interpreter is able to
1636 interpret two kinds of entity: humanly readable code, on which we will
1637 focus exclusively, and specially processed code, called @dfn{byte
1638 compiled} code, which is not humanly readable. Byte compiled code
1639 runs faster than humanly readable code.
1640
1641 You can transform humanly readable code into byte compiled code by
1642 running one of the compile commands such as @code{byte-compile-file}.
1643 Byte compiled code is usually stored in a file that ends with a
1644 @file{.elc} extension rather than a @file{.el} extension. You will
1645 see both kinds of file in the @file{emacs/lisp} directory; the files
1646 to read are those with @file{.el} extensions.
1647
1648 As a practical matter, for most things you might do to customize or
1649 extend Emacs, you do not need to byte compile; and I will not discuss
1650 the topic here. @xref{Byte Compilation, , Byte Compilation, elisp,
1651 The GNU Emacs Lisp Reference Manual}, for a full description of byte
1652 compilation.
1653
1654 @node Evaluation
1655 @section Evaluation
1656 @cindex Evaluation
1657
1658 When the Lisp interpreter works on an expression, the term for the
1659 activity is called @dfn{evaluation}. We say that the interpreter
1660 `evaluates the expression'. I've used this term several times before.
1661 The word comes from its use in everyday language, `to ascertain the
1662 value or amount of; to appraise', according to @cite{Webster's New
1663 Collegiate Dictionary}.
1664
1665 @menu
1666 * How the Interpreter Acts:: Returns and Side Effects...
1667 * Evaluating Inner Lists:: Lists within lists...
1668 @end menu
1669
1670 @ifnottex
1671 @node How the Interpreter Acts
1672 @unnumberedsubsec How the Lisp Interpreter Acts
1673 @end ifnottex
1674
1675 @cindex @samp{returned value} explained
1676 After evaluating an expression, the Lisp interpreter will most likely
1677 @dfn{return} the value that the computer produces by carrying out the
1678 instructions it found in the function definition, or perhaps it will
1679 give up on that function and produce an error message. (The interpreter
1680 may also find itself tossed, so to speak, to a different function or it
1681 may attempt to repeat continually what it is doing for ever and ever in
1682 what is called an `infinite loop'. These actions are less common; and
1683 we can ignore them.) Most frequently, the interpreter returns a value.
1684
1685 @cindex @samp{side effect} defined
1686 At the same time the interpreter returns a value, it may do something
1687 else as well, such as move a cursor or copy a file; this other kind of
1688 action is called a @dfn{side effect}. Actions that we humans think are
1689 important, such as printing results, are often ``side effects'' to the
1690 Lisp interpreter. The jargon can sound peculiar, but it turns out that
1691 it is fairly easy to learn to use side effects.
1692
1693 In summary, evaluating a symbolic expression most commonly causes the
1694 Lisp interpreter to return a value and perhaps carry out a side effect;
1695 or else produce an error.
1696
1697 @node Evaluating Inner Lists
1698 @subsection Evaluating Inner Lists
1699 @cindex Inner list evaluation
1700 @cindex Evaluating inner lists
1701
1702 If evaluation applies to a list that is inside another list, the outer
1703 list may use the value returned by the first evaluation as information
1704 when the outer list is evaluated. This explains why inner expressions
1705 are evaluated first: the values they return are used by the outer
1706 expressions.
1707
1708 @need 1250
1709 We can investigate this process by evaluating another addition example.
1710 Place your cursor after the following expression and type @kbd{C-x C-e}:
1711
1712 @smallexample
1713 (+ 2 (+ 3 3))
1714 @end smallexample
1715
1716 @noindent
1717 The number 8 will appear in the echo area.
1718
1719 What happens is that the Lisp interpreter first evaluates the inner
1720 expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1721 evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1722 returns the value 8. Since there are no more enclosing expressions to
1723 evaluate, the interpreter prints that value in the echo area.
1724
1725 Now it is easy to understand the name of the command invoked by the
1726 keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}. The
1727 letters @code{sexp} are an abbreviation for `symbolic expression', and
1728 @code{eval} is an abbreviation for `evaluate'. The command means
1729 `evaluate last symbolic expression'.
1730
1731 As an experiment, you can try evaluating the expression by putting the
1732 cursor at the beginning of the next line immediately following the
1733 expression, or inside the expression.
1734
1735 @need 800
1736 Here is another copy of the expression:
1737
1738 @smallexample
1739 (+ 2 (+ 3 3))
1740 @end smallexample
1741
1742 @noindent
1743 If you place the cursor at the beginning of the blank line that
1744 immediately follows the expression and type @kbd{C-x C-e}, you will
1745 still get the value 8 printed in the echo area. Now try putting the
1746 cursor inside the expression. If you put it right after the next to
1747 last parenthesis (so it appears to sit on top of the last parenthesis),
1748 you will get a 6 printed in the echo area! This is because the command
1749 evaluates the expression @code{(+ 3 3)}.
1750
1751 Now put the cursor immediately after a number. Type @kbd{C-x C-e} and
1752 you will get the number itself. In Lisp, if you evaluate a number, you
1753 get the number itself---this is how numbers differ from symbols. If you
1754 evaluate a list starting with a symbol like @code{+}, you will get a
1755 value returned that is the result of the computer carrying out the
1756 instructions in the function definition attached to that name. If a
1757 symbol by itself is evaluated, something different happens, as we will
1758 see in the next section.
1759
1760 @node Variables
1761 @section Variables
1762 @cindex Variables
1763
1764 In Emacs Lisp, a symbol can have a value attached to it just as it can
1765 have a function definition attached to it. The two are different.
1766 The function definition is a set of instructions that a computer will
1767 obey. A value, on the other hand, is something, such as number or a
1768 name, that can vary (which is why such a symbol is called a variable).
1769 The value of a symbol can be any expression in Lisp, such as a symbol,
1770 number, list, or string. A symbol that has a value is often called a
1771 @dfn{variable}.
1772
1773 A symbol can have both a function definition and a value attached to
1774 it at the same time. Or it can have just one or the other.
1775 The two are separate. This is somewhat similar
1776 to the way the name Cambridge can refer to the city in Massachusetts
1777 and have some information attached to the name as well, such as
1778 ``great programming center''.
1779
1780 @ignore
1781 (Incidentally, in Emacs Lisp, a symbol can have two
1782 other things attached to it, too: a property list and a documentation
1783 string; these are discussed later.)
1784 @end ignore
1785
1786 Another way to think about this is to imagine a symbol as being a chest
1787 of drawers. The function definition is put in one drawer, the value in
1788 another, and so on. What is put in the drawer holding the value can be
1789 changed without affecting the contents of the drawer holding the
1790 function definition, and vice-verse.
1791
1792 @menu
1793 * fill-column Example::
1794 * Void Function:: The error message for a symbol
1795 without a function.
1796 * Void Variable:: The error message for a symbol without a value.
1797 @end menu
1798
1799 @ifnottex
1800 @node fill-column Example
1801 @unnumberedsubsec @code{fill-column}, an Example Variable
1802 @end ifnottex
1803
1804 @findex fill-column, @r{an example variable}
1805 @cindex Example variable, @code{fill-column}
1806 @cindex Variable, example of, @code{fill-column}
1807 The variable @code{fill-column} illustrates a symbol with a value
1808 attached to it: in every GNU Emacs buffer, this symbol is set to some
1809 value, usually 72 or 70, but sometimes to some other value. To find the
1810 value of this symbol, evaluate it by itself. If you are reading this in
1811 Info inside of GNU Emacs, you can do this by putting the cursor after
1812 the symbol and typing @kbd{C-x C-e}:
1813
1814 @smallexample
1815 fill-column
1816 @end smallexample
1817
1818 @noindent
1819 After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1820 area. This is the value for which @code{fill-column} is set for me as I
1821 write this. It may be different for you in your Info buffer. Notice
1822 that the value returned as a variable is printed in exactly the same way
1823 as the value returned by a function carrying out its instructions. From
1824 the point of view of the Lisp interpreter, a value returned is a value
1825 returned. What kind of expression it came from ceases to matter once
1826 the value is known.
1827
1828 A symbol can have any value attached to it or, to use the jargon, we can
1829 @dfn{bind} the variable to a value: to a number, such as 72; to a
1830 string, @code{"such as this"}; to a list, such as @code{(spruce pine
1831 oak)}; we can even bind a variable to a function definition.
1832
1833 A symbol can be bound to a value in several ways. @xref{set & setq, ,
1834 Setting the Value of a Variable}, for information about one way to do
1835 this.
1836
1837 @node Void Function
1838 @subsection Error Message for a Symbol Without a Function
1839 @cindex Symbol without function error
1840 @cindex Error for symbol without function
1841
1842 When we evaluated @code{fill-column} to find its value as a variable,
1843 we did not place parentheses around the word. This is because we did
1844 not intend to use it as a function name.
1845
1846 If @code{fill-column} were the first or only element of a list, the
1847 Lisp interpreter would attempt to find the function definition
1848 attached to it. But @code{fill-column} has no function definition.
1849 Try evaluating this:
1850
1851 @smallexample
1852 (fill-column)
1853 @end smallexample
1854
1855 @need 1250
1856 @noindent
1857 You will create a @file{*Backtrace*} buffer that says:
1858
1859 @smallexample
1860 @group
1861 ---------- Buffer: *Backtrace* ----------
1862 Debugger entered--Lisp error: (void-function fill-column)
1863 (fill-column)
1864 eval((fill-column))
1865 eval-last-sexp-1(nil)
1866 eval-last-sexp(nil)
1867 call-interactively(eval-last-sexp)
1868 ---------- Buffer: *Backtrace* ----------
1869 @end group
1870 @end smallexample
1871
1872 @noindent
1873 (Remember, to quit the debugger and make the debugger window go away,
1874 type @kbd{q} in the @file{*Backtrace*} buffer.)
1875
1876 @ignore
1877 @need 800
1878 In GNU Emacs 20 and before, you will produce an error message that says:
1879
1880 @smallexample
1881 Symbol's function definition is void:@: fill-column
1882 @end smallexample
1883
1884 @noindent
1885 (The message will go away as soon as you move the cursor or type
1886 another key.)
1887 @end ignore
1888
1889 @node Void Variable
1890 @subsection Error Message for a Symbol Without a Value
1891 @cindex Symbol without value error
1892 @cindex Error for symbol without value
1893
1894 If you attempt to evaluate a symbol that does not have a value bound to
1895 it, you will receive an error message. You can see this by
1896 experimenting with our 2 plus 2 addition. In the following expression,
1897 put your cursor right after the @code{+}, before the first number 2,
1898 type @kbd{C-x C-e}:
1899
1900 @smallexample
1901 (+ 2 2)
1902 @end smallexample
1903
1904 @need 1500
1905 @noindent
1906 In GNU Emacs 22, you will create a @file{*Backtrace*} buffer that
1907 says:
1908
1909 @smallexample
1910 @group
1911 ---------- Buffer: *Backtrace* ----------
1912 Debugger entered--Lisp error: (void-variable +)
1913 eval(+)
1914 eval-last-sexp-1(nil)
1915 eval-last-sexp(nil)
1916 call-interactively(eval-last-sexp)
1917 ---------- Buffer: *Backtrace* ----------
1918 @end group
1919 @end smallexample
1920
1921 @noindent
1922 (Again, you can quit the debugger by
1923 typing @kbd{q} in the @file{*Backtrace*} buffer.)
1924
1925 This backtrace is different from the very first error message we saw,
1926 which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1927 In this case, the function does not have a value as a variable; while
1928 in the other error message, the function (the word `this') did not
1929 have a definition.
1930
1931 In this experiment with the @code{+}, what we did was cause the Lisp
1932 interpreter to evaluate the @code{+} and look for the value of the
1933 variable instead of the function definition. We did this by placing the
1934 cursor right after the symbol rather than after the parenthesis of the
1935 enclosing list as we did before. As a consequence, the Lisp interpreter
1936 evaluated the preceding s-expression, which in this case was
1937 @code{+} by itself.
1938
1939 Since @code{+} does not have a value bound to it, just the function
1940 definition, the error message reported that the symbol's value as a
1941 variable was void.
1942
1943 @ignore
1944 @need 800
1945 In GNU Emacs version 20 and before, your error message will say:
1946
1947 @example
1948 Symbol's value as variable is void:@: +
1949 @end example
1950
1951 @noindent
1952 The meaning is the same as in GNU Emacs 22.
1953 @end ignore
1954
1955 @node Arguments
1956 @section Arguments
1957 @cindex Arguments
1958 @cindex Passing information to functions
1959
1960 To see how information is passed to functions, let's look again at
1961 our old standby, the addition of two plus two. In Lisp, this is written
1962 as follows:
1963
1964 @smallexample
1965 (+ 2 2)
1966 @end smallexample
1967
1968 If you evaluate this expression, the number 4 will appear in your echo
1969 area. What the Lisp interpreter does is add the numbers that follow
1970 the @code{+}.
1971
1972 @cindex @samp{argument} defined
1973 The numbers added by @code{+} are called the @dfn{arguments} of the
1974 function @code{+}. These numbers are the information that is given to
1975 or @dfn{passed} to the function.
1976
1977 The word `argument' comes from the way it is used in mathematics and
1978 does not refer to a disputation between two people; instead it refers to
1979 the information presented to the function, in this case, to the
1980 @code{+}. In Lisp, the arguments to a function are the atoms or lists
1981 that follow the function. The values returned by the evaluation of
1982 these atoms or lists are passed to the function. Different functions
1983 require different numbers of arguments; some functions require none at
1984 all.@footnote{It is curious to track the path by which the word `argument'
1985 came to have two different meanings, one in mathematics and the other in
1986 everyday English. According to the @cite{Oxford English Dictionary},
1987 the word derives from the Latin for @samp{to make clear, prove}; thus it
1988 came to mean, by one thread of derivation, `the evidence offered as
1989 proof', which is to say, `the information offered', which led to its
1990 meaning in Lisp. But in the other thread of derivation, it came to mean
1991 `to assert in a manner against which others may make counter
1992 assertions', which led to the meaning of the word as a disputation.
1993 (Note here that the English word has two different definitions attached
1994 to it at the same time. By contrast, in Emacs Lisp, a symbol cannot
1995 have two different function definitions at the same time.)}
1996
1997 @menu
1998 * Data types:: Types of data passed to a function.
1999 * Args as Variable or List:: An argument can be the value
2000 of a variable or list.
2001 * Variable Number of Arguments:: Some functions may take a
2002 variable number of arguments.
2003 * Wrong Type of Argument:: Passing an argument of the wrong type
2004 to a function.
2005 * message:: A useful function for sending messages.
2006 @end menu
2007
2008 @node Data types
2009 @subsection Arguments' Data Types
2010 @cindex Data types
2011 @cindex Types of data
2012 @cindex Arguments' data types
2013
2014 The type of data that should be passed to a function depends on what
2015 kind of information it uses. The arguments to a function such as
2016 @code{+} must have values that are numbers, since @code{+} adds numbers.
2017 Other functions use different kinds of data for their arguments.
2018
2019 @need 1250
2020 @findex concat
2021 For example, the @code{concat} function links together or unites two or
2022 more strings of text to produce a string. The arguments are strings.
2023 Concatenating the two character strings @code{abc}, @code{def} produces
2024 the single string @code{abcdef}. This can be seen by evaluating the
2025 following:
2026
2027 @smallexample
2028 (concat "abc" "def")
2029 @end smallexample
2030
2031 @noindent
2032 The value produced by evaluating this expression is @code{"abcdef"}.
2033
2034 A function such as @code{substring} uses both a string and numbers as
2035 arguments. The function returns a part of the string, a substring of
2036 the first argument. This function takes three arguments. Its first
2037 argument is the string of characters, the second and third arguments are
2038 numbers that indicate the beginning and end of the substring. The
2039 numbers are a count of the number of characters (including spaces and
2040 punctuation) from the beginning of the string.
2041
2042 @need 800
2043 For example, if you evaluate the following:
2044
2045 @smallexample
2046 (substring "The quick brown fox jumped." 16 19)
2047 @end smallexample
2048
2049 @noindent
2050 you will see @code{"fox"} appear in the echo area. The arguments are the
2051 string and the two numbers.
2052
2053 Note that the string passed to @code{substring} is a single atom even
2054 though it is made up of several words separated by spaces. Lisp counts
2055 everything between the two quotation marks as part of the string,
2056 including the spaces. You can think of the @code{substring} function as
2057 a kind of `atom smasher' since it takes an otherwise indivisible atom
2058 and extracts a part. However, @code{substring} is only able to extract
2059 a substring from an argument that is a string, not from another type of
2060 atom such as a number or symbol.
2061
2062 @node Args as Variable or List
2063 @subsection An Argument as the Value of a Variable or List
2064
2065 An argument can be a symbol that returns a value when it is evaluated.
2066 For example, when the symbol @code{fill-column} by itself is evaluated,
2067 it returns a number. This number can be used in an addition.
2068
2069 @need 1250
2070 Position the cursor after the following expression and type @kbd{C-x
2071 C-e}:
2072
2073 @smallexample
2074 (+ 2 fill-column)
2075 @end smallexample
2076
2077 @noindent
2078 The value will be a number two more than what you get by evaluating
2079 @code{fill-column} alone. For me, this is 74, because my value of
2080 @code{fill-column} is 72.
2081
2082 As we have just seen, an argument can be a symbol that returns a value
2083 when evaluated. In addition, an argument can be a list that returns a
2084 value when it is evaluated. For example, in the following expression,
2085 the arguments to the function @code{concat} are the strings
2086 @w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2087 @code{(number-to-string (+ 2 fill-column))}.
2088
2089 @c For GNU Emacs 22, need number-to-string
2090 @smallexample
2091 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2092 @end smallexample
2093
2094 @noindent
2095 If you evaluate this expression---and if, as with my Emacs,
2096 @code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2097 appear in the echo area. (Note that you must put spaces after the
2098 word @samp{The} and before the word @samp{red} so they will appear in
2099 the final string. The function @code{number-to-string} converts the
2100 integer that the addition function returns to a string.
2101 @code{number-to-string} is also known as @code{int-to-string}.)
2102
2103 @node Variable Number of Arguments
2104 @subsection Variable Number of Arguments
2105 @cindex Variable number of arguments
2106 @cindex Arguments, variable number of
2107
2108 Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2109 number of arguments. (The @code{*} is the symbol for multiplication.)
2110 This can be seen by evaluating each of the following expressions in
2111 the usual way. What you will see in the echo area is printed in this
2112 text after @samp{@result{}}, which you may read as `evaluates to'.
2113
2114 @need 1250
2115 In the first set, the functions have no arguments:
2116
2117 @smallexample
2118 @group
2119 (+) @result{} 0
2120
2121 (*) @result{} 1
2122 @end group
2123 @end smallexample
2124
2125 @need 1250
2126 In this set, the functions have one argument each:
2127
2128 @smallexample
2129 @group
2130 (+ 3) @result{} 3
2131
2132 (* 3) @result{} 3
2133 @end group
2134 @end smallexample
2135
2136 @need 1250
2137 In this set, the functions have three arguments each:
2138
2139 @smallexample
2140 @group
2141 (+ 3 4 5) @result{} 12
2142
2143 (* 3 4 5) @result{} 60
2144 @end group
2145 @end smallexample
2146
2147 @node Wrong Type of Argument
2148 @subsection Using the Wrong Type Object as an Argument
2149 @cindex Wrong type of argument
2150 @cindex Argument, wrong type of
2151
2152 When a function is passed an argument of the wrong type, the Lisp
2153 interpreter produces an error message. For example, the @code{+}
2154 function expects the values of its arguments to be numbers. As an
2155 experiment we can pass it the quoted symbol @code{hello} instead of a
2156 number. Position the cursor after the following expression and type
2157 @kbd{C-x C-e}:
2158
2159 @smallexample
2160 (+ 2 'hello)
2161 @end smallexample
2162
2163 @noindent
2164 When you do this you will generate an error message. What has happened
2165 is that @code{+} has tried to add the 2 to the value returned by
2166 @code{'hello}, but the value returned by @code{'hello} is the symbol
2167 @code{hello}, not a number. Only numbers can be added. So @code{+}
2168 could not carry out its addition.
2169
2170 @need 1250
2171 You will create and enter a @file{*Backtrace*} buffer that says:
2172
2173 @noindent
2174 @smallexample
2175 @group
2176 ---------- Buffer: *Backtrace* ----------
2177 Debugger entered--Lisp error:
2178 (wrong-type-argument number-or-marker-p hello)
2179 +(2 hello)
2180 eval((+ 2 (quote hello)))
2181 eval-last-sexp-1(nil)
2182 eval-last-sexp(nil)
2183 call-interactively(eval-last-sexp)
2184 ---------- Buffer: *Backtrace* ----------
2185 @end group
2186 @end smallexample
2187
2188 @need 1250
2189 As usual, the error message tries to be helpful and makes sense after you
2190 learn how to read it.@footnote{@code{(quote hello)} is an expansion of
2191 the abbreviation @code{'hello}.}
2192
2193 The first part of the error message is straightforward; it says
2194 @samp{wrong type argument}. Next comes the mysterious jargon word
2195 @w{@samp{number-or-marker-p}}. This word is trying to tell you what
2196 kind of argument the @code{+} expected.
2197
2198 The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2199 trying to determine whether the information presented it (the value of
2200 the argument) is a number or a marker (a special object representing a
2201 buffer position). What it does is test to see whether the @code{+} is
2202 being given numbers to add. It also tests to see whether the
2203 argument is something called a marker, which is a specific feature of
2204 Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
2205 When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2206 its position is kept as a marker. The mark can be considered a
2207 number---the number of characters the location is from the beginning
2208 of the buffer.) In Emacs Lisp, @code{+} can be used to add the
2209 numeric value of marker positions as numbers.
2210
2211 The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2212 practice started in the early days of Lisp programming. The @samp{p}
2213 stands for `predicate'. In the jargon used by the early Lisp
2214 researchers, a predicate refers to a function to determine whether some
2215 property is true or false. So the @samp{p} tells us that
2216 @code{number-or-marker-p} is the name of a function that determines
2217 whether it is true or false that the argument supplied is a number or
2218 a marker. Other Lisp symbols that end in @samp{p} include @code{zerop},
2219 a function that tests whether its argument has the value of zero, and
2220 @code{listp}, a function that tests whether its argument is a list.
2221
2222 Finally, the last part of the error message is the symbol @code{hello}.
2223 This is the value of the argument that was passed to @code{+}. If the
2224 addition had been passed the correct type of object, the value passed
2225 would have been a number, such as 37, rather than a symbol like
2226 @code{hello}. But then you would not have got the error message.
2227
2228 @ignore
2229 @need 1250
2230 In GNU Emacs version 20 and before, the echo area displays an error
2231 message that says:
2232
2233 @smallexample
2234 Wrong type argument:@: number-or-marker-p, hello
2235 @end smallexample
2236
2237 This says, in different words, the same as the top line of the
2238 @file{*Backtrace*} buffer.
2239 @end ignore
2240
2241 @node message
2242 @subsection The @code{message} Function
2243 @findex message
2244
2245 Like @code{+}, the @code{message} function takes a variable number of
2246 arguments. It is used to send messages to the user and is so useful
2247 that we will describe it here.
2248
2249 @need 1250
2250 A message is printed in the echo area. For example, you can print a
2251 message in your echo area by evaluating the following list:
2252
2253 @smallexample
2254 (message "This message appears in the echo area!")
2255 @end smallexample
2256
2257 The whole string between double quotation marks is a single argument
2258 and is printed @i{in toto}. (Note that in this example, the message
2259 itself will appear in the echo area within double quotes; that is
2260 because you see the value returned by the @code{message} function. In
2261 most uses of @code{message} in programs that you write, the text will
2262 be printed in the echo area as a side-effect, without the quotes.
2263 @xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2264 detail}, for an example of this.)
2265
2266 However, if there is a @samp{%s} in the quoted string of characters, the
2267 @code{message} function does not print the @samp{%s} as such, but looks
2268 to the argument that follows the string. It evaluates the second
2269 argument and prints the value at the location in the string where the
2270 @samp{%s} is.
2271
2272 @need 1250
2273 You can see this by positioning the cursor after the following
2274 expression and typing @kbd{C-x C-e}:
2275
2276 @smallexample
2277 (message "The name of this buffer is: %s." (buffer-name))
2278 @end smallexample
2279
2280 @noindent
2281 In Info, @code{"The name of this buffer is: *info*."} will appear in the
2282 echo area. The function @code{buffer-name} returns the name of the
2283 buffer as a string, which the @code{message} function inserts in place
2284 of @code{%s}.
2285
2286 To print a value as an integer, use @samp{%d} in the same way as
2287 @samp{%s}. For example, to print a message in the echo area that
2288 states the value of the @code{fill-column}, evaluate the following:
2289
2290 @smallexample
2291 (message "The value of fill-column is %d." fill-column)
2292 @end smallexample
2293
2294 @noindent
2295 On my system, when I evaluate this list, @code{"The value of
2296 fill-column is 72."} appears in my echo area@footnote{Actually, you
2297 can use @code{%s} to print a number. It is non-specific. @code{%d}
2298 prints only the part of a number left of a decimal point, and not
2299 anything that is not a number.}.
2300
2301 If there is more than one @samp{%s} in the quoted string, the value of
2302 the first argument following the quoted string is printed at the
2303 location of the first @samp{%s} and the value of the second argument is
2304 printed at the location of the second @samp{%s}, and so on.
2305
2306 @need 1250
2307 For example, if you evaluate the following,
2308
2309 @smallexample
2310 @group
2311 (message "There are %d %s in the office!"
2312 (- fill-column 14) "pink elephants")
2313 @end group
2314 @end smallexample
2315
2316 @noindent
2317 a rather whimsical message will appear in your echo area. On my system
2318 it says, @code{"There are 58 pink elephants in the office!"}.
2319
2320 The expression @code{(- fill-column 14)} is evaluated and the resulting
2321 number is inserted in place of the @samp{%d}; and the string in double
2322 quotes, @code{"pink elephants"}, is treated as a single argument and
2323 inserted in place of the @samp{%s}. (That is to say, a string between
2324 double quotes evaluates to itself, like a number.)
2325
2326 Finally, here is a somewhat complex example that not only illustrates
2327 the computation of a number, but also shows how you can use an
2328 expression within an expression to generate the text that is substituted
2329 for @samp{%s}:
2330
2331 @smallexample
2332 @group
2333 (message "He saw %d %s"
2334 (- fill-column 32)
2335 (concat "red "
2336 (substring
2337 "The quick brown foxes jumped." 16 21)
2338 " leaping."))
2339 @end group
2340 @end smallexample
2341
2342 In this example, @code{message} has three arguments: the string,
2343 @code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2344 the expression beginning with the function @code{concat}. The value
2345 resulting from the evaluation of @code{(- fill-column 32)} is inserted
2346 in place of the @samp{%d}; and the value returned by the expression
2347 beginning with @code{concat} is inserted in place of the @samp{%s}.
2348
2349 When your fill column is 70 and you evaluate the expression, the
2350 message @code{"He saw 38 red foxes leaping."} appears in your echo
2351 area.
2352
2353 @node set & setq
2354 @section Setting the Value of a Variable
2355 @cindex Variable, setting value
2356 @cindex Setting value of variable
2357
2358 @cindex @samp{bind} defined
2359 There are several ways by which a variable can be given a value. One of
2360 the ways is to use either the function @code{set} or the function
2361 @code{setq}. Another way is to use @code{let} (@pxref{let}). (The
2362 jargon for this process is to @dfn{bind} a variable to a value.)
2363
2364 The following sections not only describe how @code{set} and @code{setq}
2365 work but also illustrate how arguments are passed.
2366
2367 @menu
2368 * Using set:: Setting values.
2369 * Using setq:: Setting a quoted value.
2370 * Counting:: Using @code{setq} to count.
2371 @end menu
2372
2373 @node Using set
2374 @subsection Using @code{set}
2375 @findex set
2376
2377 To set the value of the symbol @code{flowers} to the list @code{'(rose
2378 violet daisy buttercup)}, evaluate the following expression by
2379 positioning the cursor after the expression and typing @kbd{C-x C-e}.
2380
2381 @smallexample
2382 (set 'flowers '(rose violet daisy buttercup))
2383 @end smallexample
2384
2385 @noindent
2386 The list @code{(rose violet daisy buttercup)} will appear in the echo
2387 area. This is what is @emph{returned} by the @code{set} function. As a
2388 side effect, the symbol @code{flowers} is bound to the list; that is,
2389 the symbol @code{flowers}, which can be viewed as a variable, is given
2390 the list as its value. (This process, by the way, illustrates how a
2391 side effect to the Lisp interpreter, setting the value, can be the
2392 primary effect that we humans are interested in. This is because every
2393 Lisp function must return a value if it does not get an error, but it
2394 will only have a side effect if it is designed to have one.)
2395
2396 After evaluating the @code{set} expression, you can evaluate the symbol
2397 @code{flowers} and it will return the value you just set. Here is the
2398 symbol. Place your cursor after it and type @kbd{C-x C-e}.
2399
2400 @smallexample
2401 flowers
2402 @end smallexample
2403
2404 @noindent
2405 When you evaluate @code{flowers}, the list
2406 @code{(rose violet daisy buttercup)} appears in the echo area.
2407
2408 Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2409 in front of it, what you will see in the echo area is the symbol itself,
2410 @code{flowers}. Here is the quoted symbol, so you can try this:
2411
2412 @smallexample
2413 'flowers
2414 @end smallexample
2415
2416 Note also, that when you use @code{set}, you need to quote both
2417 arguments to @code{set}, unless you want them evaluated. Since we do
2418 not want either argument evaluated, neither the variable
2419 @code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2420 are quoted. (When you use @code{set} without quoting its first
2421 argument, the first argument is evaluated before anything else is
2422 done. If you did this and @code{flowers} did not have a value
2423 already, you would get an error message that the @samp{Symbol's value
2424 as variable is void}; on the other hand, if @code{flowers} did return
2425 a value after it was evaluated, the @code{set} would attempt to set
2426 the value that was returned. There are situations where this is the
2427 right thing for the function to do; but such situations are rare.)
2428
2429 @node Using setq
2430 @subsection Using @code{setq}
2431 @findex setq
2432
2433 As a practical matter, you almost always quote the first argument to
2434 @code{set}. The combination of @code{set} and a quoted first argument
2435 is so common that it has its own name: the special form @code{setq}.
2436 This special form is just like @code{set} except that the first argument
2437 is quoted automatically, so you don't need to type the quote mark
2438 yourself. Also, as an added convenience, @code{setq} permits you to set
2439 several different variables to different values, all in one expression.
2440
2441 To set the value of the variable @code{carnivores} to the list
2442 @code{'(lion tiger leopard)} using @code{setq}, the following expression
2443 is used:
2444
2445 @smallexample
2446 (setq carnivores '(lion tiger leopard))
2447 @end smallexample
2448
2449 @noindent
2450 This is exactly the same as using @code{set} except the first argument
2451 is automatically quoted by @code{setq}. (The @samp{q} in @code{setq}
2452 means @code{quote}.)
2453
2454 @need 1250
2455 With @code{set}, the expression would look like this:
2456
2457 @smallexample
2458 (set 'carnivores '(lion tiger leopard))
2459 @end smallexample
2460
2461 Also, @code{setq} can be used to assign different values to
2462 different variables. The first argument is bound to the value
2463 of the second argument, the third argument is bound to the value of the
2464 fourth argument, and so on. For example, you could use the following to
2465 assign a list of trees to the symbol @code{trees} and a list of herbivores
2466 to the symbol @code{herbivores}:
2467
2468 @smallexample
2469 @group
2470 (setq trees '(pine fir oak maple)
2471 herbivores '(gazelle antelope zebra))
2472 @end group
2473 @end smallexample
2474
2475 @noindent
2476 (The expression could just as well have been on one line, but it might
2477 not have fit on a page; and humans find it easier to read nicely
2478 formatted lists.)
2479
2480 Although I have been using the term `assign', there is another way of
2481 thinking about the workings of @code{set} and @code{setq}; and that is to
2482 say that @code{set} and @code{setq} make the symbol @emph{point} to the
2483 list. This latter way of thinking is very common and in forthcoming
2484 chapters we shall come upon at least one symbol that has `pointer' as
2485 part of its name. The name is chosen because the symbol has a value,
2486 specifically a list, attached to it; or, expressed another way,
2487 the symbol is set to ``point'' to the list.
2488
2489 @node Counting
2490 @subsection Counting
2491 @cindex Counting
2492
2493 Here is an example that shows how to use @code{setq} in a counter. You
2494 might use this to count how many times a part of your program repeats
2495 itself. First set a variable to zero; then add one to the number each
2496 time the program repeats itself. To do this, you need a variable that
2497 serves as a counter, and two expressions: an initial @code{setq}
2498 expression that sets the counter variable to zero; and a second
2499 @code{setq} expression that increments the counter each time it is
2500 evaluated.
2501
2502 @smallexample
2503 @group
2504 (setq counter 0) ; @r{Let's call this the initializer.}
2505
2506 (setq counter (+ counter 1)) ; @r{This is the incrementer.}
2507
2508 counter ; @r{This is the counter.}
2509 @end group
2510 @end smallexample
2511
2512 @noindent
2513 (The text following the @samp{;} are comments. @xref{Change a
2514 defun, , Change a Function Definition}.)
2515
2516 If you evaluate the first of these expressions, the initializer,
2517 @code{(setq counter 0)}, and then evaluate the third expression,
2518 @code{counter}, the number @code{0} will appear in the echo area. If
2519 you then evaluate the second expression, the incrementer, @code{(setq
2520 counter (+ counter 1))}, the counter will get the value 1. So if you
2521 again evaluate @code{counter}, the number @code{1} will appear in the
2522 echo area. Each time you evaluate the second expression, the value of
2523 the counter will be incremented.
2524
2525 When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2526 the Lisp interpreter first evaluates the innermost list; this is the
2527 addition. In order to evaluate this list, it must evaluate the variable
2528 @code{counter} and the number @code{1}. When it evaluates the variable
2529 @code{counter}, it receives its current value. It passes this value and
2530 the number @code{1} to the @code{+} which adds them together. The sum
2531 is then returned as the value of the inner list and passed to the
2532 @code{setq} which sets the variable @code{counter} to this new value.
2533 Thus, the value of the variable, @code{counter}, is changed.
2534
2535 @node Summary
2536 @section Summary
2537
2538 Learning Lisp is like climbing a hill in which the first part is the
2539 steepest. You have now climbed the most difficult part; what remains
2540 becomes easier as you progress onwards.
2541
2542 @need 1000
2543 In summary,
2544
2545 @itemize @bullet
2546
2547 @item
2548 Lisp programs are made up of expressions, which are lists or single atoms.
2549
2550 @item
2551 Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2552 surrounded by parentheses. A list can be empty.
2553
2554 @item
2555 Atoms are multi-character symbols, like @code{forward-paragraph}, single
2556 character symbols like @code{+}, strings of characters between double
2557 quotation marks, or numbers.
2558
2559 @item
2560 A number evaluates to itself.
2561
2562 @item
2563 A string between double quotes also evaluates to itself.
2564
2565 @item
2566 When you evaluate a symbol by itself, its value is returned.
2567
2568 @item
2569 When you evaluate a list, the Lisp interpreter looks at the first symbol
2570 in the list and then at the function definition bound to that symbol.
2571 Then the instructions in the function definition are carried out.
2572
2573 @item
2574 A single quotation mark,
2575 @ifinfo
2576 '
2577 @end ifinfo
2578 @ifnotinfo
2579 @code{'}
2580 @end ifnotinfo
2581 , tells the Lisp interpreter that it should
2582 return the following expression as written, and not evaluate it as it
2583 would if the quote were not there.
2584
2585 @item
2586 Arguments are the information passed to a function. The arguments to a
2587 function are computed by evaluating the rest of the elements of the list
2588 of which the function is the first element.
2589
2590 @item
2591 A function always returns a value when it is evaluated (unless it gets
2592 an error); in addition, it may also carry out some action called a
2593 ``side effect''. In many cases, a function's primary purpose is to
2594 create a side effect.
2595 @end itemize
2596
2597 @node Error Message Exercises
2598 @section Exercises
2599
2600 A few simple exercises:
2601
2602 @itemize @bullet
2603 @item
2604 Generate an error message by evaluating an appropriate symbol that is
2605 not within parentheses.
2606
2607 @item
2608 Generate an error message by evaluating an appropriate symbol that is
2609 between parentheses.
2610
2611 @item
2612 Create a counter that increments by two rather than one.
2613
2614 @item
2615 Write an expression that prints a message in the echo area when
2616 evaluated.
2617 @end itemize
2618
2619 @node Practicing Evaluation
2620 @chapter Practicing Evaluation
2621 @cindex Practicing evaluation
2622 @cindex Evaluation practice
2623
2624 Before learning how to write a function definition in Emacs Lisp, it is
2625 useful to spend a little time evaluating various expressions that have
2626 already been written. These expressions will be lists with the
2627 functions as their first (and often only) element. Since some of the
2628 functions associated with buffers are both simple and interesting, we
2629 will start with those. In this section, we will evaluate a few of
2630 these. In another section, we will study the code of several other
2631 buffer-related functions, to see how they were written.
2632
2633 @menu
2634 * How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
2635 causes evaluation.
2636 * Buffer Names:: Buffers and files are different.
2637 * Getting Buffers:: Getting a buffer itself, not merely its name.
2638 * Switching Buffers:: How to change to another buffer.
2639 * Buffer Size & Locations:: Where point is located and the size of
2640 the buffer.
2641 * Evaluation Exercise::
2642 @end menu
2643
2644 @ifnottex
2645 @node How to Evaluate
2646 @unnumberedsec How to Evaluate
2647 @end ifnottex
2648
2649 @i{Whenever you give an editing command} to Emacs Lisp, such as the
2650 command to move the cursor or to scroll the screen, @i{you are evaluating
2651 an expression,} the first element of which is a function. @i{This is
2652 how Emacs works.}
2653
2654 @cindex @samp{interactive function} defined
2655 @cindex @samp{command} defined
2656 When you type keys, you cause the Lisp interpreter to evaluate an
2657 expression and that is how you get your results. Even typing plain text
2658 involves evaluating an Emacs Lisp function, in this case, one that uses
2659 @code{self-insert-command}, which simply inserts the character you
2660 typed. The functions you evaluate by typing keystrokes are called
2661 @dfn{interactive} functions, or @dfn{commands}; how you make a function
2662 interactive will be illustrated in the chapter on how to write function
2663 definitions. @xref{Interactive, , Making a Function Interactive}.
2664
2665 In addition to typing keyboard commands, we have seen a second way to
2666 evaluate an expression: by positioning the cursor after a list and
2667 typing @kbd{C-x C-e}. This is what we will do in the rest of this
2668 section. There are other ways to evaluate an expression as well; these
2669 will be described as we come to them.
2670
2671 Besides being used for practicing evaluation, the functions shown in the
2672 next few sections are important in their own right. A study of these
2673 functions makes clear the distinction between buffers and files, how to
2674 switch to a buffer, and how to determine a location within it.
2675
2676 @node Buffer Names
2677 @section Buffer Names
2678 @findex buffer-name
2679 @findex buffer-file-name
2680
2681 The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2682 the difference between a file and a buffer. When you evaluate the
2683 following expression, @code{(buffer-name)}, the name of the buffer
2684 appears in the echo area. When you evaluate @code{(buffer-file-name)},
2685 the name of the file to which the buffer refers appears in the echo
2686 area. Usually, the name returned by @code{(buffer-name)} is the same as
2687 the name of the file to which it refers, and the name returned by
2688 @code{(buffer-file-name)} is the full path-name of the file.
2689
2690 A file and a buffer are two different entities. A file is information
2691 recorded permanently in the computer (unless you delete it). A buffer,
2692 on the other hand, is information inside of Emacs that will vanish at
2693 the end of the editing session (or when you kill the buffer). Usually,
2694 a buffer contains information that you have copied from a file; we say
2695 the buffer is @dfn{visiting} that file. This copy is what you work on
2696 and modify. Changes to the buffer do not change the file, until you
2697 save the buffer. When you save the buffer, the buffer is copied to the file
2698 and is thus saved permanently.
2699
2700 @need 1250
2701 If you are reading this in Info inside of GNU Emacs, you can evaluate
2702 each of the following expressions by positioning the cursor after it and
2703 typing @kbd{C-x C-e}.
2704
2705 @example
2706 @group
2707 (buffer-name)
2708
2709 (buffer-file-name)
2710 @end group
2711 @end example
2712
2713 @noindent
2714 When I do this in Info, the value returned by evaluating
2715 @code{(buffer-name)} is @file{"*info*"}, and the value returned by
2716 evaluating @code{(buffer-file-name)} is @file{nil}.
2717
2718 On the other hand, while I am writing this document, the value
2719 returned by evaluating @code{(buffer-name)} is
2720 @file{"introduction.texinfo"}, and the value returned by evaluating
2721 @code{(buffer-file-name)} is
2722 @file{"/gnu/work/intro/introduction.texinfo"}.
2723
2724 @cindex @code{nil}, history of word
2725 The former is the name of the buffer and the latter is the name of the
2726 file. In Info, the buffer name is @file{"*info*"}. Info does not
2727 point to any file, so the result of evaluating
2728 @code{(buffer-file-name)} is @file{nil}. The symbol @code{nil} is
2729 from the Latin word for `nothing'; in this case, it means that the
2730 buffer is not associated with any file. (In Lisp, @code{nil} is also
2731 used to mean `false' and is a synonym for the empty list, @code{()}.)
2732
2733 When I am writing, the name of my buffer is
2734 @file{"introduction.texinfo"}. The name of the file to which it
2735 points is @file{"/gnu/work/intro/introduction.texinfo"}.
2736
2737 (In the expressions, the parentheses tell the Lisp interpreter to
2738 treat @w{@code{buffer-name}} and @w{@code{buffer-file-name}} as
2739 functions; without the parentheses, the interpreter would attempt to
2740 evaluate the symbols as variables. @xref{Variables}.)
2741
2742 In spite of the distinction between files and buffers, you will often
2743 find that people refer to a file when they mean a buffer and vice-verse.
2744 Indeed, most people say, ``I am editing a file,'' rather than saying,
2745 ``I am editing a buffer which I will soon save to a file.'' It is
2746 almost always clear from context what people mean. When dealing with
2747 computer programs, however, it is important to keep the distinction in mind,
2748 since the computer is not as smart as a person.
2749
2750 @cindex Buffer, history of word
2751 The word `buffer', by the way, comes from the meaning of the word as a
2752 cushion that deadens the force of a collision. In early computers, a
2753 buffer cushioned the interaction between files and the computer's
2754 central processing unit. The drums or tapes that held a file and the
2755 central processing unit were pieces of equipment that were very
2756 different from each other, working at their own speeds, in spurts. The
2757 buffer made it possible for them to work together effectively.
2758 Eventually, the buffer grew from being an intermediary, a temporary
2759 holding place, to being the place where work is done. This
2760 transformation is rather like that of a small seaport that grew into a
2761 great city: once it was merely the place where cargo was warehoused
2762 temporarily before being loaded onto ships; then it became a business
2763 and cultural center in its own right.
2764
2765 Not all buffers are associated with files. For example, a
2766 @file{*scratch*} buffer does not visit any file. Similarly, a
2767 @file{*Help*} buffer is not associated with any file.
2768
2769 In the old days, when you lacked a @file{~/.emacs} file and started an
2770 Emacs session by typing the command @code{emacs} alone, without naming
2771 any files, Emacs started with the @file{*scratch*} buffer visible.
2772 Nowadays, you will see a splash screen. You can follow one of the
2773 commands suggested on the splash screen, visit a file, or press the
2774 spacebar to reach the @file{*scratch*} buffer.
2775
2776 If you switch to the @file{*scratch*} buffer, type
2777 @code{(buffer-name)}, position the cursor after it, and then type
2778 @kbd{C-x C-e} to evaluate the expression. The name @code{"*scratch*"}
2779 will be returned and will appear in the echo area. @code{"*scratch*"}
2780 is the name of the buffer. When you type @code{(buffer-file-name)} in
2781 the @file{*scratch*} buffer and evaluate that, @code{nil} will appear
2782 in the echo area, just as it does when you evaluate
2783 @code{(buffer-file-name)} in Info.
2784
2785 Incidentally, if you are in the @file{*scratch*} buffer and want the
2786 value returned by an expression to appear in the @file{*scratch*}
2787 buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2788 instead of @kbd{C-x C-e}. This causes the value returned to appear
2789 after the expression. The buffer will look like this:
2790
2791 @smallexample
2792 (buffer-name)"*scratch*"
2793 @end smallexample
2794
2795 @noindent
2796 You cannot do this in Info since Info is read-only and it will not allow
2797 you to change the contents of the buffer. But you can do this in any
2798 buffer you can edit; and when you write code or documentation (such as
2799 this book), this feature is very useful.
2800
2801 @node Getting Buffers
2802 @section Getting Buffers
2803 @findex current-buffer
2804 @findex other-buffer
2805 @cindex Getting a buffer
2806
2807 The @code{buffer-name} function returns the @emph{name} of the buffer;
2808 to get the buffer @emph{itself}, a different function is needed: the
2809 @code{current-buffer} function. If you use this function in code, what
2810 you get is the buffer itself.
2811
2812 A name and the object or entity to which the name refers are different
2813 from each other. You are not your name. You are a person to whom
2814 others refer by name. If you ask to speak to George and someone hands you
2815 a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2816 @samp{g}, and @samp{e} written on it, you might be amused, but you would
2817 not be satisfied. You do not want to speak to the name, but to the
2818 person to whom the name refers. A buffer is similar: the name of the
2819 scratch buffer is @file{*scratch*}, but the name is not the buffer. To
2820 get a buffer itself, you need to use a function such as
2821 @code{current-buffer}.
2822
2823 However, there is a slight complication: if you evaluate
2824 @code{current-buffer} in an expression on its own, as we will do here,
2825 what you see is a printed representation of the name of the buffer
2826 without the contents of the buffer. Emacs works this way for two
2827 reasons: the buffer may be thousands of lines long---too long to be
2828 conveniently displayed; and, another buffer may have the same contents
2829 but a different name, and it is important to distinguish between them.
2830
2831 @need 800
2832 Here is an expression containing the function:
2833
2834 @smallexample
2835 (current-buffer)
2836 @end smallexample
2837
2838 @noindent
2839 If you evaluate this expression in Info in Emacs in the usual way,
2840 @file{#<buffer *info*>} will appear in the echo area. The special
2841 format indicates that the buffer itself is being returned, rather than
2842 just its name.
2843
2844 Incidentally, while you can type a number or symbol into a program, you
2845 cannot do that with the printed representation of a buffer: the only way
2846 to get a buffer itself is with a function such as @code{current-buffer}.
2847
2848 A related function is @code{other-buffer}. This returns the most
2849 recently selected buffer other than the one you are in currently, not
2850 a printed representation of its name. If you have recently switched
2851 back and forth from the @file{*scratch*} buffer, @code{other-buffer}
2852 will return that buffer.
2853
2854 @need 800
2855 You can see this by evaluating the expression:
2856
2857 @smallexample
2858 (other-buffer)
2859 @end smallexample
2860
2861 @noindent
2862 You should see @file{#<buffer *scratch*>} appear in the echo area, or
2863 the name of whatever other buffer you switched back from most
2864 recently@footnote{Actually, by default, if the buffer from which you
2865 just switched is visible to you in another window, @code{other-buffer}
2866 will choose the most recent buffer that you cannot see; this is a
2867 subtlety that I often forget.}.
2868
2869 @node Switching Buffers
2870 @section Switching Buffers
2871 @findex switch-to-buffer
2872 @findex set-buffer
2873 @cindex Switching to a buffer
2874
2875 The @code{other-buffer} function actually provides a buffer when it is
2876 used as an argument to a function that requires one. We can see this
2877 by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2878 different buffer.
2879
2880 But first, a brief introduction to the @code{switch-to-buffer}
2881 function. When you switched back and forth from Info to the
2882 @file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2883 likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2884 rather, to save typing, you probably only typed @kbd{RET} if the
2885 default buffer was @file{*scratch*}, or if it was different, then you
2886 typed just part of the name, such as @code{*sc}, pressed your
2887 @kbd{TAB} key to cause it to expand to the full name, and then typed
2888 @kbd{RET}.} when prompted in the minibuffer for the name of
2889 the buffer to which you wanted to switch. The keystrokes, @kbd{C-x
2890 b}, cause the Lisp interpreter to evaluate the interactive function
2891 @code{switch-to-buffer}. As we said before, this is how Emacs works:
2892 different keystrokes call or run different functions. For example,
2893 @kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2894 @code{forward-sentence}, and so on.
2895
2896 By writing @code{switch-to-buffer} in an expression, and giving it a
2897 buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2898 does:
2899
2900 @smallexample
2901 (switch-to-buffer (other-buffer))
2902 @end smallexample
2903
2904 @noindent
2905 The symbol @code{switch-to-buffer} is the first element of the list,
2906 so the Lisp interpreter will treat it as a function and carry out the
2907 instructions that are attached to it. But before doing that, the
2908 interpreter will note that @code{other-buffer} is inside parentheses
2909 and work on that symbol first. @code{other-buffer} is the first (and
2910 in this case, the only) element of this list, so the Lisp interpreter
2911 calls or runs the function. It returns another buffer. Next, the
2912 interpreter runs @code{switch-to-buffer}, passing to it, as an
2913 argument, the other buffer, which is what Emacs will switch to. If
2914 you are reading this in Info, try this now. Evaluate the expression.
2915 (To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2916 expression will move you to your most recent other buffer that you
2917 cannot see. If you really want to go to your most recently selected
2918 buffer, even if you can still see it, you need to evaluate the
2919 following more complex expression:
2920
2921 @smallexample
2922 (switch-to-buffer (other-buffer (current-buffer) t))
2923 @end smallexample
2924
2925 @c noindent
2926 In this case, the first argument to @code{other-buffer} tells it which
2927 buffer to skip---the current one---and the second argument tells
2928 @code{other-buffer} it is OK to switch to a visible buffer.
2929 In regular use, @code{switch-to-buffer} takes you to an invisible
2930 window since you would most likely use @kbd{C-x o} (@code{other-window})
2931 to go to another visible buffer.}
2932
2933 In the programming examples in later sections of this document, you will
2934 see the function @code{set-buffer} more often than
2935 @code{switch-to-buffer}. This is because of a difference between
2936 computer programs and humans: humans have eyes and expect to see the
2937 buffer on which they are working on their computer terminals. This is
2938 so obvious, it almost goes without saying. However, programs do not
2939 have eyes. When a computer program works on a buffer, that buffer does
2940 not need to be visible on the screen.
2941
2942 @code{switch-to-buffer} is designed for humans and does two different
2943 things: it switches the buffer to which Emacs's attention is directed; and
2944 it switches the buffer displayed in the window to the new buffer.
2945 @code{set-buffer}, on the other hand, does only one thing: it switches
2946 the attention of the computer program to a different buffer. The buffer
2947 on the screen remains unchanged (of course, normally nothing happens
2948 there until the command finishes running).
2949
2950 @cindex @samp{call} defined
2951 Also, we have just introduced another jargon term, the word @dfn{call}.
2952 When you evaluate a list in which the first symbol is a function, you
2953 are calling that function. The use of the term comes from the notion of
2954 the function as an entity that can do something for you if you `call'
2955 it---just as a plumber is an entity who can fix a leak if you call him
2956 or her.
2957
2958 @node Buffer Size & Locations
2959 @section Buffer Size and the Location of Point
2960 @cindex Size of buffer
2961 @cindex Buffer size
2962 @cindex Point location
2963 @cindex Location of point
2964
2965 Finally, let's look at several rather simple functions,
2966 @code{buffer-size}, @code{point}, @code{point-min}, and
2967 @code{point-max}. These give information about the size of a buffer and
2968 the location of point within it.
2969
2970 The function @code{buffer-size} tells you the size of the current
2971 buffer; that is, the function returns a count of the number of
2972 characters in the buffer.
2973
2974 @smallexample
2975 (buffer-size)
2976 @end smallexample
2977
2978 @noindent
2979 You can evaluate this in the usual way, by positioning the
2980 cursor after the expression and typing @kbd{C-x C-e}.
2981
2982 @cindex @samp{point} defined
2983 In Emacs, the current position of the cursor is called @dfn{point}.
2984 The expression @code{(point)} returns a number that tells you where the
2985 cursor is located as a count of the number of characters from the
2986 beginning of the buffer up to point.
2987
2988 @need 1250
2989 You can see the character count for point in this buffer by evaluating
2990 the following expression in the usual way:
2991
2992 @smallexample
2993 (point)
2994 @end smallexample
2995
2996 @noindent
2997 As I write this, the value of @code{point} is 65724. The @code{point}
2998 function is frequently used in some of the examples later in this
2999 book.
3000
3001 @need 1250
3002 The value of point depends, of course, on its location within the
3003 buffer. If you evaluate point in this spot, the number will be larger:
3004
3005 @smallexample
3006 (point)
3007 @end smallexample
3008
3009 @noindent
3010 For me, the value of point in this location is 66043, which means that
3011 there are 319 characters (including spaces) between the two
3012 expressions. (Doubtless, you will see different numbers, since I will
3013 have edited this since I first evaluated point.)
3014
3015 @cindex @samp{narrowing} defined
3016 The function @code{point-min} is somewhat similar to @code{point}, but
3017 it returns the value of the minimum permissible value of point in the
3018 current buffer. This is the number 1 unless @dfn{narrowing} is in
3019 effect. (Narrowing is a mechanism whereby you can restrict yourself,
3020 or a program, to operations on just a part of a buffer.
3021 @xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the
3022 function @code{point-max} returns the value of the maximum permissible
3023 value of point in the current buffer.
3024
3025 @node Evaluation Exercise
3026 @section Exercise
3027
3028 Find a file with which you are working and move towards its middle.
3029 Find its buffer name, file name, length, and your position in the file.
3030
3031 @node Writing Defuns
3032 @chapter How To Write Function Definitions
3033 @cindex Definition writing
3034 @cindex Function definition writing
3035 @cindex Writing a function definition
3036
3037 When the Lisp interpreter evaluates a list, it looks to see whether the
3038 first symbol on the list has a function definition attached to it; or,
3039 put another way, whether the symbol points to a function definition. If
3040 it does, the computer carries out the instructions in the definition. A
3041 symbol that has a function definition is called, simply, a function
3042 (although, properly speaking, the definition is the function and the
3043 symbol refers to it.)
3044
3045 @menu
3046 * Primitive Functions::
3047 * defun:: The @code{defun} special form.
3048 * Install:: Install a function definition.
3049 * Interactive:: Making a function interactive.
3050 * Interactive Options:: Different options for @code{interactive}.
3051 * Permanent Installation:: Installing code permanently.
3052 * let:: Creating and initializing local variables.
3053 * if:: What if?
3054 * else:: If--then--else expressions.
3055 * Truth & Falsehood:: What Lisp considers false and true.
3056 * save-excursion:: Keeping track of point, mark, and buffer.
3057 * Review::
3058 * defun Exercises::
3059 @end menu
3060
3061 @ifnottex
3062 @node Primitive Functions
3063 @unnumberedsec An Aside about Primitive Functions
3064 @end ifnottex
3065 @cindex Primitive functions
3066 @cindex Functions, primitive
3067
3068 @cindex C language primitives
3069 @cindex Primitives written in C
3070 All functions are defined in terms of other functions, except for a few
3071 @dfn{primitive} functions that are written in the C programming
3072 language. When you write functions' definitions, you will write them in
3073 Emacs Lisp and use other functions as your building blocks. Some of the
3074 functions you will use will themselves be written in Emacs Lisp (perhaps
3075 by you) and some will be primitives written in C. The primitive
3076 functions are used exactly like those written in Emacs Lisp and behave
3077 like them. They are written in C so we can easily run GNU Emacs on any
3078 computer that has sufficient power and can run C.
3079
3080 Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3081 distinguish between the use of functions written in C and the use of
3082 functions written in Emacs Lisp. The difference is irrelevant. I
3083 mention the distinction only because it is interesting to know. Indeed,
3084 unless you investigate, you won't know whether an already-written
3085 function is written in Emacs Lisp or C.
3086
3087 @node defun
3088 @section The @code{defun} Special Form
3089 @findex defun
3090 @cindex Special form of @code{defun}
3091
3092 @cindex @samp{function definition} defined
3093 In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3094 it that tells the computer what to do when the function is called.
3095 This code is called the @dfn{function definition} and is created by
3096 evaluating a Lisp expression that starts with the symbol @code{defun}
3097 (which is an abbreviation for @emph{define function}). Because
3098 @code{defun} does not evaluate its arguments in the usual way, it is
3099 called a @dfn{special form}.
3100
3101 In subsequent sections, we will look at function definitions from the
3102 Emacs source code, such as @code{mark-whole-buffer}. In this section,
3103 we will describe a simple function definition so you can see how it
3104 looks. This function definition uses arithmetic because it makes for a
3105 simple example. Some people dislike examples using arithmetic; however,
3106 if you are such a person, do not despair. Hardly any of the code we
3107 will study in the remainder of this introduction involves arithmetic or
3108 mathematics. The examples mostly involve text in one way or another.
3109
3110 A function definition has up to five parts following the word
3111 @code{defun}:
3112
3113 @enumerate
3114 @item
3115 The name of the symbol to which the function definition should be
3116 attached.
3117
3118 @item
3119 A list of the arguments that will be passed to the function. If no
3120 arguments will be passed to the function, this is an empty list,
3121 @code{()}.
3122
3123 @item
3124 Documentation describing the function. (Technically optional, but
3125 strongly recommended.)
3126
3127 @item
3128 Optionally, an expression to make the function interactive so you can
3129 use it by typing @kbd{M-x} and then the name of the function; or by
3130 typing an appropriate key or keychord.
3131
3132 @cindex @samp{body} defined
3133 @item
3134 The code that instructs the computer what to do: the @dfn{body} of the
3135 function definition.
3136 @end enumerate
3137
3138 It is helpful to think of the five parts of a function definition as
3139 being organized in a template, with slots for each part:
3140
3141 @smallexample
3142 @group
3143 (defun @var{function-name} (@var{arguments}@dots{})
3144 "@var{optional-documentation}@dots{}"
3145 (interactive @var{argument-passing-info}) ; @r{optional}
3146 @var{body}@dots{})
3147 @end group
3148 @end smallexample
3149
3150 As an example, here is the code for a function that multiplies its
3151 argument by 7. (This example is not interactive. @xref{Interactive,
3152 , Making a Function Interactive}, for that information.)
3153
3154 @smallexample
3155 @group
3156 (defun multiply-by-seven (number)
3157 "Multiply NUMBER by seven."
3158 (* 7 number))
3159 @end group
3160 @end smallexample
3161
3162 This definition begins with a parenthesis and the symbol @code{defun},
3163 followed by the name of the function.
3164
3165 @cindex @samp{argument list} defined
3166 The name of the function is followed by a list that contains the
3167 arguments that will be passed to the function. This list is called
3168 the @dfn{argument list}. In this example, the list has only one
3169 element, the symbol, @code{number}. When the function is used, the
3170 symbol will be bound to the value that is used as the argument to the
3171 function.
3172
3173 Instead of choosing the word @code{number} for the name of the argument,
3174 I could have picked any other name. For example, I could have chosen
3175 the word @code{multiplicand}. I picked the word `number' because it
3176 tells what kind of value is intended for this slot; but I could just as
3177 well have chosen the word `multiplicand' to indicate the role that the
3178 value placed in this slot will play in the workings of the function. I
3179 could have called it @code{foogle}, but that would have been a bad
3180 choice because it would not tell humans what it means. The choice of
3181 name is up to the programmer and should be chosen to make the meaning of
3182 the function clear.
3183
3184 Indeed, you can choose any name you wish for a symbol in an argument
3185 list, even the name of a symbol used in some other function: the name
3186 you use in an argument list is private to that particular definition.
3187 In that definition, the name refers to a different entity than any use
3188 of the same name outside the function definition. Suppose you have a
3189 nick-name `Shorty' in your family; when your family members refer to
3190 `Shorty', they mean you. But outside your family, in a movie, for
3191 example, the name `Shorty' refers to someone else. Because a name in an
3192 argument list is private to the function definition, you can change the
3193 value of such a symbol inside the body of a function without changing
3194 its value outside the function. The effect is similar to that produced
3195 by a @code{let} expression. (@xref{let, , @code{let}}.)
3196
3197 @ignore
3198 Note also that we discuss the word `number' in two different ways: as a
3199 symbol that appears in the code, and as the name of something that will
3200 be replaced by a something else during the evaluation of the function.
3201 In the first case, @code{number} is a symbol, not a number; it happens
3202 that within the function, it is a variable who value is the number in
3203 question, but our primary interest in it is as a symbol. On the other
3204 hand, when we are talking about the function, our interest is that we
3205 will substitute a number for the word @var{number}. To keep this
3206 distinction clear, we use different typography for the two
3207 circumstances. When we talk about this function, or about how it works,
3208 we refer to this number by writing @var{number}. In the function
3209 itself, we refer to it by writing @code{number}.
3210 @end ignore
3211
3212 The argument list is followed by the documentation string that
3213 describes the function. This is what you see when you type
3214 @w{@kbd{C-h f}} and the name of a function. Incidentally, when you
3215 write a documentation string like this, you should make the first line
3216 a complete sentence since some commands, such as @code{apropos}, print
3217 only the first line of a multi-line documentation string. Also, you
3218 should not indent the second line of a documentation string, if you
3219 have one, because that looks odd when you use @kbd{C-h f}
3220 (@code{describe-function}). The documentation string is optional, but
3221 it is so useful, it should be included in almost every function you
3222 write.
3223
3224 @findex * @r{(multiplication)}
3225 The third line of the example consists of the body of the function
3226 definition. (Most functions' definitions, of course, are longer than
3227 this.) In this function, the body is the list, @code{(* 7 number)}, which
3228 says to multiply the value of @var{number} by 7. (In Emacs Lisp,
3229 @code{*} is the function for multiplication, just as @code{+} is the
3230 function for addition.)
3231
3232 When you use the @code{multiply-by-seven} function, the argument
3233 @code{number} evaluates to the actual number you want used. Here is an
3234 example that shows how @code{multiply-by-seven} is used; but don't try
3235 to evaluate this yet!
3236
3237 @smallexample
3238 (multiply-by-seven 3)
3239 @end smallexample
3240
3241 @noindent
3242 The symbol @code{number}, specified in the function definition in the
3243 next section, is given or ``bound to'' the value 3 in the actual use of
3244 the function. Note that although @code{number} was inside parentheses
3245 in the function definition, the argument passed to the
3246 @code{multiply-by-seven} function is not in parentheses. The
3247 parentheses are written in the function definition so the computer can
3248 figure out where the argument list ends and the rest of the function
3249 definition begins.
3250
3251 If you evaluate this example, you are likely to get an error message.
3252 (Go ahead, try it!) This is because we have written the function
3253 definition, but not yet told the computer about the definition---we have
3254 not yet installed (or `loaded') the function definition in Emacs.
3255 Installing a function is the process that tells the Lisp interpreter the
3256 definition of the function. Installation is described in the next
3257 section.
3258
3259 @node Install
3260 @section Install a Function Definition
3261 @cindex Install a Function Definition
3262 @cindex Definition installation
3263 @cindex Function definition installation
3264
3265 If you are reading this inside of Info in Emacs, you can try out the
3266 @code{multiply-by-seven} function by first evaluating the function
3267 definition and then evaluating @code{(multiply-by-seven 3)}. A copy of
3268 the function definition follows. Place the cursor after the last
3269 parenthesis of the function definition and type @kbd{C-x C-e}. When you
3270 do this, @code{multiply-by-seven} will appear in the echo area. (What
3271 this means is that when a function definition is evaluated, the value it
3272 returns is the name of the defined function.) At the same time, this
3273 action installs the function definition.
3274
3275 @smallexample
3276 @group
3277 (defun multiply-by-seven (number)
3278 "Multiply NUMBER by seven."
3279 (* 7 number))
3280 @end group
3281 @end smallexample
3282
3283 @noindent
3284 By evaluating this @code{defun}, you have just installed
3285 @code{multiply-by-seven} in Emacs. The function is now just as much a
3286 part of Emacs as @code{forward-word} or any other editing function you
3287 use. (@code{multiply-by-seven} will stay installed until you quit
3288 Emacs. To reload code automatically whenever you start Emacs, see
3289 @ref{Permanent Installation, , Installing Code Permanently}.)
3290
3291 @menu
3292 * Effect of installation::
3293 * Change a defun:: How to change a function definition.
3294 @end menu
3295
3296 @ifnottex
3297 @node Effect of installation
3298 @unnumberedsubsec The effect of installation
3299 @end ifnottex
3300
3301 You can see the effect of installing @code{multiply-by-seven} by
3302 evaluating the following sample. Place the cursor after the following
3303 expression and type @kbd{C-x C-e}. The number 21 will appear in the
3304 echo area.
3305
3306 @smallexample
3307 (multiply-by-seven 3)
3308 @end smallexample
3309
3310 If you wish, you can read the documentation for the function by typing
3311 @kbd{C-h f} (@code{describe-function}) and then the name of the
3312 function, @code{multiply-by-seven}. When you do this, a
3313 @file{*Help*} window will appear on your screen that says:
3314
3315 @smallexample
3316 @group
3317 multiply-by-seven is a Lisp function.
3318 (multiply-by-seven NUMBER)
3319
3320 Multiply NUMBER by seven.
3321 @end group
3322 @end smallexample
3323
3324 @noindent
3325 (To return to a single window on your screen, type @kbd{C-x 1}.)
3326
3327 @node Change a defun
3328 @subsection Change a Function Definition
3329 @cindex Changing a function definition
3330 @cindex Function definition, how to change
3331 @cindex Definition, how to change
3332
3333 If you want to change the code in @code{multiply-by-seven}, just rewrite
3334 it. To install the new version in place of the old one, evaluate the
3335 function definition again. This is how you modify code in Emacs. It is
3336 very simple.
3337
3338 As an example, you can change the @code{multiply-by-seven} function to
3339 add the number to itself seven times instead of multiplying the number
3340 by seven. It produces the same answer, but by a different path. At
3341 the same time, we will add a comment to the code; a comment is text
3342 that the Lisp interpreter ignores, but that a human reader may find
3343 useful or enlightening. The comment is that this is the ``second
3344 version''.
3345
3346 @smallexample
3347 @group
3348 (defun multiply-by-seven (number) ; @r{Second version.}
3349 "Multiply NUMBER by seven."
3350 (+ number number number number number number number))
3351 @end group
3352 @end smallexample
3353
3354 @cindex Comments in Lisp code
3355 The comment follows a semicolon, @samp{;}. In Lisp, everything on a
3356 line that follows a semicolon is a comment. The end of the line is the
3357 end of the comment. To stretch a comment over two or more lines, begin
3358 each line with a semicolon.
3359
3360 @xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3361 File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3362 Reference Manual}, for more about comments.
3363
3364 You can install this version of the @code{multiply-by-seven} function by
3365 evaluating it in the same way you evaluated the first function: place
3366 the cursor after the last parenthesis and type @kbd{C-x C-e}.
3367
3368 In summary, this is how you write code in Emacs Lisp: you write a
3369 function; install it; test it; and then make fixes or enhancements and
3370 install it again.
3371
3372 @node Interactive
3373 @section Make a Function Interactive
3374 @cindex Interactive functions
3375 @findex interactive
3376
3377 You make a function interactive by placing a list that begins with
3378 the special form @code{interactive} immediately after the
3379 documentation. A user can invoke an interactive function by typing
3380 @kbd{M-x} and then the name of the function; or by typing the keys to
3381 which it is bound, for example, by typing @kbd{C-n} for
3382 @code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3383
3384 Interestingly, when you call an interactive function interactively,
3385 the value returned is not automatically displayed in the echo area.
3386 This is because you often call an interactive function for its side
3387 effects, such as moving forward by a word or line, and not for the
3388 value returned. If the returned value were displayed in the echo area
3389 each time you typed a key, it would be very distracting.
3390
3391 @menu
3392 * Interactive multiply-by-seven:: An overview.
3393 * multiply-by-seven in detail:: The interactive version.
3394 @end menu
3395
3396 @ifnottex
3397 @node Interactive multiply-by-seven
3398 @unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3399 @end ifnottex
3400
3401 Both the use of the special form @code{interactive} and one way to
3402 display a value in the echo area can be illustrated by creating an
3403 interactive version of @code{multiply-by-seven}.
3404
3405 @need 1250
3406 Here is the code:
3407
3408 @smallexample
3409 @group
3410 (defun multiply-by-seven (number) ; @r{Interactive version.}
3411 "Multiply NUMBER by seven."
3412 (interactive "p")
3413 (message "The result is %d" (* 7 number)))
3414 @end group
3415 @end smallexample
3416
3417 @noindent
3418 You can install this code by placing your cursor after it and typing
3419 @kbd{C-x C-e}. The name of the function will appear in your echo area.
3420 Then, you can use this code by typing @kbd{C-u} and a number and then
3421 typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase
3422 @samp{The result is @dots{}} followed by the product will appear in the
3423 echo area.
3424
3425 Speaking more generally, you invoke a function like this in either of two
3426 ways:
3427
3428 @enumerate
3429 @item
3430 By typing a prefix argument that contains the number to be passed, and
3431 then typing @kbd{M-x} and the name of the function, as with
3432 @kbd{C-u 3 M-x forward-sentence}; or,
3433
3434 @item
3435 By typing whatever key or keychord the function is bound to, as with
3436 @kbd{C-u 3 M-e}.
3437 @end enumerate
3438
3439 @noindent
3440 Both the examples just mentioned work identically to move point forward
3441 three sentences. (Since @code{multiply-by-seven} is not bound to a key,
3442 it could not be used as an example of key binding.)
3443
3444 (@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3445 to a key.)
3446
3447 A prefix argument is passed to an interactive function by typing the
3448 @key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3449 typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3450 type @kbd{C-u} without a number, it defaults to 4).
3451
3452 @node multiply-by-seven in detail
3453 @subsection An Interactive @code{multiply-by-seven}
3454
3455 Let's look at the use of the special form @code{interactive} and then at
3456 the function @code{message} in the interactive version of
3457 @code{multiply-by-seven}. You will recall that the function definition
3458 looks like this:
3459
3460 @smallexample
3461 @group
3462 (defun multiply-by-seven (number) ; @r{Interactive version.}
3463 "Multiply NUMBER by seven."
3464 (interactive "p")
3465 (message "The result is %d" (* 7 number)))
3466 @end group
3467 @end smallexample
3468
3469 In this function, the expression, @code{(interactive "p")}, is a list of
3470 two elements. The @code{"p"} tells Emacs to pass the prefix argument to
3471 the function and use its value for the argument of the function.
3472
3473 @need 1000
3474 The argument will be a number. This means that the symbol
3475 @code{number} will be bound to a number in the line:
3476
3477 @smallexample
3478 (message "The result is %d" (* 7 number))
3479 @end smallexample
3480
3481 @need 1250
3482 @noindent
3483 For example, if your prefix argument is 5, the Lisp interpreter will
3484 evaluate the line as if it were:
3485
3486 @smallexample
3487 (message "The result is %d" (* 7 5))
3488 @end smallexample
3489
3490 @noindent
3491 (If you are reading this in GNU Emacs, you can evaluate this expression
3492 yourself.) First, the interpreter will evaluate the inner list, which
3493 is @code{(* 7 5)}. This returns a value of 35. Next, it
3494 will evaluate the outer list, passing the values of the second and
3495 subsequent elements of the list to the function @code{message}.
3496
3497 As we have seen, @code{message} is an Emacs Lisp function especially
3498 designed for sending a one line message to a user. (@xref{message, ,
3499 The @code{message} function}.) In summary, the @code{message}
3500 function prints its first argument in the echo area as is, except for
3501 occurrences of @samp{%d} or @samp{%s} (and various other %-sequences
3502 which we have not mentioned). When it sees a control sequence, the
3503 function looks to the second or subsequent arguments and prints the
3504 value of the argument in the location in the string where the control
3505 sequence is located.
3506
3507 In the interactive @code{multiply-by-seven} function, the control string
3508 is @samp{%d}, which requires a number, and the value returned by
3509 evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35
3510 is printed in place of the @samp{%d} and the message is @samp{The result
3511 is 35}.
3512
3513 (Note that when you call the function @code{multiply-by-seven}, the
3514 message is printed without quotes, but when you call @code{message}, the
3515 text is printed in double quotes. This is because the value returned by
3516 @code{message} is what appears in the echo area when you evaluate an
3517 expression whose first element is @code{message}; but when embedded in a
3518 function, @code{message} prints the text as a side effect without
3519 quotes.)
3520
3521 @node Interactive Options
3522 @section Different Options for @code{interactive}
3523 @cindex Options for @code{interactive}
3524 @cindex Interactive options
3525
3526 In the example, @code{multiply-by-seven} used @code{"p"} as the
3527 argument to @code{interactive}. This argument told Emacs to interpret
3528 your typing either @kbd{C-u} followed by a number or @key{META}
3529 followed by a number as a command to pass that number to the function
3530 as its argument. Emacs has more than twenty characters predefined for
3531 use with @code{interactive}. In almost every case, one of these
3532 options will enable you to pass the right information interactively to
3533 a function. (@xref{Interactive Codes, , Code Characters for
3534 @code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3535
3536 @need 1250
3537 Consider the function @code{zap-to-char}. Its interactive expression
3538 is
3539
3540 @smallexample
3541 (interactive "p\ncZap to char: ")
3542 @end smallexample
3543
3544 The first part of the argument to @code{interactive} is @samp{p}, with
3545 which you are already familiar. This argument tells Emacs to
3546 interpret a `prefix', as a number to be passed to the function. You
3547 can specify a prefix either by typing @kbd{C-u} followed by a number
3548 or by typing @key{META} followed by a number. The prefix is the
3549 number of specified characters. Thus, if your prefix is three and the
3550 specified character is @samp{x}, then you will delete all the text up
3551 to and including the third next @samp{x}. If you do not set a prefix,
3552 then you delete all the text up to and including the specified
3553 character, but no more.
3554
3555 The @samp{c} tells the function the name of the character to which to delete.
3556
3557 More formally, a function with two or more arguments can have
3558 information passed to each argument by adding parts to the string that
3559 follows @code{interactive}. When you do this, the information is
3560 passed to each argument in the same order it is specified in the
3561 @code{interactive} list. In the string, each part is separated from
3562 the next part by a @samp{\n}, which is a newline. For example, you
3563 can follow @samp{p} with a @samp{\n} and an @samp{cZap to char:@: }.
3564 This causes Emacs to pass the value of the prefix argument (if there
3565 is one) and the character.
3566
3567 In this case, the function definition looks like the following, where
3568 @code{arg} and @code{char} are the symbols to which @code{interactive}
3569 binds the prefix argument and the specified character:
3570
3571 @smallexample
3572 @group
3573 (defun @var{name-of-function} (arg char)
3574 "@var{documentation}@dots{}"
3575 (interactive "p\ncZap to char: ")
3576 @var{body-of-function}@dots{})
3577 @end group
3578 @end smallexample
3579
3580 @noindent
3581 (The space after the colon in the prompt makes it look better when you
3582 are prompted. @xref{copy-to-buffer, , The Definition of
3583 @code{copy-to-buffer}}, for an example.)
3584
3585 When a function does not take arguments, @code{interactive} does not
3586 require any. Such a function contains the simple expression
3587 @code{(interactive)}. The @code{mark-whole-buffer} function is like
3588 this.
3589
3590 Alternatively, if the special letter-codes are not right for your
3591 application, you can pass your own arguments to @code{interactive} as
3592 a list.
3593
3594 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}},
3595 for an example. @xref{Using Interactive, , Using @code{Interactive},
3596 elisp, The GNU Emacs Lisp Reference Manual}, for a more complete
3597 explanation about this technique.
3598
3599 @node Permanent Installation
3600 @section Install Code Permanently
3601 @cindex Install code permanently
3602 @cindex Permanent code installation
3603 @cindex Code installation
3604
3605 When you install a function definition by evaluating it, it will stay
3606 installed until you quit Emacs. The next time you start a new session
3607 of Emacs, the function will not be installed unless you evaluate the
3608 function definition again.
3609
3610 At some point, you may want to have code installed automatically
3611 whenever you start a new session of Emacs. There are several ways of
3612 doing this:
3613
3614 @itemize @bullet
3615 @item
3616 If you have code that is just for yourself, you can put the code for the
3617 function definition in your @file{.emacs} initialization file. When you
3618 start Emacs, your @file{.emacs} file is automatically evaluated and all
3619 the function definitions within it are installed.
3620 @xref{Emacs Initialization, , Your @file{.emacs} File}.
3621
3622 @item
3623 Alternatively, you can put the function definitions that you want
3624 installed in one or more files of their own and use the @code{load}
3625 function to cause Emacs to evaluate and thereby install each of the
3626 functions in the files.
3627 @xref{Loading Files, , Loading Files}.
3628
3629 @item
3630 Thirdly, if you have code that your whole site will use, it is usual
3631 to put it in a file called @file{site-init.el} that is loaded when
3632 Emacs is built. This makes the code available to everyone who uses
3633 your machine. (See the @file{INSTALL} file that is part of the Emacs
3634 distribution.)
3635 @end itemize
3636
3637 Finally, if you have code that everyone who uses Emacs may want, you
3638 can post it on a computer network or send a copy to the Free Software
3639 Foundation. (When you do this, please license the code and its
3640 documentation under a license that permits other people to run, copy,
3641 study, modify, and redistribute the code and which protects you from
3642 having your work taken from you.) If you send a copy of your code to
3643 the Free Software Foundation, and properly protect yourself and
3644 others, it may be included in the next release of Emacs. In large
3645 part, this is how Emacs has grown over the past years, by donations.
3646
3647 @node let
3648 @section @code{let}
3649 @findex let
3650
3651 The @code{let} expression is a special form in Lisp that you will need
3652 to use in most function definitions.
3653
3654 @code{let} is used to attach or bind a symbol to a value in such a way
3655 that the Lisp interpreter will not confuse the variable with a
3656 variable of the same name that is not part of the function.
3657
3658 To understand why the @code{let} special form is necessary, consider
3659 the situation in which you own a home that you generally refer to as
3660 `the house', as in the sentence, ``The house needs painting.'' If you
3661 are visiting a friend and your host refers to `the house', he is
3662 likely to be referring to @emph{his} house, not yours, that is, to a
3663 different house.
3664
3665 If your friend is referring to his house and you think he is referring
3666 to your house, you may be in for some confusion. The same thing could
3667 happen in Lisp if a variable that is used inside of one function has
3668 the same name as a variable that is used inside of another function,
3669 and the two are not intended to refer to the same value. The
3670 @code{let} special form prevents this kind of confusion.
3671
3672 @menu
3673 * Prevent confusion::
3674 * Parts of let Expression::
3675 * Sample let Expression::
3676 * Uninitialized let Variables::
3677 @end menu
3678
3679 @ifnottex
3680 @node Prevent confusion
3681 @unnumberedsubsec @code{let} Prevents Confusion
3682 @end ifnottex
3683
3684 @cindex @samp{local variable} defined
3685 @cindex @samp{variable, local}, defined
3686 The @code{let} special form prevents confusion. @code{let} creates a
3687 name for a @dfn{local variable} that overshadows any use of the same
3688 name outside the @code{let} expression. This is like understanding
3689 that whenever your host refers to `the house', he means his house, not
3690 yours. (Symbols used in argument lists work the same way.
3691 @xref{defun, , The @code{defun} Special Form}.)
3692
3693 Local variables created by a @code{let} expression retain their value
3694 @emph{only} within the @code{let} expression itself (and within
3695 expressions called within the @code{let} expression); the local
3696 variables have no effect outside the @code{let} expression.
3697
3698 Another way to think about @code{let} is that it is like a @code{setq}
3699 that is temporary and local. The values set by @code{let} are
3700 automatically undone when the @code{let} is finished. The setting
3701 only affects expressions that are inside the bounds of the @code{let}
3702 expression. In computer science jargon, we would say ``the binding of
3703 a symbol is visible only in functions called in the @code{let} form;
3704 in Emacs Lisp, scoping is dynamic, not lexical.''
3705
3706 @code{let} can create more than one variable at once. Also,
3707 @code{let} gives each variable it creates an initial value, either a
3708 value specified by you, or @code{nil}. (In the jargon, this is called
3709 `binding the variable to the value'.) After @code{let} has created
3710 and bound the variables, it executes the code in the body of the
3711 @code{let}, and returns the value of the last expression in the body,
3712 as the value of the whole @code{let} expression. (`Execute' is a jargon
3713 term that means to evaluate a list; it comes from the use of the word
3714 meaning `to give practical effect to' (@cite{Oxford English
3715 Dictionary}). Since you evaluate an expression to perform an action,
3716 `execute' has evolved as a synonym to `evaluate'.)
3717
3718 @node Parts of let Expression
3719 @subsection The Parts of a @code{let} Expression
3720 @cindex @code{let} expression, parts of
3721 @cindex Parts of @code{let} expression
3722
3723 @cindex @samp{varlist} defined
3724 A @code{let} expression is a list of three parts. The first part is
3725 the symbol @code{let}. The second part is a list, called a
3726 @dfn{varlist}, each element of which is either a symbol by itself or a
3727 two-element list, the first element of which is a symbol. The third
3728 part of the @code{let} expression is the body of the @code{let}. The
3729 body usually consists of one or more lists.
3730
3731 @need 800
3732 A template for a @code{let} expression looks like this:
3733
3734 @smallexample
3735 (let @var{varlist} @var{body}@dots{})
3736 @end smallexample
3737
3738 @noindent
3739 The symbols in the varlist are the variables that are given initial
3740 values by the @code{let} special form. Symbols by themselves are given
3741 the initial value of @code{nil}; and each symbol that is the first
3742 element of a two-element list is bound to the value that is returned
3743 when the Lisp interpreter evaluates the second element.
3744
3745 Thus, a varlist might look like this: @code{(thread (needles 3))}. In
3746 this case, in a @code{let} expression, Emacs binds the symbol
3747 @code{thread} to an initial value of @code{nil}, and binds the symbol
3748 @code{needles} to an initial value of 3.
3749
3750 When you write a @code{let} expression, what you do is put the
3751 appropriate expressions in the slots of the @code{let} expression
3752 template.
3753
3754 If the varlist is composed of two-element lists, as is often the case,
3755 the template for the @code{let} expression looks like this:
3756
3757 @smallexample
3758 @group
3759 (let ((@var{variable} @var{value})
3760 (@var{variable} @var{value})
3761 @dots{})
3762 @var{body}@dots{})
3763 @end group
3764 @end smallexample
3765
3766 @node Sample let Expression
3767 @subsection Sample @code{let} Expression
3768 @cindex Sample @code{let} expression
3769 @cindex @code{let} expression sample
3770
3771 The following expression creates and gives initial values
3772 to the two variables @code{zebra} and @code{tiger}. The body of the
3773 @code{let} expression is a list which calls the @code{message} function.
3774
3775 @smallexample
3776 @group
3777 (let ((zebra 'stripes)
3778 (tiger 'fierce))
3779 (message "One kind of animal has %s and another is %s."
3780 zebra tiger))
3781 @end group
3782 @end smallexample
3783
3784 Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3785
3786 The two variables are @code{zebra} and @code{tiger}. Each variable is
3787 the first element of a two-element list and each value is the second
3788 element of its two-element list. In the varlist, Emacs binds the
3789 variable @code{zebra} to the value @code{stripes}@footnote{According
3790 to Jared Diamond in @cite{Guns, Germs, and Steel}, ``@dots{} zebras
3791 become impossibly dangerous as they grow older'' but the claim here is
3792 that they do not become fierce like a tiger. (1997, W. W. Norton and
3793 Co., ISBN 0-393-03894-2, page 171)}, and binds the
3794 variable @code{tiger} to the value @code{fierce}. In this example,
3795 both values are symbols preceded by a quote. The values could just as
3796 well have been another list or a string. The body of the @code{let}
3797 follows after the list holding the variables. In this example, the
3798 body is a list that uses the @code{message} function to print a string
3799 in the echo area.
3800
3801 @need 1500
3802 You may evaluate the example in the usual fashion, by placing the
3803 cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do
3804 this, the following will appear in the echo area:
3805
3806 @smallexample
3807 "One kind of animal has stripes and another is fierce."
3808 @end smallexample
3809
3810 As we have seen before, the @code{message} function prints its first
3811 argument, except for @samp{%s}. In this example, the value of the variable
3812 @code{zebra} is printed at the location of the first @samp{%s} and the
3813 value of the variable @code{tiger} is printed at the location of the
3814 second @samp{%s}.
3815
3816 @node Uninitialized let Variables
3817 @subsection Uninitialized Variables in a @code{let} Statement
3818 @cindex Uninitialized @code{let} variables
3819 @cindex @code{let} variables uninitialized
3820
3821 If you do not bind the variables in a @code{let} statement to specific
3822 initial values, they will automatically be bound to an initial value of
3823 @code{nil}, as in the following expression:
3824
3825 @smallexample
3826 @group
3827 (let ((birch 3)
3828 pine
3829 fir
3830 (oak 'some))
3831 (message
3832 "Here are %d variables with %s, %s, and %s value."
3833 birch pine fir oak))
3834 @end group
3835 @end smallexample
3836
3837 @noindent
3838 Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3839
3840 @need 1250
3841 If you evaluate this expression in the usual way, the following will
3842 appear in your echo area:
3843
3844 @smallexample
3845 "Here are 3 variables with nil, nil, and some value."
3846 @end smallexample
3847
3848 @noindent
3849 In this example, Emacs binds the symbol @code{birch} to the number 3,
3850 binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3851 the symbol @code{oak} to the value @code{some}.
3852
3853 Note that in the first part of the @code{let}, the variables @code{pine}
3854 and @code{fir} stand alone as atoms that are not surrounded by
3855 parentheses; this is because they are being bound to @code{nil}, the
3856 empty list. But @code{oak} is bound to @code{some} and so is a part of
3857 the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the
3858 number 3 and so is in a list with that number. (Since a number
3859 evaluates to itself, the number does not need to be quoted. Also, the
3860 number is printed in the message using a @samp{%d} rather than a
3861 @samp{%s}.) The four variables as a group are put into a list to
3862 delimit them from the body of the @code{let}.
3863
3864 @node if
3865 @section The @code{if} Special Form
3866 @findex if
3867 @cindex Conditional with @code{if}
3868
3869 A third special form, in addition to @code{defun} and @code{let}, is the
3870 conditional @code{if}. This form is used to instruct the computer to
3871 make decisions. You can write function definitions without using
3872 @code{if}, but it is used often enough, and is important enough, to be
3873 included here. It is used, for example, in the code for the
3874 function @code{beginning-of-buffer}.
3875
3876 The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3877 @emph{then} an expression is evaluated.'' If the test is not true, the
3878 expression is not evaluated. For example, you might make a decision
3879 such as, ``if it is warm and sunny, then go to the beach!''
3880
3881 @menu
3882 * if in more detail::
3883 * type-of-animal in detail:: An example of an @code{if} expression.
3884 @end menu
3885
3886 @ifnottex
3887 @node if in more detail
3888 @unnumberedsubsec @code{if} in more detail
3889 @end ifnottex
3890
3891 @cindex @samp{if-part} defined
3892 @cindex @samp{then-part} defined
3893 An @code{if} expression written in Lisp does not use the word `then';
3894 the test and the action are the second and third elements of the list
3895 whose first element is @code{if}. Nonetheless, the test part of an
3896 @code{if} expression is often called the @dfn{if-part} and the second
3897 argument is often called the @dfn{then-part}.
3898
3899 Also, when an @code{if} expression is written, the true-or-false-test
3900 is usually written on the same line as the symbol @code{if}, but the
3901 action to carry out if the test is true, the ``then-part'', is written
3902 on the second and subsequent lines. This makes the @code{if}
3903 expression easier to read.
3904
3905 @smallexample
3906 @group
3907 (if @var{true-or-false-test}
3908 @var{action-to-carry-out-if-test-is-true})
3909 @end group
3910 @end smallexample
3911
3912 @noindent
3913 The true-or-false-test will be an expression that
3914 is evaluated by the Lisp interpreter.
3915
3916 Here is an example that you can evaluate in the usual manner. The test
3917 is whether the number 5 is greater than the number 4. Since it is, the
3918 message @samp{5 is greater than 4!} will be printed.
3919
3920 @smallexample
3921 @group
3922 (if (> 5 4) ; @r{if-part}
3923 (message "5 is greater than 4!")) ; @r{then-part}
3924 @end group
3925 @end smallexample
3926
3927 @noindent
3928 (The function @code{>} tests whether its first argument is greater than
3929 its second argument and returns true if it is.)
3930 @findex > (greater than)
3931
3932 Of course, in actual use, the test in an @code{if} expression will not
3933 be fixed for all time as it is by the expression @code{(> 5 4)}.
3934 Instead, at least one of the variables used in the test will be bound to
3935 a value that is not known ahead of time. (If the value were known ahead
3936 of time, we would not need to run the test!)
3937
3938 For example, the value may be bound to an argument of a function
3939 definition. In the following function definition, the character of the
3940 animal is a value that is passed to the function. If the value bound to
3941 @code{characteristic} is @code{fierce}, then the message, @samp{It's a
3942 tiger!} will be printed; otherwise, @code{nil} will be returned.
3943
3944 @smallexample
3945 @group
3946 (defun type-of-animal (characteristic)
3947 "Print message in echo area depending on CHARACTERISTIC.
3948 If the CHARACTERISTIC is the symbol `fierce',
3949 then warn of a tiger."
3950 (if (equal characteristic 'fierce)
3951 (message "It's a tiger!")))
3952 @end group
3953 @end smallexample
3954
3955 @need 1500
3956 @noindent
3957 If you are reading this inside of GNU Emacs, you can evaluate the
3958 function definition in the usual way to install it in Emacs, and then you
3959 can evaluate the following two expressions to see the results:
3960
3961 @smallexample
3962 @group
3963 (type-of-animal 'fierce)
3964
3965 (type-of-animal 'zebra)
3966
3967 @end group
3968 @end smallexample
3969
3970 @c Following sentences rewritten to prevent overfull hbox.
3971 @noindent
3972 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3973 following message printed in the echo area: @code{"It's a tiger!"}; and
3974 when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3975 printed in the echo area.
3976
3977 @node type-of-animal in detail
3978 @subsection The @code{type-of-animal} Function in Detail
3979
3980 Let's look at the @code{type-of-animal} function in detail.
3981
3982 The function definition for @code{type-of-animal} was written by filling
3983 the slots of two templates, one for a function definition as a whole, and
3984 a second for an @code{if} expression.
3985
3986 @need 1250
3987 The template for every function that is not interactive is:
3988
3989 @smallexample
3990 @group
3991 (defun @var{name-of-function} (@var{argument-list})
3992 "@var{documentation}@dots{}"
3993 @var{body}@dots{})
3994 @end group
3995 @end smallexample
3996
3997 @need 800
3998 The parts of the function that match this template look like this:
3999
4000 @smallexample
4001 @group
4002 (defun type-of-animal (characteristic)
4003 "Print message in echo area depending on CHARACTERISTIC.
4004 If the CHARACTERISTIC is the symbol `fierce',
4005 then warn of a tiger."
4006 @var{body: the} @code{if} @var{expression})
4007 @end group
4008 @end smallexample
4009
4010 The name of function is @code{type-of-animal}; it is passed the value
4011 of one argument. The argument list is followed by a multi-line
4012 documentation string. The documentation string is included in the
4013 example because it is a good habit to write documentation string for
4014 every function definition. The body of the function definition
4015 consists of the @code{if} expression.
4016
4017 @need 800
4018 The template for an @code{if} expression looks like this:
4019
4020 @smallexample
4021 @group
4022 (if @var{true-or-false-test}
4023 @var{action-to-carry-out-if-the-test-returns-true})
4024 @end group
4025 @end smallexample
4026
4027 @need 1250
4028 In the @code{type-of-animal} function, the code for the @code{if}
4029 looks like this:
4030
4031 @smallexample
4032 @group
4033 (if (equal characteristic 'fierce)
4034 (message "It's a tiger!")))
4035 @end group
4036 @end smallexample
4037
4038 @need 800
4039 Here, the true-or-false-test is the expression:
4040
4041 @smallexample
4042 (equal characteristic 'fierce)
4043 @end smallexample
4044
4045 @noindent
4046 In Lisp, @code{equal} is a function that determines whether its first
4047 argument is equal to its second argument. The second argument is the
4048 quoted symbol @code{'fierce} and the first argument is the value of the
4049 symbol @code{characteristic}---in other words, the argument passed to
4050 this function.
4051
4052 In the first exercise of @code{type-of-animal}, the argument
4053 @code{fierce} is passed to @code{type-of-animal}. Since @code{fierce}
4054 is equal to @code{fierce}, the expression, @code{(equal characteristic
4055 'fierce)}, returns a value of true. When this happens, the @code{if}
4056 evaluates the second argument or then-part of the @code{if}:
4057 @code{(message "It's tiger!")}.
4058
4059 On the other hand, in the second exercise of @code{type-of-animal}, the
4060 argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra}
4061 is not equal to @code{fierce}, so the then-part is not evaluated and
4062 @code{nil} is returned by the @code{if} expression.
4063
4064 @node else
4065 @section If--then--else Expressions
4066 @cindex Else
4067
4068 An @code{if} expression may have an optional third argument, called
4069 the @dfn{else-part}, for the case when the true-or-false-test returns
4070 false. When this happens, the second argument or then-part of the
4071 overall @code{if} expression is @emph{not} evaluated, but the third or
4072 else-part @emph{is} evaluated. You might think of this as the cloudy
4073 day alternative for the decision ``if it is warm and sunny, then go to
4074 the beach, else read a book!''.
4075
4076 The word ``else'' is not written in the Lisp code; the else-part of an
4077 @code{if} expression comes after the then-part. In the written Lisp, the
4078 else-part is usually written to start on a line of its own and is
4079 indented less than the then-part:
4080
4081 @smallexample
4082 @group
4083 (if @var{true-or-false-test}
4084 @var{action-to-carry-out-if-the-test-returns-true}
4085 @var{action-to-carry-out-if-the-test-returns-false})
4086 @end group
4087 @end smallexample
4088
4089 For example, the following @code{if} expression prints the message @samp{4
4090 is not greater than 5!} when you evaluate it in the usual way:
4091
4092 @smallexample
4093 @group
4094 (if (> 4 5) ; @r{if-part}
4095 (message "4 falsely greater than 5!") ; @r{then-part}
4096 (message "4 is not greater than 5!")) ; @r{else-part}
4097 @end group
4098 @end smallexample
4099
4100 @noindent
4101 Note that the different levels of indentation make it easy to
4102 distinguish the then-part from the else-part. (GNU Emacs has several
4103 commands that automatically indent @code{if} expressions correctly.
4104 @xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4105
4106 We can extend the @code{type-of-animal} function to include an
4107 else-part by simply incorporating an additional part to the @code{if}
4108 expression.
4109
4110 @need 1500
4111 You can see the consequences of doing this if you evaluate the following
4112 version of the @code{type-of-animal} function definition to install it
4113 and then evaluate the two subsequent expressions to pass different
4114 arguments to the function.
4115
4116 @smallexample
4117 @group
4118 (defun type-of-animal (characteristic) ; @r{Second version.}
4119 "Print message in echo area depending on CHARACTERISTIC.
4120 If the CHARACTERISTIC is the symbol `fierce',
4121 then warn of a tiger;
4122 else say it's not fierce."
4123 (if (equal characteristic 'fierce)
4124 (message "It's a tiger!")
4125 (message "It's not fierce!")))
4126 @end group
4127 @end smallexample
4128 @sp 1
4129
4130 @smallexample
4131 @group
4132 (type-of-animal 'fierce)
4133
4134 (type-of-animal 'zebra)
4135
4136 @end group
4137 @end smallexample
4138
4139 @c Following sentence rewritten to prevent overfull hbox.
4140 @noindent
4141 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4142 following message printed in the echo area: @code{"It's a tiger!"}; but
4143 when you evaluate @code{(type-of-animal 'zebra)}, you will see
4144 @code{"It's not fierce!"}.
4145
4146 (Of course, if the @var{characteristic} were @code{ferocious}, the
4147 message @code{"It's not fierce!"} would be printed; and it would be
4148 misleading! When you write code, you need to take into account the
4149 possibility that some such argument will be tested by the @code{if}
4150 and write your program accordingly.)
4151
4152 @node Truth & Falsehood
4153 @section Truth and Falsehood in Emacs Lisp
4154 @cindex Truth and falsehood in Emacs Lisp
4155 @cindex Falsehood and truth in Emacs Lisp
4156 @findex nil
4157
4158 There is an important aspect to the truth test in an @code{if}
4159 expression. So far, we have spoken of `true' and `false' as values of
4160 predicates as if they were new kinds of Emacs Lisp objects. In fact,
4161 `false' is just our old friend @code{nil}. Anything else---anything
4162 at all---is `true'.
4163
4164 The expression that tests for truth is interpreted as @dfn{true}
4165 if the result of evaluating it is a value that is not @code{nil}. In
4166 other words, the result of the test is considered true if the value
4167 returned is a number such as 47, a string such as @code{"hello"}, or a
4168 symbol (other than @code{nil}) such as @code{flowers}, or a list (so
4169 long as it is not empty), or even a buffer!
4170
4171 @menu
4172 * nil explained:: @code{nil} has two meanings.
4173 @end menu
4174
4175 @ifnottex
4176 @node nil explained
4177 @unnumberedsubsec An explanation of @code{nil}
4178 @end ifnottex
4179
4180 Before illustrating a test for truth, we need an explanation of @code{nil}.
4181
4182 In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the
4183 empty list. Second, it means false and is the value returned when a
4184 true-or-false-test tests false. @code{nil} can be written as an empty
4185 list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is
4186 concerned, @code{()} and @code{nil} are the same. Humans, however, tend
4187 to use @code{nil} for false and @code{()} for the empty list.
4188
4189 In Emacs Lisp, any value that is not @code{nil}---is not the empty
4190 list---is considered true. This means that if an evaluation returns
4191 something that is not an empty list, an @code{if} expression will test
4192 true. For example, if a number is put in the slot for the test, it
4193 will be evaluated and will return itself, since that is what numbers
4194 do when evaluated. In this conditional, the @code{if} expression will
4195 test true. The expression tests false only when @code{nil}, an empty
4196 list, is returned by evaluating the expression.
4197
4198 You can see this by evaluating the two expressions in the following examples.
4199
4200 In the first example, the number 4 is evaluated as the test in the
4201 @code{if} expression and returns itself; consequently, the then-part
4202 of the expression is evaluated and returned: @samp{true} appears in
4203 the echo area. In the second example, the @code{nil} indicates false;
4204 consequently, the else-part of the expression is evaluated and
4205 returned: @samp{false} appears in the echo area.
4206
4207 @smallexample
4208 @group
4209 (if 4
4210 'true
4211 'false)
4212 @end group
4213
4214 @group
4215 (if nil
4216 'true
4217 'false)
4218 @end group
4219 @end smallexample
4220
4221 @need 1250
4222 Incidentally, if some other useful value is not available for a test that
4223 returns true, then the Lisp interpreter will return the symbol @code{t}
4224 for true. For example, the expression @code{(> 5 4)} returns @code{t}
4225 when evaluated, as you can see by evaluating it in the usual way:
4226
4227 @smallexample
4228 (> 5 4)
4229 @end smallexample
4230
4231 @need 1250
4232 @noindent
4233 On the other hand, this function returns @code{nil} if the test is false.
4234
4235 @smallexample
4236 (> 4 5)
4237 @end smallexample
4238
4239 @node save-excursion
4240 @section @code{save-excursion}
4241 @findex save-excursion
4242 @cindex Region, what it is
4243 @cindex Preserving point, mark, and buffer
4244 @cindex Point, mark, buffer preservation
4245 @findex point
4246 @findex mark
4247
4248 The @code{save-excursion} function is the fourth and final special form
4249 that we will discuss in this chapter.
4250
4251 In Emacs Lisp programs used for editing, the @code{save-excursion}
4252 function is very common. It saves the location of point and mark,
4253 executes the body of the function, and then restores point and mark to
4254 their previous positions if their locations were changed. Its primary
4255 purpose is to keep the user from being surprised and disturbed by
4256 unexpected movement of point or mark.
4257
4258 @menu
4259 * Point and mark:: A review of various locations.
4260 * Template for save-excursion::
4261 @end menu
4262
4263 @ifnottex
4264 @node Point and mark
4265 @unnumberedsubsec Point and Mark
4266 @end ifnottex
4267
4268 Before discussing @code{save-excursion}, however, it may be useful
4269 first to review what point and mark are in GNU Emacs. @dfn{Point} is
4270 the current location of the cursor. Wherever the cursor
4271 is, that is point. More precisely, on terminals where the cursor
4272 appears to be on top of a character, point is immediately before the
4273 character. In Emacs Lisp, point is an integer. The first character in
4274 a buffer is number one, the second is number two, and so on. The
4275 function @code{point} returns the current position of the cursor as a
4276 number. Each buffer has its own value for point.
4277
4278 The @dfn{mark} is another position in the buffer; its value can be set
4279 with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If
4280 a mark has been set, you can use the command @kbd{C-x C-x}
4281 (@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4282 and set the mark to be the previous position of point. In addition, if
4283 you set another mark, the position of the previous mark is saved in the
4284 mark ring. Many mark positions can be saved this way. You can jump the
4285 cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4286 times.
4287
4288 The part of the buffer between point and mark is called @dfn{the
4289 region}. Numerous commands work on the region, including
4290 @code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4291 @code{print-region}.
4292
4293 The @code{save-excursion} special form saves the locations of point and
4294 mark and restores those positions after the code within the body of the
4295 special form is evaluated by the Lisp interpreter. Thus, if point were
4296 in the beginning of a piece of text and some code moved point to the end
4297 of the buffer, the @code{save-excursion} would put point back to where
4298 it was before, after the expressions in the body of the function were
4299 evaluated.
4300
4301 In Emacs, a function frequently moves point as part of its internal
4302 workings even though a user would not expect this. For example,
4303 @code{count-lines-region} moves point. To prevent the user from being
4304 bothered by jumps that are both unexpected and (from the user's point of
4305 view) unnecessary, @code{save-excursion} is often used to keep point and
4306 mark in the location expected by the user. The use of
4307 @code{save-excursion} is good housekeeping.
4308
4309 To make sure the house stays clean, @code{save-excursion} restores the
4310 values of point and mark even if something goes wrong in the code inside
4311 of it (or, to be more precise and to use the proper jargon, ``in case of
4312 abnormal exit''). This feature is very helpful.
4313
4314 In addition to recording the values of point and mark,
4315 @code{save-excursion} keeps track of the current buffer, and restores
4316 it, too. This means you can write code that will change the buffer and
4317 have @code{save-excursion} switch you back to the original buffer.
4318 This is how @code{save-excursion} is used in @code{append-to-buffer}.
4319 (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4320
4321 @node Template for save-excursion
4322 @subsection Template for a @code{save-excursion} Expression
4323
4324 @need 800
4325 The template for code using @code{save-excursion} is simple:
4326
4327 @smallexample
4328 @group
4329 (save-excursion
4330 @var{body}@dots{})
4331 @end group
4332 @end smallexample
4333
4334 @noindent
4335 The body of the function is one or more expressions that will be
4336 evaluated in sequence by the Lisp interpreter. If there is more than
4337 one expression in the body, the value of the last one will be returned
4338 as the value of the @code{save-excursion} function. The other
4339 expressions in the body are evaluated only for their side effects; and
4340 @code{save-excursion} itself is used only for its side effect (which
4341 is restoring the positions of point and mark).
4342
4343 @need 1250
4344 In more detail, the template for a @code{save-excursion} expression
4345 looks like this:
4346
4347 @smallexample
4348 @group
4349 (save-excursion
4350 @var{first-expression-in-body}
4351 @var{second-expression-in-body}
4352 @var{third-expression-in-body}
4353 @dots{}
4354 @var{last-expression-in-body})
4355 @end group
4356 @end smallexample
4357
4358 @noindent
4359 An expression, of course, may be a symbol on its own or a list.
4360
4361 In Emacs Lisp code, a @code{save-excursion} expression often occurs
4362 within the body of a @code{let} expression. It looks like this:
4363
4364 @smallexample
4365 @group
4366 (let @var{varlist}
4367 (save-excursion
4368 @var{body}@dots{}))
4369 @end group
4370 @end smallexample
4371
4372 @node Review
4373 @section Review
4374
4375 In the last few chapters we have introduced a fair number of functions
4376 and special forms. Here they are described in brief, along with a few
4377 similar functions that have not been mentioned yet.
4378
4379 @table @code
4380 @item eval-last-sexp
4381 Evaluate the last symbolic expression before the current location of
4382 point. The value is printed in the echo area unless the function is
4383 invoked with an argument; in that case, the output is printed in the
4384 current buffer. This command is normally bound to @kbd{C-x C-e}.
4385
4386 @item defun
4387 Define function. This special form has up to five parts: the name,
4388 a template for the arguments that will be passed to the function,
4389 documentation, an optional interactive declaration, and the body of the
4390 definition.
4391
4392 @need 1250
4393 For example, in an early version of Emacs, the function definition was
4394 as follows. (It is slightly more complex now that it seeks the first
4395 non-whitespace character rather than the first visible character.)
4396
4397 @smallexample
4398 @group
4399 (defun back-to-indentation ()
4400 "Move point to first visible character on line."
4401 (interactive)
4402 (beginning-of-line 1)
4403 (skip-chars-forward " \t"))
4404 @end group
4405 @end smallexample
4406
4407 @ignore
4408 In GNU Emacs 22,
4409
4410 (defun backward-to-indentation (&optional arg)
4411 "Move backward ARG lines and position at first nonblank character."
4412 (interactive "p")
4413 (forward-line (- (or arg 1)))
4414 (skip-chars-forward " \t"))
4415
4416 (defun back-to-indentation ()
4417 "Move point to the first non-whitespace character on this line."
4418 (interactive)
4419 (beginning-of-line 1)
4420 (skip-syntax-forward " " (line-end-position))
4421 ;; Move back over chars that have whitespace syntax but have the p flag.
4422 (backward-prefix-chars))
4423 @end ignore
4424
4425 @item interactive
4426 Declare to the interpreter that the function can be used
4427 interactively. This special form may be followed by a string with one
4428 or more parts that pass the information to the arguments of the
4429 function, in sequence. These parts may also tell the interpreter to
4430 prompt for information. Parts of the string are separated by
4431 newlines, @samp{\n}.
4432
4433 @need 1000
4434 Common code characters are:
4435
4436 @table @code
4437 @item b
4438 The name of an existing buffer.
4439
4440 @item f
4441 The name of an existing file.
4442
4443 @item p
4444 The numeric prefix argument. (Note that this `p' is lower case.)
4445
4446 @item r
4447 Point and the mark, as two numeric arguments, smallest first. This
4448 is the only code letter that specifies two successive arguments
4449 rather than one.
4450 @end table
4451
4452 @xref{Interactive Codes, , Code Characters for @samp{interactive},
4453 elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4454 code characters.
4455
4456 @item let
4457 Declare that a list of variables is for use within the body of the
4458 @code{let} and give them an initial value, either @code{nil} or a
4459 specified value; then evaluate the rest of the expressions in the body
4460 of the @code{let} and return the value of the last one. Inside the
4461 body of the @code{let}, the Lisp interpreter does not see the values of
4462 the variables of the same names that are bound outside of the
4463 @code{let}.
4464
4465 @need 1250
4466 For example,
4467
4468 @smallexample
4469 @group
4470 (let ((foo (buffer-name))
4471 (bar (buffer-size)))
4472 (message
4473 "This buffer is %s and has %d characters."
4474 foo bar))
4475 @end group
4476 @end smallexample
4477
4478 @item save-excursion
4479 Record the values of point and mark and the current buffer before
4480 evaluating the body of this special form. Restore the values of point
4481 and mark and buffer afterward.
4482
4483 @need 1250
4484 For example,
4485
4486 @smallexample
4487 @group
4488 (message "We are %d characters into this buffer."
4489 (- (point)
4490 (save-excursion
4491 (goto-char (point-min)) (point))))
4492 @end group
4493 @end smallexample
4494
4495 @item if
4496 Evaluate the first argument to the function; if it is true, evaluate
4497 the second argument; else evaluate the third argument, if there is one.
4498
4499 The @code{if} special form is called a @dfn{conditional}. There are
4500 other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4501 commonly used.
4502
4503 @need 1250
4504 For example,
4505
4506 @smallexample
4507 @group
4508 (if (= 22 emacs-major-version)
4509 (message "This is version 22 Emacs")
4510 (message "This is not version 22 Emacs"))
4511 @end group
4512 @end smallexample
4513
4514 @need 1250
4515 @item <
4516 @itemx >
4517 @itemx <=
4518 @itemx >=
4519 The @code{<} function tests whether its first argument is smaller than
4520 its second argument. A corresponding function, @code{>}, tests whether
4521 the first argument is greater than the second. Likewise, @code{<=}
4522 tests whether the first argument is less than or equal to the second and
4523 @code{>=} tests whether the first argument is greater than or equal to
4524 the second. In all cases, both arguments must be numbers or markers
4525 (markers indicate positions in buffers).
4526
4527 @need 800
4528 @item =
4529 The @code{=} function tests whether two arguments, both numbers or
4530 markers, are equal.
4531
4532 @need 1250
4533 @item equal
4534 @itemx eq
4535 Test whether two objects are the same. @code{equal} uses one meaning
4536 of the word `same' and @code{eq} uses another: @code{equal} returns
4537 true if the two objects have a similar structure and contents, such as
4538 two copies of the same book. On the other hand, @code{eq}, returns
4539 true if both arguments are actually the same object.
4540 @findex equal
4541 @findex eq
4542
4543 @need 1250
4544 @item string<
4545 @itemx string-lessp
4546 @itemx string=
4547 @itemx string-equal
4548 The @code{string-lessp} function tests whether its first argument is
4549 smaller than the second argument. A shorter, alternative name for the
4550 same function (a @code{defalias}) is @code{string<}.
4551
4552 The arguments to @code{string-lessp} must be strings or symbols; the
4553 ordering is lexicographic, so case is significant. The print names of
4554 symbols are used instead of the symbols themselves.
4555
4556 @cindex @samp{empty string} defined
4557 An empty string, @samp{""}, a string with no characters in it, is
4558 smaller than any string of characters.
4559
4560 @code{string-equal} provides the corresponding test for equality. Its
4561 shorter, alternative name is @code{string=}. There are no string test
4562 functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4563
4564 @item message
4565 Print a message in the echo area. The first argument is a string that
4566 can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4567 arguments that follow the string. The argument used by @samp{%s} must
4568 be a string or a symbol; the argument used by @samp{%d} must be a
4569 number. The argument used by @samp{%c} must be an @sc{ascii} code
4570 number; it will be printed as the character with that @sc{ascii} code.
4571 (Various other %-sequences have not been mentioned.)
4572
4573 @item setq
4574 @itemx set
4575 The @code{setq} function sets the value of its first argument to the
4576 value of the second argument. The first argument is automatically
4577 quoted by @code{setq}. It does the same for succeeding pairs of
4578 arguments. Another function, @code{set}, takes only two arguments and
4579 evaluates both of them before setting the value returned by its first
4580 argument to the value returned by its second argument.
4581
4582 @item buffer-name
4583 Without an argument, return the name of the buffer, as a string.
4584
4585 @itemx buffer-file-name
4586 Without an argument, return the name of the file the buffer is
4587 visiting.
4588
4589 @item current-buffer
4590 Return the buffer in which Emacs is active; it may not be
4591 the buffer that is visible on the screen.
4592
4593 @item other-buffer
4594 Return the most recently selected buffer (other than the buffer passed
4595 to @code{other-buffer} as an argument and other than the current
4596 buffer).
4597
4598 @item switch-to-buffer
4599 Select a buffer for Emacs to be active in and display it in the current
4600 window so users can look at it. Usually bound to @kbd{C-x b}.
4601
4602 @item set-buffer
4603 Switch Emacs's attention to a buffer on which programs will run. Don't
4604 alter what the window is showing.
4605
4606 @item buffer-size
4607 Return the number of characters in the current buffer.
4608
4609 @item point
4610 Return the value of the current position of the cursor, as an
4611 integer counting the number of characters from the beginning of the
4612 buffer.
4613
4614 @item point-min
4615 Return the minimum permissible value of point in
4616 the current buffer. This is 1, unless narrowing is in effect.
4617
4618 @item point-max
4619 Return the value of the maximum permissible value of point in the
4620 current buffer. This is the end of the buffer, unless narrowing is in
4621 effect.
4622 @end table
4623
4624 @need 1500
4625 @node defun Exercises
4626 @section Exercises
4627
4628 @itemize @bullet
4629 @item
4630 Write a non-interactive function that doubles the value of its
4631 argument, a number. Make that function interactive.
4632
4633 @item
4634 Write a function that tests whether the current value of
4635 @code{fill-column} is greater than the argument passed to the function,
4636 and if so, prints an appropriate message.
4637 @end itemize
4638
4639 @node Buffer Walk Through
4640 @chapter A Few Buffer--Related Functions
4641
4642 In this chapter we study in detail several of the functions used in GNU
4643 Emacs. This is called a ``walk-through''. These functions are used as
4644 examples of Lisp code, but are not imaginary examples; with the
4645 exception of the first, simplified function definition, these functions
4646 show the actual code used in GNU Emacs. You can learn a great deal from
4647 these definitions. The functions described here are all related to
4648 buffers. Later, we will study other functions.
4649
4650 @menu
4651 * Finding More:: How to find more information.
4652 * simplified-beginning-of-buffer:: Shows @code{goto-char},
4653 @code{point-min}, and @code{push-mark}.
4654 * mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
4655 * append-to-buffer:: Uses @code{save-excursion} and
4656 @code{insert-buffer-substring}.
4657 * Buffer Related Review:: Review.
4658 * Buffer Exercises::
4659 @end menu
4660
4661 @node Finding More
4662 @section Finding More Information
4663
4664 @findex describe-function, @r{introduced}
4665 @cindex Find function documentation
4666 In this walk-through, I will describe each new function as we come to
4667 it, sometimes in detail and sometimes briefly. If you are interested,
4668 you can get the full documentation of any Emacs Lisp function at any
4669 time by typing @kbd{C-h f} and then the name of the function (and then
4670 @key{RET}). Similarly, you can get the full documentation for a
4671 variable by typing @kbd{C-h v} and then the name of the variable (and
4672 then @key{RET}).
4673
4674 @cindex Find source of function
4675 @c In version 22, tells location both of C and of Emacs Lisp
4676 Also, @code{describe-function} will tell you the location of the
4677 function definition.
4678
4679 Put point into the name of the file that contains the function and
4680 press the @key{RET} key. In this case, @key{RET} means
4681 @code{push-button} rather than `return' or `enter'. Emacs will take
4682 you directly to the function definition.
4683
4684 @ignore
4685 Not In version 22
4686
4687 If you move point over the file name and press
4688 the @key{RET} key, which in this case means @code{help-follow} rather
4689 than `return' or `enter', Emacs will take you directly to the function
4690 definition.
4691 @end ignore
4692
4693 More generally, if you want to see a function in its original source
4694 file, you can use the @code{find-tag} function to jump to it.
4695 @code{find-tag} works with a wide variety of languages, not just
4696 Lisp, and C, and it works with non-programming text as well. For
4697 example, @code{find-tag} will jump to the various nodes in the
4698 Texinfo source file of this document.
4699 The @code{find-tag} function depends on `tags tables' that record
4700 the locations of the functions, variables, and other items to which
4701 @code{find-tag} jumps.
4702
4703 To use the @code{find-tag} command, type @kbd{M-.} (i.e., press the
4704 period key while holding down the @key{META} key, or else type the
4705 @key{ESC} key and then type the period key), and then, at the prompt,
4706 type in the name of the function whose source code you want to see,
4707 such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will
4708 switch buffers and display the source code for the function on your
4709 screen. To switch back to your current buffer, type @kbd{C-x b
4710 @key{RET}}. (On some keyboards, the @key{META} key is labeled
4711 @key{ALT}.)
4712
4713 @c !!! 22.1.1 tags table location in this paragraph
4714 @cindex TAGS table, specifying
4715 @findex find-tag
4716 Depending on how the initial default values of your copy of Emacs are
4717 set, you may also need to specify the location of your `tags table',
4718 which is a file called @file{TAGS}. For example, if you are
4719 interested in Emacs sources, the tags table you will most likely want,
4720 if it has already been created for you, will be in a subdirectory of
4721 the @file{/usr/local/share/emacs/} directory; thus you would use the
4722 @code{M-x visit-tags-table} command and specify a pathname such as
4723 @file{/usr/local/share/emacs/22.1.1/lisp/TAGS}. If the tags table
4724 has not already been created, you will have to create it yourself. It
4725 will be in a file such as @file{/usr/local/src/emacs/src/TAGS}.
4726
4727 @need 1250
4728 To create a @file{TAGS} file in a specific directory, switch to that
4729 directory in Emacs using @kbd{M-x cd} command, or list the directory
4730 with @kbd{C-x d} (@code{dired}). Then run the compile command, with
4731 @w{@code{etags *.el}} as the command to execute:
4732
4733 @smallexample
4734 M-x compile RET etags *.el RET
4735 @end smallexample
4736
4737 For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4738
4739 After you become more familiar with Emacs Lisp, you will find that you will
4740 frequently use @code{find-tag} to navigate your way around source code;
4741 and you will create your own @file{TAGS} tables.
4742
4743 @cindex Library, as term for `file'
4744 Incidentally, the files that contain Lisp code are conventionally
4745 called @dfn{libraries}. The metaphor is derived from that of a
4746 specialized library, such as a law library or an engineering library,
4747 rather than a general library. Each library, or file, contains
4748 functions that relate to a particular topic or activity, such as
4749 @file{abbrev.el} for handling abbreviations and other typing
4750 shortcuts, and @file{help.el} for on-line help. (Sometimes several
4751 libraries provide code for a single activity, as the various
4752 @file{rmail@dots{}} files provide code for reading electronic mail.)
4753 In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4754 @kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4755 by topic keywords.''
4756
4757 @node simplified-beginning-of-buffer
4758 @section A Simplified @code{beginning-of-buffer} Definition
4759 @findex simplified-beginning-of-buffer
4760
4761 The @code{beginning-of-buffer} command is a good function to start with
4762 since you are likely to be familiar with it and it is easy to
4763 understand. Used as an interactive command, @code{beginning-of-buffer}
4764 moves the cursor to the beginning of the buffer, leaving the mark at the
4765 previous position. It is generally bound to @kbd{M-<}.
4766
4767 In this section, we will discuss a shortened version of the function
4768 that shows how it is most frequently used. This shortened function
4769 works as written, but it does not contain the code for a complex option.
4770 In another section, we will describe the entire function.
4771 (@xref{beginning-of-buffer, , Complete Definition of
4772 @code{beginning-of-buffer}}.)
4773
4774 Before looking at the code, let's consider what the function
4775 definition has to contain: it must include an expression that makes
4776 the function interactive so it can be called by typing @kbd{M-x
4777 beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
4778 must include code to leave a mark at the original position in the
4779 buffer; and it must include code to move the cursor to the beginning
4780 of the buffer.
4781
4782 @need 1250
4783 Here is the complete text of the shortened version of the function:
4784
4785 @smallexample
4786 @group
4787 (defun simplified-beginning-of-buffer ()
4788 "Move point to the beginning of the buffer;
4789 leave mark at previous position."
4790 (interactive)
4791 (push-mark)
4792 (goto-char (point-min)))
4793 @end group
4794 @end smallexample
4795
4796 Like all function definitions, this definition has five parts following
4797 the special form @code{defun}:
4798
4799 @enumerate
4800 @item
4801 The name: in this example, @code{simplified-beginning-of-buffer}.
4802
4803 @item
4804 A list of the arguments: in this example, an empty list, @code{()},
4805
4806 @item
4807 The documentation string.
4808
4809 @item
4810 The interactive expression.
4811
4812 @item
4813 The body.
4814 @end enumerate
4815
4816 @noindent
4817 In this function definition, the argument list is empty; this means that
4818 this function does not require any arguments. (When we look at the
4819 definition for the complete function, we will see that it may be passed
4820 an optional argument.)
4821
4822 The interactive expression tells Emacs that the function is intended to
4823 be used interactively. In this example, @code{interactive} does not have
4824 an argument because @code{simplified-beginning-of-buffer} does not
4825 require one.
4826
4827 @need 800
4828 The body of the function consists of the two lines:
4829
4830 @smallexample
4831 @group
4832 (push-mark)
4833 (goto-char (point-min))
4834 @end group
4835 @end smallexample
4836
4837 The first of these lines is the expression, @code{(push-mark)}. When
4838 this expression is evaluated by the Lisp interpreter, it sets a mark at
4839 the current position of the cursor, wherever that may be. The position
4840 of this mark is saved in the mark ring.
4841
4842 The next line is @code{(goto-char (point-min))}. This expression
4843 jumps the cursor to the minimum point in the buffer, that is, to the
4844 beginning of the buffer (or to the beginning of the accessible portion
4845 of the buffer if it is narrowed. @xref{Narrowing & Widening, ,
4846 Narrowing and Widening}.)
4847
4848 The @code{push-mark} command sets a mark at the place where the cursor
4849 was located before it was moved to the beginning of the buffer by the
4850 @code{(goto-char (point-min))} expression. Consequently, you can, if
4851 you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4852
4853 That is all there is to the function definition!
4854
4855 @findex describe-function
4856 When you are reading code such as this and come upon an unfamiliar
4857 function, such as @code{goto-char}, you can find out what it does by
4858 using the @code{describe-function} command. To use this command, type
4859 @kbd{C-h f} and then type in the name of the function and press
4860 @key{RET}. The @code{describe-function} command will print the
4861 function's documentation string in a @file{*Help*} window. For
4862 example, the documentation for @code{goto-char} is:
4863
4864 @smallexample
4865 @group
4866 Set point to POSITION, a number or marker.
4867 Beginning of buffer is position (point-min), end is (point-max).
4868 @end group
4869 @end smallexample
4870
4871 @noindent
4872 The function's one argument is the desired position.
4873
4874 @noindent
4875 (The prompt for @code{describe-function} will offer you the symbol
4876 under or preceding the cursor, so you can save typing by positioning
4877 the cursor right over or after the function and then typing @kbd{C-h f
4878 @key{RET}}.)
4879
4880 The @code{end-of-buffer} function definition is written in the same way as
4881 the @code{beginning-of-buffer} definition except that the body of the
4882 function contains the expression @code{(goto-char (point-max))} in place
4883 of @code{(goto-char (point-min))}.
4884
4885 @node mark-whole-buffer
4886 @section The Definition of @code{mark-whole-buffer}
4887 @findex mark-whole-buffer
4888
4889 The @code{mark-whole-buffer} function is no harder to understand than the
4890 @code{simplified-beginning-of-buffer} function. In this case, however,
4891 we will look at the complete function, not a shortened version.
4892
4893 The @code{mark-whole-buffer} function is not as commonly used as the
4894 @code{beginning-of-buffer} function, but is useful nonetheless: it
4895 marks a whole buffer as a region by putting point at the beginning and
4896 a mark at the end of the buffer. It is generally bound to @kbd{C-x
4897 h}.
4898
4899 @menu
4900 * mark-whole-buffer overview::
4901 * Body of mark-whole-buffer:: Only three lines of code.
4902 @end menu
4903
4904 @ifnottex
4905 @node mark-whole-buffer overview
4906 @unnumberedsubsec An overview of @code{mark-whole-buffer}
4907 @end ifnottex
4908
4909 @need 1250
4910 In GNU Emacs 22, the code for the complete function looks like this:
4911
4912 @smallexample
4913 @group
4914 (defun mark-whole-buffer ()
4915 "Put point at beginning and mark at end of buffer.
4916 You probably should not use this function in Lisp programs;
4917 it is usually a mistake for a Lisp function to use any subroutine
4918 that uses or sets the mark."
4919 (interactive)
4920 (push-mark (point))
4921 (push-mark (point-max) nil t)
4922 (goto-char (point-min)))
4923 @end group
4924 @end smallexample
4925
4926 @need 1250
4927 Like all other functions, the @code{mark-whole-buffer} function fits
4928 into the template for a function definition. The template looks like
4929 this:
4930
4931 @smallexample
4932 @group
4933 (defun @var{name-of-function} (@var{argument-list})
4934 "@var{documentation}@dots{}"
4935 (@var{interactive-expression}@dots{})
4936 @var{body}@dots{})
4937 @end group
4938 @end smallexample
4939
4940 Here is how the function works: the name of the function is
4941 @code{mark-whole-buffer}; it is followed by an empty argument list,
4942 @samp{()}, which means that the function does not require arguments.
4943 The documentation comes next.
4944
4945 The next line is an @code{(interactive)} expression that tells Emacs
4946 that the function will be used interactively. These details are similar
4947 to the @code{simplified-beginning-of-buffer} function described in the
4948 previous section.
4949
4950 @need 1250
4951 @node Body of mark-whole-buffer
4952 @subsection Body of @code{mark-whole-buffer}
4953
4954 The body of the @code{mark-whole-buffer} function consists of three
4955 lines of code:
4956
4957 @c GNU Emacs 22
4958 @smallexample
4959 @group
4960 (push-mark (point))
4961 (push-mark (point-max) nil t)
4962 (goto-char (point-min))
4963 @end group
4964 @end smallexample
4965
4966 The first of these lines is the expression, @code{(push-mark (point))}.
4967
4968 This line does exactly the same job as the first line of the body of
4969 the @code{simplified-beginning-of-buffer} function, which is written
4970 @code{(push-mark)}. In both cases, the Lisp interpreter sets a mark
4971 at the current position of the cursor.
4972
4973 I don't know why the expression in @code{mark-whole-buffer} is written
4974 @code{(push-mark (point))} and the expression in
4975 @code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps
4976 whoever wrote the code did not know that the arguments for
4977 @code{push-mark} are optional and that if @code{push-mark} is not
4978 passed an argument, the function automatically sets mark at the
4979 location of point by default. Or perhaps the expression was written
4980 so as to parallel the structure of the next line. In any case, the
4981 line causes Emacs to determine the position of point and set a mark
4982 there.
4983
4984 In earlier versions of GNU Emacs, the next line of
4985 @code{mark-whole-buffer} was @code{(push-mark (point-max))}. This
4986 expression sets a mark at the point in the buffer that has the highest
4987 number. This will be the end of the buffer (or, if the buffer is
4988 narrowed, the end of the accessible portion of the buffer.
4989 @xref{Narrowing & Widening, , Narrowing and Widening}, for more about
4990 narrowing.) After this mark has been set, the previous mark, the one
4991 set at point, is no longer set, but Emacs remembers its position, just
4992 as all other recent marks are always remembered. This means that you
4993 can, if you wish, go back to that position by typing @kbd{C-u
4994 C-@key{SPC}} twice.
4995
4996 @need 1250
4997 In GNU Emacs 22, the @code{(point-max)} is slightly more complicated.
4998 The line reads
4999
5000 @smallexample
5001 (push-mark (point-max) nil t)
5002 @end smallexample
5003
5004 @noindent
5005 The expression works nearly the same as before. It sets a mark at the
5006 highest numbered place in the buffer that it can. However, in this
5007 version, @code{push-mark} has two additional arguments. The second
5008 argument to @code{push-mark} is @code{nil}. This tells the function
5009 it @emph{should} display a message that says `Mark set' when it pushes
5010 the mark. The third argument is @code{t}. This tells
5011 @code{push-mark} to activate the mark when Transient Mark mode is
5012 turned on. Transient Mark mode highlights the currently active
5013 region. It is often turned off.
5014
5015 Finally, the last line of the function is @code{(goto-char
5016 (point-min)))}. This is written exactly the same way as it is written
5017 in @code{beginning-of-buffer}. The expression moves the cursor to
5018 the minimum point in the buffer, that is, to the beginning of the buffer
5019 (or to the beginning of the accessible portion of the buffer). As a
5020 result of this, point is placed at the beginning of the buffer and mark
5021 is set at the end of the buffer. The whole buffer is, therefore, the
5022 region.
5023
5024 @node append-to-buffer
5025 @section The Definition of @code{append-to-buffer}
5026 @findex append-to-buffer
5027
5028 The @code{append-to-buffer} command is more complex than the
5029 @code{mark-whole-buffer} command. What it does is copy the region
5030 (that is, the part of the buffer between point and mark) from the
5031 current buffer to a specified buffer.
5032
5033 @menu
5034 * append-to-buffer overview::
5035 * append interactive:: A two part interactive expression.
5036 * append-to-buffer body:: Incorporates a @code{let} expression.
5037 * append save-excursion:: How the @code{save-excursion} works.
5038 @end menu
5039
5040 @ifnottex
5041 @node append-to-buffer overview
5042 @unnumberedsubsec An Overview of @code{append-to-buffer}
5043 @end ifnottex
5044
5045 @findex insert-buffer-substring
5046 The @code{append-to-buffer} command uses the
5047 @code{insert-buffer-substring} function to copy the region.
5048 @code{insert-buffer-substring} is described by its name: it takes a
5049 string of characters from part of a buffer, a ``substring'', and
5050 inserts them into another buffer.
5051
5052 Most of @code{append-to-buffer} is
5053 concerned with setting up the conditions for
5054 @code{insert-buffer-substring} to work: the code must specify both the
5055 buffer to which the text will go, the window it comes from and goes
5056 to, and the region that will be copied.
5057
5058 @need 1250
5059 Here is the complete text of the function:
5060
5061 @smallexample
5062 @group
5063 (defun append-to-buffer (buffer start end)
5064 "Append to specified buffer the text of the region.
5065 It is inserted into that buffer before its point.
5066 @end group
5067
5068 @group
5069 When calling from a program, give three arguments:
5070 BUFFER (or buffer name), START and END.
5071 START and END specify the portion of the current buffer to be copied."
5072 (interactive
5073 (list (read-buffer "Append to buffer: " (other-buffer
5074 (current-buffer) t))
5075 (region-beginning) (region-end)))
5076 @end group
5077 @group
5078 (let ((oldbuf (current-buffer)))
5079 (save-excursion
5080 (let* ((append-to (get-buffer-create buffer))
5081 (windows (get-buffer-window-list append-to t t))
5082 point)
5083 (set-buffer append-to)
5084 (setq point (point))
5085 (barf-if-buffer-read-only)
5086 (insert-buffer-substring oldbuf start end)
5087 (dolist (window windows)
5088 (when (= (window-point window) point)
5089 (set-window-point window (point))))))))
5090 @end group
5091 @end smallexample
5092
5093 The function can be understood by looking at it as a series of
5094 filled-in templates.
5095
5096 The outermost template is for the function definition. In this
5097 function, it looks like this (with several slots filled in):
5098
5099 @smallexample
5100 @group
5101 (defun append-to-buffer (buffer start end)
5102 "@var{documentation}@dots{}"
5103 (interactive @dots{})
5104 @var{body}@dots{})
5105 @end group
5106 @end smallexample
5107
5108 The first line of the function includes its name and three arguments.
5109 The arguments are the @code{buffer} to which the text will be copied, and
5110 the @code{start} and @code{end} of the region in the current buffer that
5111 will be copied.
5112
5113 The next part of the function is the documentation, which is clear and
5114 complete. As is conventional, the three arguments are written in
5115 upper case so you will notice them easily. Even better, they are
5116 described in the same order as in the argument list.
5117
5118 Note that the documentation distinguishes between a buffer and its
5119 name. (The function can handle either.)
5120
5121 @node append interactive
5122 @subsection The @code{append-to-buffer} Interactive Expression
5123
5124 Since the @code{append-to-buffer} function will be used interactively,
5125 the function must have an @code{interactive} expression. (For a
5126 review of @code{interactive}, see @ref{Interactive, , Making a
5127 Function Interactive}.) The expression reads as follows:
5128
5129 @smallexample
5130 @group
5131 (interactive
5132 (list (read-buffer
5133 "Append to buffer: "
5134 (other-buffer (current-buffer) t))
5135 (region-beginning)
5136 (region-end)))
5137 @end group
5138 @end smallexample
5139
5140 @noindent
5141 This expression is not one with letters standing for parts, as
5142 described earlier. Instead, it starts a list with these parts:
5143
5144 The first part of the list is an expression to read the name of a
5145 buffer and return it as a string. That is @code{read-buffer}. The
5146 function requires a prompt as its first argument, @samp{"Append to
5147 buffer: "}. Its second argument tells the command what value to
5148 provide if you don't specify anything.
5149
5150 In this case that second argument is an expression containing the
5151 function @code{other-buffer}, an exception, and a @samp{t}, standing
5152 for true.
5153
5154 The first argument to @code{other-buffer}, the exception, is yet
5155 another function, @code{current-buffer}. That is not going to be
5156 returned. The second argument is the symbol for true, @code{t}. that
5157 tells @code{other-buffer} that it may show visible buffers (except in
5158 this case, it will not show the current buffer, which makes sense).
5159
5160 @need 1250
5161 The expression looks like this:
5162
5163 @smallexample
5164 (other-buffer (current-buffer) t)
5165 @end smallexample
5166
5167 The second and third arguments to the @code{list} expression are
5168 @code{(region-beginning)} and @code{(region-end)}. These two
5169 functions specify the beginning and end of the text to be appended.
5170
5171 @need 1250
5172 Originally, the command used the letters @samp{B} and @samp{r}.
5173 The whole @code{interactive} expression looked like this:
5174
5175 @smallexample
5176 (interactive "BAppend to buffer:@: \nr")
5177 @end smallexample
5178
5179 @noindent
5180 But when that was done, the default value of the buffer switched to
5181 was invisible. That was not wanted.
5182
5183 (The prompt was separated from the second argument with a newline,
5184 @samp{\n}. It was followed by an @samp{r} that told Emacs to bind the
5185 two arguments that follow the symbol @code{buffer} in the function's
5186 argument list (that is, @code{start} and @code{end}) to the values of
5187 point and mark. That argument worked fine.)
5188
5189 @node append-to-buffer body
5190 @subsection The Body of @code{append-to-buffer}
5191
5192 @ignore
5193 in GNU Emacs 22 in /usr/local/src/emacs/lisp/simple.el
5194
5195 (defun append-to-buffer (buffer start end)
5196 "Append to specified buffer the text of the region.
5197 It is inserted into that buffer before its point.
5198
5199 When calling from a program, give three arguments:
5200 BUFFER (or buffer name), START and END.
5201 START and END specify the portion of the current buffer to be copied."
5202 (interactive
5203 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5204 (region-beginning) (region-end)))
5205 (let ((oldbuf (current-buffer)))
5206 (save-excursion
5207 (let* ((append-to (get-buffer-create buffer))
5208 (windows (get-buffer-window-list append-to t t))
5209 point)
5210 (set-buffer append-to)
5211 (setq point (point))
5212 (barf-if-buffer-read-only)
5213 (insert-buffer-substring oldbuf start end)
5214 (dolist (window windows)
5215 (when (= (window-point window) point)
5216 (set-window-point window (point))))))))
5217 @end ignore
5218
5219 The body of the @code{append-to-buffer} function begins with @code{let}.
5220
5221 As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5222 @code{let} expression is to create and give initial values to one or
5223 more variables that will only be used within the body of the
5224 @code{let}. This means that such a variable will not be confused with
5225 any variable of the same name outside the @code{let} expression.
5226
5227 We can see how the @code{let} expression fits into the function as a
5228 whole by showing a template for @code{append-to-buffer} with the
5229 @code{let} expression in outline:
5230
5231 @smallexample
5232 @group
5233 (defun append-to-buffer (buffer start end)
5234 "@var{documentation}@dots{}"
5235 (interactive @dots{})
5236 (let ((@var{variable} @var{value}))
5237 @var{body}@dots{})
5238 @end group
5239 @end smallexample
5240
5241 The @code{let} expression has three elements:
5242
5243 @enumerate
5244 @item
5245 The symbol @code{let};
5246
5247 @item
5248 A varlist containing, in this case, a single two-element list,
5249 @code{(@var{variable} @var{value})};
5250
5251 @item
5252 The body of the @code{let} expression.
5253 @end enumerate
5254
5255 @need 800
5256 In the @code{append-to-buffer} function, the varlist looks like this:
5257
5258 @smallexample
5259 (oldbuf (current-buffer))
5260 @end smallexample
5261
5262 @noindent
5263 In this part of the @code{let} expression, the one variable,
5264 @code{oldbuf}, is bound to the value returned by the
5265 @code{(current-buffer)} expression. The variable, @code{oldbuf}, is
5266 used to keep track of the buffer in which you are working and from
5267 which you will copy.
5268
5269 The element or elements of a varlist are surrounded by a set of
5270 parentheses so the Lisp interpreter can distinguish the varlist from
5271 the body of the @code{let}. As a consequence, the two-element list
5272 within the varlist is surrounded by a circumscribing set of parentheses.
5273 The line looks like this:
5274
5275 @smallexample
5276 @group
5277 (let ((oldbuf (current-buffer)))
5278 @dots{} )
5279 @end group
5280 @end smallexample
5281
5282 @noindent
5283 The two parentheses before @code{oldbuf} might surprise you if you did
5284 not realize that the first parenthesis before @code{oldbuf} marks the
5285 boundary of the varlist and the second parenthesis marks the beginning
5286 of the two-element list, @code{(oldbuf (current-buffer))}.
5287
5288 @node append save-excursion
5289 @subsection @code{save-excursion} in @code{append-to-buffer}
5290
5291 The body of the @code{let} expression in @code{append-to-buffer}
5292 consists of a @code{save-excursion} expression.
5293
5294 The @code{save-excursion} function saves the locations of point and
5295 mark, and restores them to those positions after the expressions in the
5296 body of the @code{save-excursion} complete execution. In addition,
5297 @code{save-excursion} keeps track of the original buffer, and
5298 restores it. This is how @code{save-excursion} is used in
5299 @code{append-to-buffer}.
5300
5301 @need 1500
5302 @cindex Indentation for formatting
5303 @cindex Formatting convention
5304 Incidentally, it is worth noting here that a Lisp function is normally
5305 formatted so that everything that is enclosed in a multi-line spread is
5306 indented more to the right than the first symbol. In this function
5307 definition, the @code{let} is indented more than the @code{defun}, and
5308 the @code{save-excursion} is indented more than the @code{let}, like
5309 this:
5310
5311 @smallexample
5312 @group
5313 (defun @dots{}
5314 @dots{}
5315 @dots{}
5316 (let@dots{}
5317 (save-excursion
5318 @dots{}
5319 @end group
5320 @end smallexample
5321
5322 @need 1500
5323 @noindent
5324 This formatting convention makes it easy to see that the lines in
5325 the body of the @code{save-excursion} are enclosed by the parentheses
5326 associated with @code{save-excursion}, just as the
5327 @code{save-excursion} itself is enclosed by the parentheses associated
5328 with the @code{let}:
5329
5330 @smallexample
5331 @group
5332 (let ((oldbuf (current-buffer)))
5333 (save-excursion
5334 @dots{}
5335 (set-buffer @dots{})
5336 (insert-buffer-substring oldbuf start end)
5337 @dots{}))
5338 @end group
5339 @end smallexample
5340
5341 @need 1200
5342 The use of the @code{save-excursion} function can be viewed as a process
5343 of filling in the slots of a template:
5344
5345 @smallexample
5346 @group
5347 (save-excursion
5348 @var{first-expression-in-body}
5349 @var{second-expression-in-body}
5350 @dots{}
5351 @var{last-expression-in-body})
5352 @end group
5353 @end smallexample
5354
5355 @need 1200
5356 @noindent
5357 In this function, the body of the @code{save-excursion} contains only
5358 one expression, the @code{let*} expression. You know about a
5359 @code{let} function. The @code{let*} function is different. It has a
5360 @samp{*} in its name. It enables Emacs to set each variable in its
5361 varlist in sequence, one after another.
5362
5363 Its critical feature is that variables later in the varlist can make
5364 use of the values to which Emacs set variables earlier in the varlist.
5365 @xref{fwd-para let, , The @code{let*} expression}.
5366
5367 We will skip functions like @code{let*} and focus on two: the
5368 @code{set-buffer} function and the @code{insert-buffer-substring}
5369 function.
5370
5371 @need 1250
5372 In the old days, the @code{set-buffer} expression was simply
5373
5374 @smallexample
5375 (set-buffer (get-buffer-create buffer))
5376 @end smallexample
5377
5378 @need 1250
5379 @noindent
5380 but now it is
5381
5382 @smallexample
5383 (set-buffer append-to)
5384 @end smallexample
5385
5386 @noindent
5387 @code{append-to} is bound to @code{(get-buffer-create buffer)} earlier
5388 on in the @code{let*} expression. That extra binding would not be
5389 necessary except for that @code{append-to} is used later in the
5390 varlist as an argument to @code{get-buffer-window-list}.
5391
5392 @ignore
5393 in GNU Emacs 22
5394
5395 (let ((oldbuf (current-buffer)))
5396 (save-excursion
5397 (let* ((append-to (get-buffer-create buffer))
5398 (windows (get-buffer-window-list append-to t t))
5399 point)
5400 (set-buffer append-to)
5401 (setq point (point))
5402 (barf-if-buffer-read-only)
5403 (insert-buffer-substring oldbuf start end)
5404 (dolist (window windows)
5405 (when (= (window-point window) point)
5406 (set-window-point window (point))))))))
5407 @end ignore
5408
5409 The @code{append-to-buffer} function definition inserts text from the
5410 buffer in which you are currently to a named buffer. It happens that
5411 @code{insert-buffer-substring} copies text from another buffer to the
5412 current buffer, just the reverse---that is why the
5413 @code{append-to-buffer} definition starts out with a @code{let} that
5414 binds the local symbol @code{oldbuf} to the value returned by
5415 @code{current-buffer}.
5416
5417 @need 1250
5418 The @code{insert-buffer-substring} expression looks like this:
5419
5420 @smallexample
5421 (insert-buffer-substring oldbuf start end)
5422 @end smallexample
5423
5424 @noindent
5425 The @code{insert-buffer-substring} function copies a string
5426 @emph{from} the buffer specified as its first argument and inserts the
5427 string into the present buffer. In this case, the argument to
5428 @code{insert-buffer-substring} is the value of the variable created
5429 and bound by the @code{let}, namely the value of @code{oldbuf}, which
5430 was the current buffer when you gave the @code{append-to-buffer}
5431 command.
5432
5433 After @code{insert-buffer-substring} has done its work,
5434 @code{save-excursion} will restore the action to the original buffer
5435 and @code{append-to-buffer} will have done its job.
5436
5437 @need 800
5438 Written in skeletal form, the workings of the body look like this:
5439
5440 @smallexample
5441 @group
5442 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5443 (save-excursion ; @r{Keep track of buffer.}
5444 @var{change-buffer}
5445 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5446
5447 @var{change-back-to-original-buffer-when-finished}
5448 @var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5449 @end group
5450 @end smallexample
5451
5452 In summary, @code{append-to-buffer} works as follows: it saves the
5453 value of the current buffer in the variable called @code{oldbuf}. It
5454 gets the new buffer (creating one if need be) and switches Emacs's
5455 attention to it. Using the value of @code{oldbuf}, it inserts the
5456 region of text from the old buffer into the new buffer; and then using
5457 @code{save-excursion}, it brings you back to your original buffer.
5458
5459 In looking at @code{append-to-buffer}, you have explored a fairly
5460 complex function. It shows how to use @code{let} and
5461 @code{save-excursion}, and how to change to and come back from another
5462 buffer. Many function definitions use @code{let},
5463 @code{save-excursion}, and @code{set-buffer} this way.
5464
5465 @node Buffer Related Review
5466 @section Review
5467
5468 Here is a brief summary of the various functions discussed in this chapter.
5469
5470 @table @code
5471 @item describe-function
5472 @itemx describe-variable
5473 Print the documentation for a function or variable.
5474 Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5475
5476 @item find-tag
5477 Find the file containing the source for a function or variable and
5478 switch buffers to it, positioning point at the beginning of the item.
5479 Conventionally bound to @kbd{M-.} (that's a period following the
5480 @key{META} key).
5481
5482 @item save-excursion
5483 Save the location of point and mark and restore their values after the
5484 arguments to @code{save-excursion} have been evaluated. Also, remember
5485 the current buffer and return to it.
5486
5487 @item push-mark
5488 Set mark at a location and record the value of the previous mark on the
5489 mark ring. The mark is a location in the buffer that will keep its
5490 relative position even if text is added to or removed from the buffer.
5491
5492 @item goto-char
5493 Set point to the location specified by the value of the argument, which
5494 can be a number, a marker, or an expression that returns the number of
5495 a position, such as @code{(point-min)}.
5496
5497 @item insert-buffer-substring
5498 Copy a region of text from a buffer that is passed to the function as
5499 an argument and insert the region into the current buffer.
5500
5501 @item mark-whole-buffer
5502 Mark the whole buffer as a region. Normally bound to @kbd{C-x h}.
5503
5504 @item set-buffer
5505 Switch the attention of Emacs to another buffer, but do not change the
5506 window being displayed. Used when the program rather than a human is
5507 to work on a different buffer.
5508
5509 @item get-buffer-create
5510 @itemx get-buffer
5511 Find a named buffer or create one if a buffer of that name does not
5512 exist. The @code{get-buffer} function returns @code{nil} if the named
5513 buffer does not exist.
5514 @end table
5515
5516 @need 1500
5517 @node Buffer Exercises
5518 @section Exercises
5519
5520 @itemize @bullet
5521 @item
5522 Write your own @code{simplified-end-of-buffer} function definition;
5523 then test it to see whether it works.
5524
5525 @item
5526 Use @code{if} and @code{get-buffer} to write a function that prints a
5527 message telling you whether a buffer exists.
5528
5529 @item
5530 Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5531 function.
5532 @end itemize
5533
5534 @node More Complex
5535 @chapter A Few More Complex Functions
5536
5537 In this chapter, we build on what we have learned in previous chapters
5538 by looking at more complex functions. The @code{copy-to-buffer}
5539 function illustrates use of two @code{save-excursion} expressions in
5540 one definition, while the @code{insert-buffer} function illustrates
5541 use of an asterisk in an @code{interactive} expression, use of
5542 @code{or}, and the important distinction between a name and the object
5543 to which the name refers.
5544
5545 @menu
5546 * copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
5547 * insert-buffer:: Read-only, and with @code{or}.
5548 * beginning-of-buffer:: Shows @code{goto-char},
5549 @code{point-min}, and @code{push-mark}.
5550 * Second Buffer Related Review::
5551 * optional Exercise::
5552 @end menu
5553
5554 @node copy-to-buffer
5555 @section The Definition of @code{copy-to-buffer}
5556 @findex copy-to-buffer
5557
5558 After understanding how @code{append-to-buffer} works, it is easy to
5559 understand @code{copy-to-buffer}. This function copies text into a
5560 buffer, but instead of adding to the second buffer, it replaces all the
5561 previous text in the second buffer.
5562
5563 @need 800
5564 The body of @code{copy-to-buffer} looks like this,
5565
5566 @smallexample
5567 @group
5568 @dots{}
5569 (interactive "BCopy to buffer: \nr")
5570 (let ((oldbuf (current-buffer)))
5571 (with-current-buffer (get-buffer-create buffer)
5572 (barf-if-buffer-read-only)
5573 (erase-buffer)
5574 (save-excursion
5575 (insert-buffer-substring oldbuf start end)))))
5576 @end group
5577 @end smallexample
5578
5579 The @code{copy-to-buffer} function has a simpler @code{interactive}
5580 expression than @code{append-to-buffer}.
5581
5582 @need 800
5583 The definition then says
5584
5585 @smallexample
5586 (with-current-buffer (get-buffer-create buffer) @dots{}
5587 @end smallexample
5588
5589 First, look at the earliest inner expression; that is evaluated first.
5590 That expression starts with @code{get-buffer-create buffer}. The
5591 function tells the computer to use the buffer with the name specified
5592 as the one to which you are copying, or if such a buffer does not
5593 exist, to create it. Then, the @code{with-current-buffer} function
5594 evaluates its body with that buffer temporarily current.
5595
5596 (This demonstrates another way to shift the computer's attention but
5597 not the user's. The @code{append-to-buffer} function showed how to do
5598 the same with @code{save-excursion} and @code{set-buffer}.
5599 @code{with-current-buffer} is a newer, and arguably easier,
5600 mechanism.)
5601
5602 The @code{barf-if-buffer-read-only} function sends you an error
5603 message saying the buffer is read-only if you cannot modify it.
5604
5605 The next line has the @code{erase-buffer} function as its sole
5606 contents. That function erases the buffer.
5607
5608 Finally, the last two lines contain the @code{save-excursion}
5609 expression with @code{insert-buffer-substring} as its body.
5610 The @code{insert-buffer-substring} expression copies the text from
5611 the buffer you are in (and you have not seen the computer shift its
5612 attention, so you don't know that that buffer is now called
5613 @code{oldbuf}).
5614
5615 Incidentally, this is what is meant by `replacement'. To replace text,
5616 Emacs erases the previous text and then inserts new text.
5617
5618 @need 1250
5619 In outline, the body of @code{copy-to-buffer} looks like this:
5620
5621 @smallexample
5622 @group
5623 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5624 (@var{with-the-buffer-you-are-copying-to}
5625 (@var{but-do-not-erase-or-copy-to-a-read-only-buffer})
5626 (erase-buffer)
5627 (save-excursion
5628 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5629 @end group
5630 @end smallexample
5631
5632 @node insert-buffer
5633 @section The Definition of @code{insert-buffer}
5634 @findex insert-buffer
5635
5636 @code{insert-buffer} is yet another buffer-related function. This
5637 command copies another buffer @emph{into} the current buffer. It is the
5638 reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5639 copy a region of text @emph{from} the current buffer to another buffer.
5640
5641 Here is a discussion based on the original code. The code was
5642 simplified in 2003 and is harder to understand.
5643
5644 (@xref{New insert-buffer, , New Body for @code{insert-buffer}}, to see
5645 a discussion of the new body.)
5646
5647 In addition, this code illustrates the use of @code{interactive} with a
5648 buffer that might be @dfn{read-only} and the important distinction
5649 between the name of an object and the object actually referred to.
5650
5651 @menu
5652 * insert-buffer code::
5653 * insert-buffer interactive:: When you can read, but not write.
5654 * insert-buffer body:: The body has an @code{or} and a @code{let}.
5655 * if & or:: Using an @code{if} instead of an @code{or}.
5656 * Insert or:: How the @code{or} expression works.
5657 * Insert let:: Two @code{save-excursion} expressions.
5658 * New insert-buffer::
5659 @end menu
5660
5661 @ifnottex
5662 @node insert-buffer code
5663 @unnumberedsubsec The Code for @code{insert-buffer}
5664 @end ifnottex
5665
5666 @need 800
5667 Here is the earlier code:
5668
5669 @smallexample
5670 @group
5671 (defun insert-buffer (buffer)
5672 "Insert after point the contents of BUFFER.
5673 Puts mark after the inserted text.
5674 BUFFER may be a buffer or a buffer name."
5675 (interactive "*bInsert buffer:@: ")
5676 @end group
5677 @group
5678 (or (bufferp buffer)
5679 (setq buffer (get-buffer buffer)))
5680 (let (start end newmark)
5681 (save-excursion
5682 (save-excursion
5683 (set-buffer buffer)
5684 (setq start (point-min) end (point-max)))
5685 @end group
5686 @group
5687 (insert-buffer-substring buffer start end)
5688 (setq newmark (point)))
5689 (push-mark newmark)))
5690 @end group
5691 @end smallexample
5692
5693 @need 1200
5694 As with other function definitions, you can use a template to see an
5695 outline of the function:
5696
5697 @smallexample
5698 @group
5699 (defun insert-buffer (buffer)
5700 "@var{documentation}@dots{}"
5701 (interactive "*bInsert buffer:@: ")
5702 @var{body}@dots{})
5703 @end group
5704 @end smallexample
5705
5706 @node insert-buffer interactive
5707 @subsection The Interactive Expression in @code{insert-buffer}
5708 @findex interactive, @r{example use of}
5709
5710 In @code{insert-buffer}, the argument to the @code{interactive}
5711 declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5712 buffer:@: }.
5713
5714 @menu
5715 * Read-only buffer:: When a buffer cannot be modified.
5716 * b for interactive:: An existing buffer or else its name.
5717 @end menu
5718
5719 @node Read-only buffer
5720 @unnumberedsubsubsec A Read-only Buffer
5721 @cindex Read-only buffer
5722 @cindex Asterisk for read-only buffer
5723 @findex * @r{for read-only buffer}
5724
5725 The asterisk is for the situation when the current buffer is a
5726 read-only buffer---a buffer that cannot be modified. If
5727 @code{insert-buffer} is called when the current buffer is read-only, a
5728 message to this effect is printed in the echo area and the terminal
5729 may beep or blink at you; you will not be permitted to insert anything
5730 into current buffer. The asterisk does not need to be followed by a
5731 newline to separate it from the next argument.
5732
5733 @node b for interactive
5734 @unnumberedsubsubsec @samp{b} in an Interactive Expression
5735
5736 The next argument in the interactive expression starts with a lower
5737 case @samp{b}. (This is different from the code for
5738 @code{append-to-buffer}, which uses an upper-case @samp{B}.
5739 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5740 The lower-case @samp{b} tells the Lisp interpreter that the argument
5741 for @code{insert-buffer} should be an existing buffer or else its
5742 name. (The upper-case @samp{B} option provides for the possibility
5743 that the buffer does not exist.) Emacs will prompt you for the name
5744 of the buffer, offering you a default buffer, with name completion
5745 enabled. If the buffer does not exist, you receive a message that
5746 says ``No match''; your terminal may beep at you as well.
5747
5748 The new and simplified code generates a list for @code{interactive}.
5749 It uses the @code{barf-if-buffer-read-only} and @code{read-buffer}
5750 functions with which we are already familiar and the @code{progn}
5751 special form with which we are not. (It will be described later.)
5752
5753 @node insert-buffer body
5754 @subsection The Body of the @code{insert-buffer} Function
5755
5756 The body of the @code{insert-buffer} function has two major parts: an
5757 @code{or} expression and a @code{let} expression. The purpose of the
5758 @code{or} expression is to ensure that the argument @code{buffer} is
5759 bound to a buffer and not just the name of a buffer. The body of the
5760 @code{let} expression contains the code which copies the other buffer
5761 into the current buffer.
5762
5763 @need 1250
5764 In outline, the two expressions fit into the @code{insert-buffer}
5765 function like this:
5766
5767 @smallexample
5768 @group
5769 (defun insert-buffer (buffer)
5770 "@var{documentation}@dots{}"
5771 (interactive "*bInsert buffer:@: ")
5772 (or @dots{}
5773 @dots{}
5774 @end group
5775 @group
5776 (let (@var{varlist})
5777 @var{body-of-}@code{let}@dots{} )
5778 @end group
5779 @end smallexample
5780
5781 To understand how the @code{or} expression ensures that the argument
5782 @code{buffer} is bound to a buffer and not to the name of a buffer, it
5783 is first necessary to understand the @code{or} function.
5784
5785 Before doing this, let me rewrite this part of the function using
5786 @code{if} so that you can see what is done in a manner that will be familiar.
5787
5788 @node if & or
5789 @subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5790
5791 The job to be done is to make sure the value of @code{buffer} is a
5792 buffer itself and not the name of a buffer. If the value is the name,
5793 then the buffer itself must be got.
5794
5795 You can imagine yourself at a conference where an usher is wandering
5796 around holding a list with your name on it and looking for you: the
5797 usher is ``bound'' to your name, not to you; but when the usher finds
5798 you and takes your arm, the usher becomes ``bound'' to you.
5799
5800 @need 800
5801 In Lisp, you might describe this situation like this:
5802
5803 @smallexample
5804 @group
5805 (if (not (holding-on-to-guest))
5806 (find-and-take-arm-of-guest))
5807 @end group
5808 @end smallexample
5809
5810 We want to do the same thing with a buffer---if we do not have the
5811 buffer itself, we want to get it.
5812
5813 @need 1200
5814 Using a predicate called @code{bufferp} that tells us whether we have a
5815 buffer (rather than its name), we can write the code like this:
5816
5817 @smallexample
5818 @group
5819 (if (not (bufferp buffer)) ; @r{if-part}
5820 (setq buffer (get-buffer buffer))) ; @r{then-part}
5821 @end group
5822 @end smallexample
5823
5824 @noindent
5825 Here, the true-or-false-test of the @code{if} expression is
5826 @w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5827 @w{@code{(setq buffer (get-buffer buffer))}}.
5828
5829 In the test, the function @code{bufferp} returns true if its argument is
5830 a buffer---but false if its argument is the name of the buffer. (The
5831 last character of the function name @code{bufferp} is the character
5832 @samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5833 indicates that the function is a predicate, which is a term that means
5834 that the function will determine whether some property is true or false.
5835 @xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5836 Argument}.)
5837
5838 @need 1200
5839 The function @code{not} precedes the expression @code{(bufferp buffer)},
5840 so the true-or-false-test looks like this:
5841
5842 @smallexample
5843 (not (bufferp buffer))
5844 @end smallexample
5845
5846 @noindent
5847 @code{not} is a function that returns true if its argument is false
5848 and false if its argument is true. So if @code{(bufferp buffer)}
5849 returns true, the @code{not} expression returns false and vice-verse:
5850 what is ``not true'' is false and what is ``not false'' is true.
5851
5852 Using this test, the @code{if} expression works as follows: when the
5853 value of the variable @code{buffer} is actually a buffer rather than
5854 its name, the true-or-false-test returns false and the @code{if}
5855 expression does not evaluate the then-part. This is fine, since we do
5856 not need to do anything to the variable @code{buffer} if it really is
5857 a buffer.
5858
5859 On the other hand, when the value of @code{buffer} is not a buffer
5860 itself, but the name of a buffer, the true-or-false-test returns true
5861 and the then-part of the expression is evaluated. In this case, the
5862 then-part is @code{(setq buffer (get-buffer buffer))}. This
5863 expression uses the @code{get-buffer} function to return an actual
5864 buffer itself, given its name. The @code{setq} then sets the variable
5865 @code{buffer} to the value of the buffer itself, replacing its previous
5866 value (which was the name of the buffer).
5867
5868 @node Insert or
5869 @subsection The @code{or} in the Body
5870
5871 The purpose of the @code{or} expression in the @code{insert-buffer}
5872 function is to ensure that the argument @code{buffer} is bound to a
5873 buffer and not just to the name of a buffer. The previous section shows
5874 how the job could have been done using an @code{if} expression.
5875 However, the @code{insert-buffer} function actually uses @code{or}.
5876 To understand this, it is necessary to understand how @code{or} works.
5877
5878 @findex or
5879 An @code{or} function can have any number of arguments. It evaluates
5880 each argument in turn and returns the value of the first of its
5881 arguments that is not @code{nil}. Also, and this is a crucial feature
5882 of @code{or}, it does not evaluate any subsequent arguments after
5883 returning the first non-@code{nil} value.
5884
5885 @need 800
5886 The @code{or} expression looks like this:
5887
5888 @smallexample
5889 @group
5890 (or (bufferp buffer)
5891 (setq buffer (get-buffer buffer)))
5892 @end group
5893 @end smallexample
5894
5895 @noindent
5896 The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5897 This expression returns true (a non-@code{nil} value) if the buffer is
5898 actually a buffer, and not just the name of a buffer. In the @code{or}
5899 expression, if this is the case, the @code{or} expression returns this
5900 true value and does not evaluate the next expression---and this is fine
5901 with us, since we do not want to do anything to the value of
5902 @code{buffer} if it really is a buffer.
5903
5904 On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5905 which it will be if the value of @code{buffer} is the name of a buffer,
5906 the Lisp interpreter evaluates the next element of the @code{or}
5907 expression. This is the expression @code{(setq buffer (get-buffer
5908 buffer))}. This expression returns a non-@code{nil} value, which
5909 is the value to which it sets the variable @code{buffer}---and this
5910 value is a buffer itself, not the name of a buffer.
5911
5912 The result of all this is that the symbol @code{buffer} is always
5913 bound to a buffer itself rather than to the name of a buffer. All
5914 this is necessary because the @code{set-buffer} function in a
5915 following line only works with a buffer itself, not with the name to a
5916 buffer.
5917
5918 @need 1250
5919 Incidentally, using @code{or}, the situation with the usher would be
5920 written like this:
5921
5922 @smallexample
5923 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
5924 @end smallexample
5925
5926 @node Insert let
5927 @subsection The @code{let} Expression in @code{insert-buffer}
5928
5929 After ensuring that the variable @code{buffer} refers to a buffer itself
5930 and not just to the name of a buffer, the @code{insert-buffer function}
5931 continues with a @code{let} expression. This specifies three local
5932 variables, @code{start}, @code{end}, and @code{newmark} and binds them
5933 to the initial value @code{nil}. These variables are used inside the
5934 remainder of the @code{let} and temporarily hide any other occurrence of
5935 variables of the same name in Emacs until the end of the @code{let}.
5936
5937 @need 1200
5938 The body of the @code{let} contains two @code{save-excursion}
5939 expressions. First, we will look at the inner @code{save-excursion}
5940 expression in detail. The expression looks like this:
5941
5942 @smallexample
5943 @group
5944 (save-excursion
5945 (set-buffer buffer)
5946 (setq start (point-min) end (point-max)))
5947 @end group
5948 @end smallexample
5949
5950 @noindent
5951 The expression @code{(set-buffer buffer)} changes Emacs's attention
5952 from the current buffer to the one from which the text will copied.
5953 In that buffer, the variables @code{start} and @code{end} are set to
5954 the beginning and end of the buffer, using the commands
5955 @code{point-min} and @code{point-max}. Note that we have here an
5956 illustration of how @code{setq} is able to set two variables in the
5957 same expression. The first argument of @code{setq} is set to the
5958 value of its second, and its third argument is set to the value of its
5959 fourth.
5960
5961 After the body of the inner @code{save-excursion} is evaluated, the
5962 @code{save-excursion} restores the original buffer, but @code{start} and
5963 @code{end} remain set to the values of the beginning and end of the
5964 buffer from which the text will be copied.
5965
5966 @need 1250
5967 The outer @code{save-excursion} expression looks like this:
5968
5969 @smallexample
5970 @group
5971 (save-excursion
5972 (@var{inner-}@code{save-excursion}@var{-expression}
5973 (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5974 (insert-buffer-substring buffer start end)
5975 (setq newmark (point)))
5976 @end group
5977 @end smallexample
5978
5979 @noindent
5980 The @code{insert-buffer-substring} function copies the text
5981 @emph{into} the current buffer @emph{from} the region indicated by
5982 @code{start} and @code{end} in @code{buffer}. Since the whole of the
5983 second buffer lies between @code{start} and @code{end}, the whole of
5984 the second buffer is copied into the buffer you are editing. Next,
5985 the value of point, which will be at the end of the inserted text, is
5986 recorded in the variable @code{newmark}.
5987
5988 After the body of the outer @code{save-excursion} is evaluated, point
5989 and mark are relocated to their original places.
5990
5991 However, it is convenient to locate a mark at the end of the newly
5992 inserted text and locate point at its beginning. The @code{newmark}
5993 variable records the end of the inserted text. In the last line of
5994 the @code{let} expression, the @code{(push-mark newmark)} expression
5995 function sets a mark to this location. (The previous location of the
5996 mark is still accessible; it is recorded on the mark ring and you can
5997 go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is
5998 located at the beginning of the inserted text, which is where it was
5999 before you called the insert function, the position of which was saved
6000 by the first @code{save-excursion}.
6001
6002 @need 1250
6003 The whole @code{let} expression looks like this:
6004
6005 @smallexample
6006 @group
6007 (let (start end newmark)
6008 (save-excursion
6009 (save-excursion
6010 (set-buffer buffer)
6011 (setq start (point-min) end (point-max)))
6012 (insert-buffer-substring buffer start end)
6013 (setq newmark (point)))
6014 (push-mark newmark))
6015 @end group
6016 @end smallexample
6017
6018 Like the @code{append-to-buffer} function, the @code{insert-buffer}
6019 function uses @code{let}, @code{save-excursion}, and
6020 @code{set-buffer}. In addition, the function illustrates one way to
6021 use @code{or}. All these functions are building blocks that we will
6022 find and use again and again.
6023
6024 @node New insert-buffer
6025 @subsection New Body for @code{insert-buffer}
6026 @findex insert-buffer, new version body
6027 @findex new version body for insert-buffer
6028
6029 The body in the GNU Emacs 22 version is more confusing than the original.
6030
6031 @need 1250
6032 It consists of two expressions,
6033
6034 @smallexample
6035 @group
6036 (push-mark
6037 (save-excursion
6038 (insert-buffer-substring (get-buffer buffer))
6039 (point)))
6040
6041 nil
6042 @end group
6043 @end smallexample
6044
6045 @noindent
6046 except, and this is what confuses novices, very important work is done
6047 inside the @code{push-mark} expression.
6048
6049 The @code{get-buffer} function returns a buffer with the name
6050 provided. You will note that the function is @emph{not} called
6051 @code{get-buffer-create}; it does not create a buffer if one does not
6052 already exist. The buffer returned by @code{get-buffer}, an existing
6053 buffer, is passed to @code{insert-buffer-substring}, which inserts the
6054 whole of the buffer (since you did not specify anything else).
6055
6056 The location into which the buffer is inserted is recorded by
6057 @code{push-mark}. Then the function returns @code{nil}, the value of
6058 its last command. Put another way, the @code{insert-buffer} function
6059 exists only to produce a side effect, inserting another buffer, not to
6060 return any value.
6061
6062 @node beginning-of-buffer
6063 @section Complete Definition of @code{beginning-of-buffer}
6064 @findex beginning-of-buffer
6065
6066 The basic structure of the @code{beginning-of-buffer} function has
6067 already been discussed. (@xref{simplified-beginning-of-buffer, , A
6068 Simplified @code{beginning-of-buffer} Definition}.)
6069 This section describes the complex part of the definition.
6070
6071 As previously described, when invoked without an argument,
6072 @code{beginning-of-buffer} moves the cursor to the beginning of the
6073 buffer (in truth, the beginning of the accessible portion of the
6074 buffer), leaving the mark at the previous position. However, when the
6075 command is invoked with a number between one and ten, the function
6076 considers that number to be a fraction of the length of the buffer,
6077 measured in tenths, and Emacs moves the cursor that fraction of the
6078 way from the beginning of the buffer. Thus, you can either call this
6079 function with the key command @kbd{M-<}, which will move the cursor to
6080 the beginning of the buffer, or with a key command such as @kbd{C-u 7
6081 M-<} which will move the cursor to a point 70% of the way through the
6082 buffer. If a number bigger than ten is used for the argument, it
6083 moves to the end of the buffer.
6084
6085 The @code{beginning-of-buffer} function can be called with or without an
6086 argument. The use of the argument is optional.
6087
6088 @menu
6089 * Optional Arguments::
6090 * beginning-of-buffer opt arg:: Example with optional argument.
6091 * beginning-of-buffer complete::
6092 @end menu
6093
6094 @node Optional Arguments
6095 @subsection Optional Arguments
6096
6097 Unless told otherwise, Lisp expects that a function with an argument in
6098 its function definition will be called with a value for that argument.
6099 If that does not happen, you get an error and a message that says
6100 @samp{Wrong number of arguments}.
6101
6102 @cindex Optional arguments
6103 @cindex Keyword
6104 @findex optional
6105 However, optional arguments are a feature of Lisp: a particular
6106 @dfn{keyword} is used to tell the Lisp interpreter that an argument is
6107 optional. The keyword is @code{&optional}. (The @samp{&} in front of
6108 @samp{optional} is part of the keyword.) In a function definition, if
6109 an argument follows the keyword @code{&optional}, no value need be
6110 passed to that argument when the function is called.
6111
6112 @need 1200
6113 The first line of the function definition of @code{beginning-of-buffer}
6114 therefore looks like this:
6115
6116 @smallexample
6117 (defun beginning-of-buffer (&optional arg)
6118 @end smallexample
6119
6120 @need 1250
6121 In outline, the whole function looks like this:
6122
6123 @smallexample
6124 @group
6125 (defun beginning-of-buffer (&optional arg)
6126 "@var{documentation}@dots{}"
6127 (interactive "P")
6128 (or (@var{is-the-argument-a-cons-cell} arg)
6129 (and @var{are-both-transient-mark-mode-and-mark-active-true})
6130 (push-mark))
6131 (let (@var{determine-size-and-set-it})
6132 (goto-char
6133 (@var{if-there-is-an-argument}
6134 @var{figure-out-where-to-go}
6135 @var{else-go-to}
6136 (point-min))))
6137 @var{do-nicety}
6138 @end group
6139 @end smallexample
6140
6141 The function is similar to the @code{simplified-beginning-of-buffer}
6142 function except that the @code{interactive} expression has @code{"P"}
6143 as an argument and the @code{goto-char} function is followed by an
6144 if-then-else expression that figures out where to put the cursor if
6145 there is an argument that is not a cons cell.
6146
6147 (Since I do not explain a cons cell for many more chapters, please
6148 consider ignoring the function @code{consp}. @xref{List
6149 Implementation, , How Lists are Implemented}, and @ref{Cons Cell Type,
6150 , Cons Cell and List Types, elisp, The GNU Emacs Lisp Reference
6151 Manual}.)
6152
6153 The @code{"P"} in the @code{interactive} expression tells Emacs to
6154 pass a prefix argument, if there is one, to the function in raw form.
6155 A prefix argument is made by typing the @key{META} key followed by a
6156 number, or by typing @kbd{C-u} and then a number. (If you don't type
6157 a number, @kbd{C-u} defaults to a cons cell with a 4. A lowercase
6158 @code{"p"} in the @code{interactive} expression causes the function to
6159 convert a prefix arg to a number.)
6160
6161 The true-or-false-test of the @code{if} expression looks complex, but
6162 it is not: it checks whether @code{arg} has a value that is not
6163 @code{nil} and whether it is a cons cell. (That is what @code{consp}
6164 does; it checks whether its argument is a cons cell.) If @code{arg}
6165 has a value that is not @code{nil} (and is not a cons cell), which
6166 will be the case if @code{beginning-of-buffer} is called with a
6167 numeric argument, then this true-or-false-test will return true and
6168 the then-part of the @code{if} expression will be evaluated. On the
6169 other hand, if @code{beginning-of-buffer} is not called with an
6170 argument, the value of @code{arg} will be @code{nil} and the else-part
6171 of the @code{if} expression will be evaluated. The else-part is
6172 simply @code{point-min}, and when this is the outcome, the whole
6173 @code{goto-char} expression is @code{(goto-char (point-min))}, which
6174 is how we saw the @code{beginning-of-buffer} function in its
6175 simplified form.
6176
6177 @node beginning-of-buffer opt arg
6178 @subsection @code{beginning-of-buffer} with an Argument
6179
6180 When @code{beginning-of-buffer} is called with an argument, an
6181 expression is evaluated which calculates what value to pass to
6182 @code{goto-char}. This expression is rather complicated at first sight.
6183 It includes an inner @code{if} expression and much arithmetic. It looks
6184 like this:
6185
6186 @smallexample
6187 @group
6188 (if (> (buffer-size) 10000)
6189 ;; @r{Avoid overflow for large buffer sizes!}
6190 (* (prefix-numeric-value arg)
6191 (/ size 10))
6192 (/
6193 (+ 10
6194 (*
6195 size (prefix-numeric-value arg))) 10)))
6196 @end group
6197 @end smallexample
6198
6199 @menu
6200 * Disentangle beginning-of-buffer::
6201 * Large buffer case::
6202 * Small buffer case::
6203 @end menu
6204
6205 @ifnottex
6206 @node Disentangle beginning-of-buffer
6207 @unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
6208 @end ifnottex
6209
6210 Like other complex-looking expressions, the conditional expression
6211 within @code{beginning-of-buffer} can be disentangled by looking at it
6212 as parts of a template, in this case, the template for an if-then-else
6213 expression. In skeletal form, the expression looks like this:
6214
6215 @smallexample
6216 @group
6217 (if (@var{buffer-is-large}
6218 @var{divide-buffer-size-by-10-and-multiply-by-arg}
6219 @var{else-use-alternate-calculation}
6220 @end group
6221 @end smallexample
6222
6223 The true-or-false-test of this inner @code{if} expression checks the
6224 size of the buffer. The reason for this is that the old version 18
6225 Emacs used numbers that are no bigger than eight million or so and in
6226 the computation that followed, the programmer feared that Emacs might
6227 try to use over-large numbers if the buffer were large. The term
6228 `overflow', mentioned in the comment, means numbers that are over
6229 large. More recent versions of Emacs use larger numbers, but this
6230 code has not been touched, if only because people now look at buffers
6231 that are far, far larger than ever before.
6232
6233 There are two cases: if the buffer is large and if it is not.
6234
6235 @node Large buffer case
6236 @unnumberedsubsubsec What happens in a large buffer
6237
6238 In @code{beginning-of-buffer}, the inner @code{if} expression tests
6239 whether the size of the buffer is greater than 10,000 characters. To do
6240 this, it uses the @code{>} function and the computation of @code{size}
6241 that comes from the let expression.
6242
6243 In the old days, the function @code{buffer-size} was used. Not only
6244 was that function called several times, it gave the size of the whole
6245 buffer, not the accessible part. The computation makes much more
6246 sense when it handles just the accessible part. (@xref{Narrowing &
6247 Widening, , Narrowing and Widening}, for more information on focusing
6248 attention to an `accessible' part.)
6249
6250 @need 800
6251 The line looks like this:
6252
6253 @smallexample
6254 (if (> size 10000)
6255 @end smallexample
6256
6257 @need 1200
6258 @noindent
6259 When the buffer is large, the then-part of the @code{if} expression is
6260 evaluated. It reads like this (after formatting for easy reading):
6261
6262 @smallexample
6263 @group
6264 (*
6265 (prefix-numeric-value arg)
6266 (/ size 10))
6267 @end group
6268 @end smallexample
6269
6270 @noindent
6271 This expression is a multiplication, with two arguments to the function
6272 @code{*}.
6273
6274 The first argument is @code{(prefix-numeric-value arg)}. When
6275 @code{"P"} is used as the argument for @code{interactive}, the value
6276 passed to the function as its argument is passed a ``raw prefix
6277 argument'', and not a number. (It is a number in a list.) To perform
6278 the arithmetic, a conversion is necessary, and
6279 @code{prefix-numeric-value} does the job.
6280
6281 @findex / @r{(division)}
6282 @cindex Division
6283 The second argument is @code{(/ size 10)}. This expression divides
6284 the numeric value by ten --- the numeric value of the size of the
6285 accessible portion of the buffer. This produces a number that tells
6286 how many characters make up one tenth of the buffer size. (In Lisp,
6287 @code{/} is used for division, just as @code{*} is used for
6288 multiplication.)
6289
6290 @need 1200
6291 In the multiplication expression as a whole, this amount is multiplied
6292 by the value of the prefix argument---the multiplication looks like this:
6293
6294 @smallexample
6295 @group
6296 (* @var{numeric-value-of-prefix-arg}
6297 @var{number-of-characters-in-one-tenth-of-the-accessible-buffer})
6298 @end group
6299 @end smallexample
6300
6301 @noindent
6302 If, for example, the prefix argument is @samp{7}, the one-tenth value
6303 will be multiplied by 7 to give a position 70% of the way through.
6304
6305 @need 1200
6306 The result of all this is that if the accessible portion of the buffer
6307 is large, the @code{goto-char} expression reads like this:
6308
6309 @smallexample
6310 @group
6311 (goto-char (* (prefix-numeric-value arg)
6312 (/ size 10)))
6313 @end group
6314 @end smallexample
6315
6316 This puts the cursor where we want it.
6317
6318 @node Small buffer case
6319 @unnumberedsubsubsec What happens in a small buffer
6320
6321 If the buffer contains fewer than 10,000 characters, a slightly
6322 different computation is performed. You might think this is not
6323 necessary, since the first computation could do the job. However, in
6324 a small buffer, the first method may not put the cursor on exactly the
6325 desired line; the second method does a better job.
6326
6327 @need 800
6328 The code looks like this:
6329
6330 @c Keep this on one line.
6331 @smallexample
6332 (/ (+ 10 (* size (prefix-numeric-value arg))) 10))
6333 @end smallexample
6334
6335 @need 1200
6336 @noindent
6337 This is code in which you figure out what happens by discovering how the
6338 functions are embedded in parentheses. It is easier to read if you
6339 reformat it with each expression indented more deeply than its
6340 enclosing expression:
6341
6342 @smallexample
6343 @group
6344 (/
6345 (+ 10
6346 (*
6347 size
6348 (prefix-numeric-value arg)))
6349 10))
6350 @end group
6351 @end smallexample
6352
6353 @need 1200
6354 @noindent
6355 Looking at parentheses, we see that the innermost operation is
6356 @code{(prefix-numeric-value arg)}, which converts the raw argument to
6357 a number. In the following expression, this number is multiplied by
6358 the size of the accessible portion of the buffer:
6359
6360 @smallexample
6361 (* size (prefix-numeric-value arg))
6362 @end smallexample
6363
6364 @noindent
6365 This multiplication creates a number that may be larger than the size of
6366 the buffer---seven times larger if the argument is 7, for example. Ten
6367 is then added to this number and finally the large number is divided by
6368 ten to provide a value that is one character larger than the percentage
6369 position in the buffer.
6370
6371 The number that results from all this is passed to @code{goto-char} and
6372 the cursor is moved to that point.
6373
6374 @need 1500
6375 @node beginning-of-buffer complete
6376 @subsection The Complete @code{beginning-of-buffer}
6377
6378 @need 1000
6379 Here is the complete text of the @code{beginning-of-buffer} function:
6380 @sp 1
6381
6382 @c In GNU Emacs 22
6383 @smallexample
6384 @group
6385 (defun beginning-of-buffer (&optional arg)
6386 "Move point to the beginning of the buffer;
6387 leave mark at previous position.
6388 With \\[universal-argument] prefix,
6389 do not set mark at previous position.
6390 With numeric arg N,
6391 put point N/10 of the way from the beginning.
6392
6393 If the buffer is narrowed,
6394 this command uses the beginning and size
6395 of the accessible part of the buffer.
6396 @end group
6397
6398 @group
6399 Don't use this command in Lisp programs!
6400 \(goto-char (point-min)) is faster
6401 and avoids clobbering the mark."
6402 (interactive "P")
6403 (or (consp arg)
6404 (and transient-mark-mode mark-active)
6405 (push-mark))
6406 @end group
6407 @group
6408 (let ((size (- (point-max) (point-min))))
6409 (goto-char (if (and arg (not (consp arg)))
6410 (+ (point-min)
6411 (if (> size 10000)
6412 ;; Avoid overflow for large buffer sizes!
6413 (* (prefix-numeric-value arg)
6414 (/ size 10))
6415 (/ (+ 10 (* size (prefix-numeric-value arg)))
6416 10)))
6417 (point-min))))
6418 (if arg (forward-line 1)))
6419 @end group
6420 @end smallexample
6421
6422 @ignore
6423 From before GNU Emacs 22
6424 @smallexample
6425 @group
6426 (defun beginning-of-buffer (&optional arg)
6427 "Move point to the beginning of the buffer;
6428 leave mark at previous position.
6429 With arg N, put point N/10 of the way
6430 from the true beginning.
6431 @end group
6432 @group
6433 Don't use this in Lisp programs!
6434 \(goto-char (point-min)) is faster
6435 and does not set the mark."
6436 (interactive "P")
6437 (push-mark)
6438 @end group
6439 @group
6440 (goto-char
6441 (if arg
6442 (if (> (buffer-size) 10000)
6443 ;; @r{Avoid overflow for large buffer sizes!}
6444 (* (prefix-numeric-value arg)
6445 (/ (buffer-size) 10))
6446 @end group
6447 @group
6448 (/ (+ 10 (* (buffer-size)
6449 (prefix-numeric-value arg)))
6450 10))
6451 (point-min)))
6452 (if arg (forward-line 1)))
6453 @end group
6454 @end smallexample
6455 @end ignore
6456
6457 @noindent
6458 Except for two small points, the previous discussion shows how this
6459 function works. The first point deals with a detail in the
6460 documentation string, and the second point concerns the last line of
6461 the function.
6462
6463 @need 800
6464 In the documentation string, there is reference to an expression:
6465
6466 @smallexample
6467 \\[universal-argument]
6468 @end smallexample
6469
6470 @noindent
6471 A @samp{\\} is used before the first square bracket of this
6472 expression. This @samp{\\} tells the Lisp interpreter to substitute
6473 whatever key is currently bound to the @samp{[@dots{}]}. In the case
6474 of @code{universal-argument}, that is usually @kbd{C-u}, but it might
6475 be different. (@xref{Documentation Tips, , Tips for Documentation
6476 Strings, elisp, The GNU Emacs Lisp Reference Manual}, for more
6477 information.)
6478
6479 @need 1200
6480 Finally, the last line of the @code{beginning-of-buffer} command says
6481 to move point to the beginning of the next line if the command is
6482 invoked with an argument:
6483
6484 @smallexample
6485 (if arg (forward-line 1)))
6486 @end smallexample
6487
6488 @noindent
6489 This puts the cursor at the beginning of the first line after the
6490 appropriate tenths position in the buffer. This is a flourish that
6491 means that the cursor is always located @emph{at least} the requested
6492 tenths of the way through the buffer, which is a nicety that is,
6493 perhaps, not necessary, but which, if it did not occur, would be sure
6494 to draw complaints.
6495
6496 On the other hand, it also means that if you specify the command with
6497 a @kbd{C-u}, but without a number, that is to say, if the `raw prefix
6498 argument' is simply a cons cell, then the command puts you at the
6499 beginning of the second line @dots{} I don't know whether this is
6500 intended or whether no one has dealt with the code to avoid this
6501 happening.
6502
6503 @node Second Buffer Related Review
6504 @section Review
6505
6506 Here is a brief summary of some of the topics covered in this chapter.
6507
6508 @table @code
6509 @item or
6510 Evaluate each argument in sequence, and return the value of the first
6511 argument that is not @code{nil}; if none return a value that is not
6512 @code{nil}, return @code{nil}. In brief, return the first true value
6513 of the arguments; return a true value if one @emph{or} any of the
6514 others are true.
6515
6516 @item and
6517 Evaluate each argument in sequence, and if any are @code{nil}, return
6518 @code{nil}; if none are @code{nil}, return the value of the last
6519 argument. In brief, return a true value only if all the arguments are
6520 true; return a true value if one @emph{and} each of the others is
6521 true.
6522
6523 @item &optional
6524 A keyword used to indicate that an argument to a function definition
6525 is optional; this means that the function can be evaluated without the
6526 argument, if desired.
6527
6528 @item prefix-numeric-value
6529 Convert the `raw prefix argument' produced by @code{(interactive
6530 "P")} to a numeric value.
6531
6532 @item forward-line
6533 Move point forward to the beginning of the next line, or if the argument
6534 is greater than one, forward that many lines. If it can't move as far
6535 forward as it is supposed to, @code{forward-line} goes forward as far as
6536 it can and then returns a count of the number of additional lines it was
6537 supposed to move but couldn't.
6538
6539 @item erase-buffer
6540 Delete the entire contents of the current buffer.
6541
6542 @item bufferp
6543 Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6544 @end table
6545
6546 @node optional Exercise
6547 @section @code{optional} Argument Exercise
6548
6549 Write an interactive function with an optional argument that tests
6550 whether its argument, a number, is greater than or equal to, or else,
6551 less than the value of @code{fill-column}, and tells you which, in a
6552 message. However, if you do not pass an argument to the function, use
6553 56 as a default value.
6554
6555 @node Narrowing & Widening
6556 @chapter Narrowing and Widening
6557 @cindex Focusing attention (narrowing)
6558 @cindex Narrowing
6559 @cindex Widening
6560
6561 Narrowing is a feature of Emacs that makes it possible for you to focus
6562 on a specific part of a buffer, and work without accidentally changing
6563 other parts. Narrowing is normally disabled since it can confuse
6564 novices.
6565
6566 @menu
6567 * Narrowing advantages:: The advantages of narrowing
6568 * save-restriction:: The @code{save-restriction} special form.
6569 * what-line:: The number of the line that point is on.
6570 * narrow Exercise::
6571 @end menu
6572
6573 @ifnottex
6574 @node Narrowing advantages
6575 @unnumberedsec The Advantages of Narrowing
6576 @end ifnottex
6577
6578 With narrowing, the rest of a buffer is made invisible, as if it weren't
6579 there. This is an advantage if, for example, you want to replace a word
6580 in one part of a buffer but not in another: you narrow to the part you want
6581 and the replacement is carried out only in that section, not in the rest
6582 of the buffer. Searches will only work within a narrowed region, not
6583 outside of one, so if you are fixing a part of a document, you can keep
6584 yourself from accidentally finding parts you do not need to fix by
6585 narrowing just to the region you want.
6586 (The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6587
6588 However, narrowing does make the rest of the buffer invisible, which
6589 can scare people who inadvertently invoke narrowing and think they
6590 have deleted a part of their file. Moreover, the @code{undo} command
6591 (which is usually bound to @kbd{C-x u}) does not turn off narrowing
6592 (nor should it), so people can become quite desperate if they do not
6593 know that they can return the rest of a buffer to visibility with the
6594 @code{widen} command.
6595 (The key binding for @code{widen} is @kbd{C-x n w}.)
6596
6597 Narrowing is just as useful to the Lisp interpreter as to a human.
6598 Often, an Emacs Lisp function is designed to work on just part of a
6599 buffer; or conversely, an Emacs Lisp function needs to work on all of a
6600 buffer that has been narrowed. The @code{what-line} function, for
6601 example, removes the narrowing from a buffer, if it has any narrowing
6602 and when it has finished its job, restores the narrowing to what it was.
6603 On the other hand, the @code{count-lines} function
6604 uses narrowing to restrict itself to just that portion
6605 of the buffer in which it is interested and then restores the previous
6606 situation.
6607
6608 @node save-restriction
6609 @section The @code{save-restriction} Special Form
6610 @findex save-restriction
6611
6612 In Emacs Lisp, you can use the @code{save-restriction} special form to
6613 keep track of whatever narrowing is in effect, if any. When the Lisp
6614 interpreter meets with @code{save-restriction}, it executes the code
6615 in the body of the @code{save-restriction} expression, and then undoes
6616 any changes to narrowing that the code caused. If, for example, the
6617 buffer is narrowed and the code that follows @code{save-restriction}
6618 gets rid of the narrowing, @code{save-restriction} returns the buffer
6619 to its narrowed region afterwards. In the @code{what-line} command,
6620 any narrowing the buffer may have is undone by the @code{widen}
6621 command that immediately follows the @code{save-restriction} command.
6622 Any original narrowing is restored just before the completion of the
6623 function.
6624
6625 @need 1250
6626 The template for a @code{save-restriction} expression is simple:
6627
6628 @smallexample
6629 @group
6630 (save-restriction
6631 @var{body}@dots{} )
6632 @end group
6633 @end smallexample
6634
6635 @noindent
6636 The body of the @code{save-restriction} is one or more expressions that
6637 will be evaluated in sequence by the Lisp interpreter.
6638
6639 Finally, a point to note: when you use both @code{save-excursion} and
6640 @code{save-restriction}, one right after the other, you should use
6641 @code{save-excursion} outermost. If you write them in reverse order,
6642 you may fail to record narrowing in the buffer to which Emacs switches
6643 after calling @code{save-excursion}. Thus, when written together,
6644 @code{save-excursion} and @code{save-restriction} should be written
6645 like this:
6646
6647 @smallexample
6648 @group
6649 (save-excursion
6650 (save-restriction
6651 @var{body}@dots{}))
6652 @end group
6653 @end smallexample
6654
6655 In other circumstances, when not written together, the
6656 @code{save-excursion} and @code{save-restriction} special forms must
6657 be written in the order appropriate to the function.
6658
6659 @need 1250
6660 For example,
6661
6662 @smallexample
6663 @group
6664 (save-restriction
6665 (widen)
6666 (save-excursion
6667 @var{body}@dots{}))
6668 @end group
6669 @end smallexample
6670
6671 @ignore
6672 Emacs 22
6673 /usr/local/src/emacs/lisp/simple.el
6674
6675 (defun what-line ()
6676 "Print the current buffer line number and narrowed line number of point."
6677 (interactive)
6678 (let ((start (point-min))
6679 (n (line-number-at-pos)))
6680 (if (= start 1)
6681 (message "Line %d" n)
6682 (save-excursion
6683 (save-restriction
6684 (widen)
6685 (message "line %d (narrowed line %d)"
6686 (+ n (line-number-at-pos start) -1) n))))))
6687
6688 (defun line-number-at-pos (&optional pos)
6689 "Return (narrowed) buffer line number at position POS.
6690 If POS is nil, use current buffer location.
6691 Counting starts at (point-min), so the value refers
6692 to the contents of the accessible portion of the buffer."
6693 (let ((opoint (or pos (point))) start)
6694 (save-excursion
6695 (goto-char (point-min))
6696 (setq start (point))
6697 (goto-char opoint)
6698 (forward-line 0)
6699 (1+ (count-lines start (point))))))
6700
6701 (defun count-lines (start end)
6702 "Return number of lines between START and END.
6703 This is usually the number of newlines between them,
6704 but can be one more if START is not equal to END
6705 and the greater of them is not at the start of a line."
6706 (save-excursion
6707 (save-restriction
6708 (narrow-to-region start end)
6709 (goto-char (point-min))
6710 (if (eq selective-display t)
6711 (save-match-data
6712 (let ((done 0))
6713 (while (re-search-forward "[\n\C-m]" nil t 40)
6714 (setq done (+ 40 done)))
6715 (while (re-search-forward "[\n\C-m]" nil t 1)
6716 (setq done (+ 1 done)))
6717 (goto-char (point-max))
6718 (if (and (/= start end)
6719 (not (bolp)))
6720 (1+ done)
6721 done)))
6722 (- (buffer-size) (forward-line (buffer-size)))))))
6723 @end ignore
6724
6725 @node what-line
6726 @section @code{what-line}
6727 @findex what-line
6728 @cindex Widening, example of
6729
6730 The @code{what-line} command tells you the number of the line in which
6731 the cursor is located. The function illustrates the use of the
6732 @code{save-restriction} and @code{save-excursion} commands. Here is the
6733 original text of the function:
6734
6735 @smallexample
6736 @group
6737 (defun what-line ()
6738 "Print the current line number (in the buffer) of point."
6739 (interactive)
6740 (save-restriction
6741 (widen)
6742 (save-excursion
6743 (beginning-of-line)
6744 (message "Line %d"
6745 (1+ (count-lines 1 (point)))))))
6746 @end group
6747 @end smallexample
6748
6749 (In recent versions of GNU Emacs, the @code{what-line} function has
6750 been expanded to tell you your line number in a narrowed buffer as
6751 well as your line number in a widened buffer. The recent version is
6752 more complex than the version shown here. If you feel adventurous,
6753 you might want to look at it after figuring out how this version
6754 works. You will probably need to use @kbd{C-h f}
6755 (@code{describe-function}). The newer version uses a conditional to
6756 determine whether the buffer has been narrowed.
6757
6758 (Also, it uses @code{line-number-at-pos}, which among other simple
6759 expressions, such as @code{(goto-char (point-min))}, moves point to
6760 the beginning of the current line with @code{(forward-line 0)} rather
6761 than @code{beginning-of-line}.)
6762
6763 The @code{what-line} function as shown here has a documentation line
6764 and is interactive, as you would expect. The next two lines use the
6765 functions @code{save-restriction} and @code{widen}.
6766
6767 The @code{save-restriction} special form notes whatever narrowing is in
6768 effect, if any, in the current buffer and restores that narrowing after
6769 the code in the body of the @code{save-restriction} has been evaluated.
6770
6771 The @code{save-restriction} special form is followed by @code{widen}.
6772 This function undoes any narrowing the current buffer may have had
6773 when @code{what-line} was called. (The narrowing that was there is
6774 the narrowing that @code{save-restriction} remembers.) This widening
6775 makes it possible for the line counting commands to count from the
6776 beginning of the buffer. Otherwise, they would have been limited to
6777 counting within the accessible region. Any original narrowing is
6778 restored just before the completion of the function by the
6779 @code{save-restriction} special form.
6780
6781 The call to @code{widen} is followed by @code{save-excursion}, which
6782 saves the location of the cursor (i.e., of point) and of the mark, and
6783 restores them after the code in the body of the @code{save-excursion}
6784 uses the @code{beginning-of-line} function to move point.
6785
6786 (Note that the @code{(widen)} expression comes between the
6787 @code{save-restriction} and @code{save-excursion} special forms. When
6788 you write the two @code{save- @dots{}} expressions in sequence, write
6789 @code{save-excursion} outermost.)
6790
6791 @need 1200
6792 The last two lines of the @code{what-line} function are functions to
6793 count the number of lines in the buffer and then print the number in the
6794 echo area.
6795
6796 @smallexample
6797 @group
6798 (message "Line %d"
6799 (1+ (count-lines 1 (point)))))))
6800 @end group
6801 @end smallexample
6802
6803 The @code{message} function prints a one-line message at the bottom of
6804 the Emacs screen. The first argument is inside of quotation marks and
6805 is printed as a string of characters. However, it may contain a
6806 @samp{%d} expression to print a following argument. @samp{%d} prints
6807 the argument as a decimal, so the message will say something such as
6808 @samp{Line 243}.
6809
6810 @need 1200
6811 The number that is printed in place of the @samp{%d} is computed by the
6812 last line of the function:
6813
6814 @smallexample
6815 (1+ (count-lines 1 (point)))
6816 @end smallexample
6817
6818 @ignore
6819 GNU Emacs 22
6820
6821 (defun count-lines (start end)
6822 "Return number of lines between START and END.
6823 This is usually the number of newlines between them,
6824 but can be one more if START is not equal to END
6825 and the greater of them is not at the start of a line."
6826 (save-excursion
6827 (save-restriction
6828 (narrow-to-region start end)
6829 (goto-char (point-min))
6830 (if (eq selective-display t)
6831 (save-match-data
6832 (let ((done 0))
6833 (while (re-search-forward "[\n\C-m]" nil t 40)
6834 (setq done (+ 40 done)))
6835 (while (re-search-forward "[\n\C-m]" nil t 1)
6836 (setq done (+ 1 done)))
6837 (goto-char (point-max))
6838 (if (and (/= start end)
6839 (not (bolp)))
6840 (1+ done)
6841 done)))
6842 (- (buffer-size) (forward-line (buffer-size)))))))
6843 @end ignore
6844
6845 @noindent
6846 What this does is count the lines from the first position of the
6847 buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6848 one to that number. (The @code{1+} function adds one to its
6849 argument.) We add one to it because line 2 has only one line before
6850 it, and @code{count-lines} counts only the lines @emph{before} the
6851 current line.
6852
6853 After @code{count-lines} has done its job, and the message has been
6854 printed in the echo area, the @code{save-excursion} restores point and
6855 mark to their original positions; and @code{save-restriction} restores
6856 the original narrowing, if any.
6857
6858 @node narrow Exercise
6859 @section Exercise with Narrowing
6860
6861 Write a function that will display the first 60 characters of the
6862 current buffer, even if you have narrowed the buffer to its latter
6863 half so that the first line is inaccessible. Restore point, mark, and
6864 narrowing. For this exercise, you need to use a whole potpourri of
6865 functions, including @code{save-restriction}, @code{widen},
6866 @code{goto-char}, @code{point-min}, @code{message}, and
6867 @code{buffer-substring}.
6868
6869 @cindex Properties, mention of @code{buffer-substring-no-properties}
6870 (@code{buffer-substring} is a previously unmentioned function you will
6871 have to investigate yourself; or perhaps you will have to use
6872 @code{buffer-substring-no-properties} or
6873 @code{filter-buffer-substring} @dots{}, yet other functions. Text
6874 properties are a feature otherwise not discussed here. @xref{Text
6875 Properties, , Text Properties, elisp, The GNU Emacs Lisp Reference
6876 Manual}.)
6877
6878 Additionally, do you really need @code{goto-char} or @code{point-min}?
6879 Or can you write the function without them?
6880
6881 @node car cdr & cons
6882 @chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6883 @findex car, @r{introduced}
6884 @findex cdr, @r{introduced}
6885
6886 In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6887 functions. The @code{cons} function is used to construct lists, and
6888 the @code{car} and @code{cdr} functions are used to take them apart.
6889
6890 In the walk through of the @code{copy-region-as-kill} function, we
6891 will see @code{cons} as well as two variants on @code{cdr},
6892 namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.)
6893
6894 @menu
6895 * Strange Names:: An historical aside: why the strange names?
6896 * car & cdr:: Functions for extracting part of a list.
6897 * cons:: Constructing a list.
6898 * nthcdr:: Calling @code{cdr} repeatedly.
6899 * nth::
6900 * setcar:: Changing the first element of a list.
6901 * setcdr:: Changing the rest of a list.
6902 * cons Exercise::
6903 @end menu
6904
6905 @ifnottex
6906 @node Strange Names
6907 @unnumberedsec Strange Names
6908 @end ifnottex
6909
6910 The name of the @code{cons} function is not unreasonable: it is an
6911 abbreviation of the word `construct'. The origins of the names for
6912 @code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6913 is an acronym from the phrase `Contents of the Address part of the
6914 Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6915 the phrase `Contents of the Decrement part of the Register'. These
6916 phrases refer to specific pieces of hardware on the very early
6917 computer on which the original Lisp was developed. Besides being
6918 obsolete, the phrases have been completely irrelevant for more than 25
6919 years to anyone thinking about Lisp. Nonetheless, although a few
6920 brave scholars have begun to use more reasonable names for these
6921 functions, the old terms are still in use. In particular, since the
6922 terms are used in the Emacs Lisp source code, we will use them in this
6923 introduction.
6924
6925 @node car & cdr
6926 @section @code{car} and @code{cdr}
6927
6928 The @sc{car} of a list is, quite simply, the first item in the list.
6929 Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6930 @code{rose}.
6931
6932 @need 1200
6933 If you are reading this in Info in GNU Emacs, you can see this by
6934 evaluating the following:
6935
6936 @smallexample
6937 (car '(rose violet daisy buttercup))
6938 @end smallexample
6939
6940 @noindent
6941 After evaluating the expression, @code{rose} will appear in the echo
6942 area.
6943
6944 Clearly, a more reasonable name for the @code{car} function would be
6945 @code{first} and this is often suggested.
6946
6947 @code{car} does not remove the first item from the list; it only reports
6948 what it is. After @code{car} has been applied to a list, the list is
6949 still the same as it was. In the jargon, @code{car} is
6950 `non-destructive'. This feature turns out to be important.
6951
6952 The @sc{cdr} of a list is the rest of the list, that is, the
6953 @code{cdr} function returns the part of the list that follows the
6954 first item. Thus, while the @sc{car} of the list @code{'(rose violet
6955 daisy buttercup)} is @code{rose}, the rest of the list, the value
6956 returned by the @code{cdr} function, is @code{(violet daisy
6957 buttercup)}.
6958
6959 @need 800
6960 You can see this by evaluating the following in the usual way:
6961
6962 @smallexample
6963 (cdr '(rose violet daisy buttercup))
6964 @end smallexample
6965
6966 @noindent
6967 When you evaluate this, @code{(violet daisy buttercup)} will appear in
6968 the echo area.
6969
6970 Like @code{car}, @code{cdr} does not remove any elements from the
6971 list---it just returns a report of what the second and subsequent
6972 elements are.
6973
6974 Incidentally, in the example, the list of flowers is quoted. If it were
6975 not, the Lisp interpreter would try to evaluate the list by calling
6976 @code{rose} as a function. In this example, we do not want to do that.
6977
6978 Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6979
6980 (There is a lesson here: when you name new functions, consider very
6981 carefully what you are doing, since you may be stuck with the names
6982 for far longer than you expect. The reason this document perpetuates
6983 these names is that the Emacs Lisp source code uses them, and if I did
6984 not use them, you would have a hard time reading the code; but do,
6985 please, try to avoid using these terms yourself. The people who come
6986 after you will be grateful to you.)
6987
6988 When @code{car} and @code{cdr} are applied to a list made up of symbols,
6989 such as the list @code{(pine fir oak maple)}, the element of the list
6990 returned by the function @code{car} is the symbol @code{pine} without
6991 any parentheses around it. @code{pine} is the first element in the
6992 list. However, the @sc{cdr} of the list is a list itself, @code{(fir
6993 oak maple)}, as you can see by evaluating the following expressions in
6994 the usual way:
6995
6996 @smallexample
6997 @group
6998 (car '(pine fir oak maple))
6999
7000 (cdr '(pine fir oak maple))
7001 @end group
7002 @end smallexample
7003
7004 On the other hand, in a list of lists, the first element is itself a
7005 list. @code{car} returns this first element as a list. For example,
7006 the following list contains three sub-lists, a list of carnivores, a
7007 list of herbivores and a list of sea mammals:
7008
7009 @smallexample
7010 @group
7011 (car '((lion tiger cheetah)
7012 (gazelle antelope zebra)
7013 (whale dolphin seal)))
7014 @end group
7015 @end smallexample
7016
7017 @noindent
7018 In this example, the first element or @sc{car} of the list is the list of
7019 carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
7020 @code{((gazelle antelope zebra) (whale dolphin seal))}.
7021
7022 @smallexample
7023 @group
7024 (cdr '((lion tiger cheetah)
7025 (gazelle antelope zebra)
7026 (whale dolphin seal)))
7027 @end group
7028 @end smallexample
7029
7030 It is worth saying again that @code{car} and @code{cdr} are
7031 non-destructive---that is, they do not modify or change lists to which
7032 they are applied. This is very important for how they are used.
7033
7034 Also, in the first chapter, in the discussion about atoms, I said that
7035 in Lisp, ``certain kinds of atom, such as an array, can be separated
7036 into parts; but the mechanism for doing this is different from the
7037 mechanism for splitting a list. As far as Lisp is concerned, the
7038 atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The
7039 @code{car} and @code{cdr} functions are used for splitting lists and
7040 are considered fundamental to Lisp. Since they cannot split or gain
7041 access to the parts of an array, an array is considered an atom.
7042 Conversely, the other fundamental function, @code{cons}, can put
7043 together or construct a list, but not an array. (Arrays are handled
7044 by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU
7045 Emacs Lisp Reference Manual}.)
7046
7047 @node cons
7048 @section @code{cons}
7049 @findex cons, @r{introduced}
7050
7051 The @code{cons} function constructs lists; it is the inverse of
7052 @code{car} and @code{cdr}. For example, @code{cons} can be used to make
7053 a four element list from the three element list, @code{(fir oak maple)}:
7054
7055 @smallexample
7056 (cons 'pine '(fir oak maple))
7057 @end smallexample
7058
7059 @need 800
7060 @noindent
7061 After evaluating this list, you will see
7062
7063 @smallexample
7064 (pine fir oak maple)
7065 @end smallexample
7066
7067 @noindent
7068 appear in the echo area. @code{cons} causes the creation of a new
7069 list in which the element is followed by the elements of the original
7070 list.
7071
7072 We often say that `@code{cons} puts a new element at the beginning of
7073 a list; it attaches or pushes elements onto the list', but this
7074 phrasing can be misleading, since @code{cons} does not change an
7075 existing list, but creates a new one.
7076
7077 Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
7078
7079 @menu
7080 * Build a list::
7081 * length:: How to find the length of a list.
7082 @end menu
7083
7084 @ifnottex
7085 @node Build a list
7086 @unnumberedsubsec Build a list
7087 @end ifnottex
7088
7089 @code{cons} must have a list to attach to.@footnote{Actually, you can
7090 @code{cons} an element to an atom to produce a dotted pair. Dotted
7091 pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
7092 Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You
7093 cannot start from absolutely nothing. If you are building a list, you
7094 need to provide at least an empty list at the beginning. Here is a
7095 series of @code{cons} expressions that build up a list of flowers. If
7096 you are reading this in Info in GNU Emacs, you can evaluate each of
7097 the expressions in the usual way; the value is printed in this text
7098 after @samp{@result{}}, which you may read as `evaluates to'.
7099
7100 @smallexample
7101 @group
7102 (cons 'buttercup ())
7103 @result{} (buttercup)
7104 @end group
7105
7106 @group
7107 (cons 'daisy '(buttercup))
7108 @result{} (daisy buttercup)
7109 @end group
7110
7111 @group
7112 (cons 'violet '(daisy buttercup))
7113 @result{} (violet daisy buttercup)
7114 @end group
7115
7116 @group
7117 (cons 'rose '(violet daisy buttercup))
7118 @result{} (rose violet daisy buttercup)
7119 @end group
7120 @end smallexample
7121
7122 @noindent
7123 In the first example, the empty list is shown as @code{()} and a list
7124 made up of @code{buttercup} followed by the empty list is constructed.
7125 As you can see, the empty list is not shown in the list that was
7126 constructed. All that you see is @code{(buttercup)}. The empty list is
7127 not counted as an element of a list because there is nothing in an empty
7128 list. Generally speaking, an empty list is invisible.
7129
7130 The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
7131 two element list by putting @code{daisy} in front of @code{buttercup};
7132 and the third example constructs a three element list by putting
7133 @code{violet} in front of @code{daisy} and @code{buttercup}.
7134
7135 @node length
7136 @subsection Find the Length of a List: @code{length}
7137 @findex length
7138
7139 You can find out how many elements there are in a list by using the Lisp
7140 function @code{length}, as in the following examples:
7141
7142 @smallexample
7143 @group
7144 (length '(buttercup))
7145 @result{} 1
7146 @end group
7147
7148 @group
7149 (length '(daisy buttercup))
7150 @result{} 2
7151 @end group
7152
7153 @group
7154 (length (cons 'violet '(daisy buttercup)))
7155 @result{} 3
7156 @end group
7157 @end smallexample
7158
7159 @noindent
7160 In the third example, the @code{cons} function is used to construct a
7161 three element list which is then passed to the @code{length} function as
7162 its argument.
7163
7164 @need 1200
7165 We can also use @code{length} to count the number of elements in an
7166 empty list:
7167
7168 @smallexample
7169 @group
7170 (length ())
7171 @result{} 0
7172 @end group
7173 @end smallexample
7174
7175 @noindent
7176 As you would expect, the number of elements in an empty list is zero.
7177
7178 An interesting experiment is to find out what happens if you try to find
7179 the length of no list at all; that is, if you try to call @code{length}
7180 without giving it an argument, not even an empty list:
7181
7182 @smallexample
7183 (length )
7184 @end smallexample
7185
7186 @need 800
7187 @noindent
7188 What you see, if you evaluate this, is the error message
7189
7190 @smallexample
7191 Lisp error: (wrong-number-of-arguments length 0)
7192 @end smallexample
7193
7194 @noindent
7195 This means that the function receives the wrong number of
7196 arguments, zero, when it expects some other number of arguments. In
7197 this case, one argument is expected, the argument being a list whose
7198 length the function is measuring. (Note that @emph{one} list is
7199 @emph{one} argument, even if the list has many elements inside it.)
7200
7201 The part of the error message that says @samp{length} is the name of
7202 the function.
7203
7204 @ignore
7205 @code{length} is still a subroutine, but you need C-h f to discover that.
7206
7207 In an earlier version:
7208 This is written with a special notation, @samp{#<subr},
7209 that indicates that the function @code{length} is one of the primitive
7210 functions written in C rather than in Emacs Lisp. (@samp{subr} is an
7211 abbreviation for `subroutine'.) @xref{What Is a Function, , What Is a
7212 Function?, elisp , The GNU Emacs Lisp Reference Manual}, for more
7213 about subroutines.
7214 @end ignore
7215
7216 @node nthcdr
7217 @section @code{nthcdr}
7218 @findex nthcdr
7219
7220 The @code{nthcdr} function is associated with the @code{cdr} function.
7221 What it does is take the @sc{cdr} of a list repeatedly.
7222
7223 If you take the @sc{cdr} of the list @code{(pine fir
7224 oak maple)}, you will be returned the list @code{(fir oak maple)}. If you
7225 repeat this on what was returned, you will be returned the list
7226 @code{(oak maple)}. (Of course, repeated @sc{cdr}ing on the original
7227 list will just give you the original @sc{cdr} since the function does
7228 not change the list. You need to evaluate the @sc{cdr} of the
7229 @sc{cdr} and so on.) If you continue this, eventually you will be
7230 returned an empty list, which in this case, instead of being shown as
7231 @code{()} is shown as @code{nil}.
7232
7233 @need 1200
7234 For review, here is a series of repeated @sc{cdr}s, the text following
7235 the @samp{@result{}} shows what is returned.
7236
7237 @smallexample
7238 @group
7239 (cdr '(pine fir oak maple))
7240 @result{}(fir oak maple)
7241 @end group
7242
7243 @group
7244 (cdr '(fir oak maple))
7245 @result{} (oak maple)
7246 @end group
7247
7248 @group
7249 (cdr '(oak maple))
7250 @result{}(maple)
7251 @end group
7252
7253 @group
7254 (cdr '(maple))
7255 @result{} nil
7256 @end group
7257
7258 @group
7259 (cdr 'nil)
7260 @result{} nil
7261 @end group
7262
7263 @group
7264 (cdr ())
7265 @result{} nil
7266 @end group
7267 @end smallexample
7268
7269 @need 1200
7270 You can also do several @sc{cdr}s without printing the values in
7271 between, like this:
7272
7273 @smallexample
7274 @group
7275 (cdr (cdr '(pine fir oak maple)))
7276 @result{} (oak maple)
7277 @end group
7278 @end smallexample
7279
7280 @noindent
7281 In this example, the Lisp interpreter evaluates the innermost list first.
7282 The innermost list is quoted, so it just passes the list as it is to the
7283 innermost @code{cdr}. This @code{cdr} passes a list made up of the
7284 second and subsequent elements of the list to the outermost @code{cdr},
7285 which produces a list composed of the third and subsequent elements of
7286 the original list. In this example, the @code{cdr} function is repeated
7287 and returns a list that consists of the original list without its
7288 first two elements.
7289
7290 The @code{nthcdr} function does the same as repeating the call to
7291 @code{cdr}. In the following example, the argument 2 is passed to the
7292 function @code{nthcdr}, along with the list, and the value returned is
7293 the list without its first two items, which is exactly the same
7294 as repeating @code{cdr} twice on the list:
7295
7296 @smallexample
7297 @group
7298 (nthcdr 2 '(pine fir oak maple))
7299 @result{} (oak maple)
7300 @end group
7301 @end smallexample
7302
7303 @need 1200
7304 Using the original four element list, we can see what happens when
7305 various numeric arguments are passed to @code{nthcdr}, including 0, 1,
7306 and 5:
7307
7308 @smallexample
7309 @group
7310 ;; @r{Leave the list as it was.}
7311 (nthcdr 0 '(pine fir oak maple))
7312 @result{} (pine fir oak maple)
7313 @end group
7314
7315 @group
7316 ;; @r{Return a copy without the first element.}
7317 (nthcdr 1 '(pine fir oak maple))
7318 @result{} (fir oak maple)
7319 @end group
7320
7321 @group
7322 ;; @r{Return a copy of the list without three elements.}
7323 (nthcdr 3 '(pine fir oak maple))
7324 @result{} (maple)
7325 @end group
7326
7327 @group
7328 ;; @r{Return a copy lacking all four elements.}
7329 (nthcdr 4 '(pine fir oak maple))
7330 @result{} nil
7331 @end group
7332
7333 @group
7334 ;; @r{Return a copy lacking all elements.}
7335 (nthcdr 5 '(pine fir oak maple))
7336 @result{} nil
7337 @end group
7338 @end smallexample
7339
7340 @node nth
7341 @section @code{nth}
7342 @findex nth
7343
7344 The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
7345 The @code{nth} function takes the @sc{car} of the result returned by
7346 @code{nthcdr}. It returns the Nth element of the list.
7347
7348 @need 1500
7349 Thus, if it were not defined in C for speed, the definition of
7350 @code{nth} would be:
7351
7352 @smallexample
7353 @group
7354 (defun nth (n list)
7355 "Returns the Nth element of LIST.
7356 N counts from zero. If LIST is not that long, nil is returned."
7357 (car (nthcdr n list)))
7358 @end group
7359 @end smallexample
7360
7361 @noindent
7362 (Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
7363 but its definition was redone in C in the 1980s.)
7364
7365 The @code{nth} function returns a single element of a list.
7366 This can be very convenient.
7367
7368 Note that the elements are numbered from zero, not one. That is to
7369 say, the first element of a list, its @sc{car} is the zeroth element.
7370 This is called `zero-based' counting and often bothers people who
7371 are accustomed to the first element in a list being number one, which
7372 is `one-based'.
7373
7374 @need 1250
7375 For example:
7376
7377 @smallexample
7378 @group
7379 (nth 0 '("one" "two" "three"))
7380 @result{} "one"
7381
7382 (nth 1 '("one" "two" "three"))
7383 @result{} "two"
7384 @end group
7385 @end smallexample
7386
7387 It is worth mentioning that @code{nth}, like @code{nthcdr} and
7388 @code{cdr}, does not change the original list---the function is
7389 non-destructive. This is in sharp contrast to the @code{setcar} and
7390 @code{setcdr} functions.
7391
7392 @node setcar
7393 @section @code{setcar}
7394 @findex setcar
7395
7396 As you might guess from their names, the @code{setcar} and @code{setcdr}
7397 functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7398 They actually change the original list, unlike @code{car} and @code{cdr}
7399 which leave the original list as it was. One way to find out how this
7400 works is to experiment. We will start with the @code{setcar} function.
7401
7402 @need 1200
7403 First, we can make a list and then set the value of a variable to the
7404 list, using the @code{setq} function. Here is a list of animals:
7405
7406 @smallexample
7407 (setq animals '(antelope giraffe lion tiger))
7408 @end smallexample
7409
7410 @noindent
7411 If you are reading this in Info inside of GNU Emacs, you can evaluate
7412 this expression in the usual fashion, by positioning the cursor after
7413 the expression and typing @kbd{C-x C-e}. (I'm doing this right here
7414 as I write this. This is one of the advantages of having the
7415 interpreter built into the computing environment. Incidentally, when
7416 there is nothing on the line after the final parentheses, such as a
7417 comment, point can be on the next line. Thus, if your cursor is in
7418 the first column of the next line, you do not need to move it.
7419 Indeed, Emacs permits any amount of white space after the final
7420 parenthesis.)
7421
7422 @need 1200
7423 When we evaluate the variable @code{animals}, we see that it is bound to
7424 the list @code{(antelope giraffe lion tiger)}:
7425
7426 @smallexample
7427 @group
7428 animals
7429 @result{} (antelope giraffe lion tiger)
7430 @end group
7431 @end smallexample
7432
7433 @noindent
7434 Put another way, the variable @code{animals} points to the list
7435 @code{(antelope giraffe lion tiger)}.
7436
7437 Next, evaluate the function @code{setcar} while passing it two
7438 arguments, the variable @code{animals} and the quoted symbol
7439 @code{hippopotamus}; this is done by writing the three element list
7440 @code{(setcar animals 'hippopotamus)} and then evaluating it in the
7441 usual fashion:
7442
7443 @smallexample
7444 (setcar animals 'hippopotamus)
7445 @end smallexample
7446
7447 @need 1200
7448 @noindent
7449 After evaluating this expression, evaluate the variable @code{animals}
7450 again. You will see that the list of animals has changed:
7451
7452 @smallexample
7453 @group
7454 animals
7455 @result{} (hippopotamus giraffe lion tiger)
7456 @end group
7457 @end smallexample
7458
7459 @noindent
7460 The first element on the list, @code{antelope} is replaced by
7461 @code{hippopotamus}.
7462
7463 So we can see that @code{setcar} did not add a new element to the list
7464 as @code{cons} would have; it replaced @code{antelope} with
7465 @code{hippopotamus}; it @emph{changed} the list.
7466
7467 @node setcdr
7468 @section @code{setcdr}
7469 @findex setcdr
7470
7471 The @code{setcdr} function is similar to the @code{setcar} function,
7472 except that the function replaces the second and subsequent elements of
7473 a list rather than the first element.
7474
7475 (To see how to change the last element of a list, look ahead to
7476 @ref{kill-new function, , The @code{kill-new} function}, which uses
7477 the @code{nthcdr} and @code{setcdr} functions.)
7478
7479 @need 1200
7480 To see how this works, set the value of the variable to a list of
7481 domesticated animals by evaluating the following expression:
7482
7483 @smallexample
7484 (setq domesticated-animals '(horse cow sheep goat))
7485 @end smallexample
7486
7487 @need 1200
7488 @noindent
7489 If you now evaluate the list, you will be returned the list
7490 @code{(horse cow sheep goat)}:
7491
7492 @smallexample
7493 @group
7494 domesticated-animals
7495 @result{} (horse cow sheep goat)
7496 @end group
7497 @end smallexample
7498
7499 @need 1200
7500 Next, evaluate @code{setcdr} with two arguments, the name of the
7501 variable which has a list as its value, and the list to which the
7502 @sc{cdr} of the first list will be set;
7503
7504 @smallexample
7505 (setcdr domesticated-animals '(cat dog))
7506 @end smallexample
7507
7508 @noindent
7509 If you evaluate this expression, the list @code{(cat dog)} will appear
7510 in the echo area. This is the value returned by the function. The
7511 result we are interested in is the ``side effect'', which we can see by
7512 evaluating the variable @code{domesticated-animals}:
7513
7514 @smallexample
7515 @group
7516 domesticated-animals
7517 @result{} (horse cat dog)
7518 @end group
7519 @end smallexample
7520
7521 @noindent
7522 Indeed, the list is changed from @code{(horse cow sheep goat)} to
7523 @code{(horse cat dog)}. The @sc{cdr} of the list is changed from
7524 @code{(cow sheep goat)} to @code{(cat dog)}.
7525
7526 @node cons Exercise
7527 @section Exercise
7528
7529 Construct a list of four birds by evaluating several expressions with
7530 @code{cons}. Find out what happens when you @code{cons} a list onto
7531 itself. Replace the first element of the list of four birds with a
7532 fish. Replace the rest of that list with a list of other fish.
7533
7534 @node Cutting & Storing Text
7535 @chapter Cutting and Storing Text
7536 @cindex Cutting and storing text
7537 @cindex Storing and cutting text
7538 @cindex Killing text
7539 @cindex Clipping text
7540 @cindex Erasing text
7541 @cindex Deleting text
7542
7543 Whenever you cut or clip text out of a buffer with a `kill' command in
7544 GNU Emacs, it is stored in a list and you can bring it back with a
7545 `yank' command.
7546
7547 (The use of the word `kill' in Emacs for processes which specifically
7548 @emph{do not} destroy the values of the entities is an unfortunate
7549 historical accident. A much more appropriate word would be `clip' since
7550 that is what the kill commands do; they clip text out of a buffer and
7551 put it into storage from which it can be brought back. I have often
7552 been tempted to replace globally all occurrences of `kill' in the Emacs
7553 sources with `clip' and all occurrences of `killed' with `clipped'.)
7554
7555 @menu
7556 * Storing Text:: Text is stored in a list.
7557 * zap-to-char:: Cutting out text up to a character.
7558 * kill-region:: Cutting text out of a region.
7559 * copy-region-as-kill:: A definition for copying text.
7560 * Digression into C:: Minor note on C programming language macros.
7561 * defvar:: How to give a variable an initial value.
7562 * cons & search-fwd Review::
7563 * search Exercises::
7564 @end menu
7565
7566 @ifnottex
7567 @node Storing Text
7568 @unnumberedsec Storing Text in a List
7569 @end ifnottex
7570
7571 When text is cut out of a buffer, it is stored on a list. Successive
7572 pieces of text are stored on the list successively, so the list might
7573 look like this:
7574
7575 @smallexample
7576 ("a piece of text" "previous piece")
7577 @end smallexample
7578
7579 @need 1200
7580 @noindent
7581 The function @code{cons} can be used to create a new list from a piece
7582 of text (an `atom', to use the jargon) and an existing list, like
7583 this:
7584
7585 @smallexample
7586 @group
7587 (cons "another piece"
7588 '("a piece of text" "previous piece"))
7589 @end group
7590 @end smallexample
7591
7592 @need 1200
7593 @noindent
7594 If you evaluate this expression, a list of three elements will appear in
7595 the echo area:
7596
7597 @smallexample
7598 ("another piece" "a piece of text" "previous piece")
7599 @end smallexample
7600
7601 With the @code{car} and @code{nthcdr} functions, you can retrieve
7602 whichever piece of text you want. For example, in the following code,
7603 @code{nthcdr 1 @dots{}} returns the list with the first item removed;
7604 and the @code{car} returns the first element of that remainder---the
7605 second element of the original list:
7606
7607 @smallexample
7608 @group
7609 (car (nthcdr 1 '("another piece"
7610 "a piece of text"
7611 "previous piece")))
7612 @result{} "a piece of text"
7613 @end group
7614 @end smallexample
7615
7616 The actual functions in Emacs are more complex than this, of course.
7617 The code for cutting and retrieving text has to be written so that
7618 Emacs can figure out which element in the list you want---the first,
7619 second, third, or whatever. In addition, when you get to the end of
7620 the list, Emacs should give you the first element of the list, rather
7621 than nothing at all.
7622
7623 The list that holds the pieces of text is called the @dfn{kill ring}.
7624 This chapter leads up to a description of the kill ring and how it is
7625 used by first tracing how the @code{zap-to-char} function works. This
7626 function uses (or `calls') a function that invokes a function that
7627 manipulates the kill ring. Thus, before reaching the mountains, we
7628 climb the foothills.
7629
7630 A subsequent chapter describes how text that is cut from the buffer is
7631 retrieved. @xref{Yanking, , Yanking Text Back}.
7632
7633 @node zap-to-char
7634 @section @code{zap-to-char}
7635 @findex zap-to-char
7636
7637 @c FIXME remove obsolete stuff
7638 The @code{zap-to-char} function changed little between GNU Emacs
7639 version 19 and GNU Emacs version 22. However, @code{zap-to-char}
7640 calls another function, @code{kill-region}, which enjoyed a major
7641 rewrite.
7642
7643 The @code{kill-region} function in Emacs 19 is complex, but does not
7644 use code that is important at this time. We will skip it.
7645
7646 The @code{kill-region} function in Emacs 22 is easier to read than the
7647 same function in Emacs 19 and introduces a very important concept,
7648 that of error handling. We will walk through the function.
7649
7650 But first, let us look at the interactive @code{zap-to-char} function.
7651
7652 @menu
7653 * Complete zap-to-char:: The complete implementation.
7654 * zap-to-char interactive:: A three part interactive expression.
7655 * zap-to-char body:: A short overview.
7656 * search-forward:: How to search for a string.
7657 * progn:: The @code{progn} special form.
7658 * Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
7659 @end menu
7660
7661 @ifnottex
7662 @node Complete zap-to-char
7663 @unnumberedsubsec The Complete @code{zap-to-char} Implementation
7664 @end ifnottex
7665
7666 The @code{zap-to-char} function removes the text in the region between
7667 the location of the cursor (i.e., of point) up to and including the
7668 next occurrence of a specified character. The text that
7669 @code{zap-to-char} removes is put in the kill ring; and it can be
7670 retrieved from the kill ring by typing @kbd{C-y} (@code{yank}). If
7671 the command is given an argument, it removes text through that number
7672 of occurrences. Thus, if the cursor were at the beginning of this
7673 sentence and the character were @samp{s}, @samp{Thus} would be
7674 removed. If the argument were two, @samp{Thus, if the curs} would be
7675 removed, up to and including the @samp{s} in @samp{cursor}.
7676
7677 If the specified character is not found, @code{zap-to-char} will say
7678 ``Search failed'', tell you the character you typed, and not remove
7679 any text.
7680
7681 In order to determine how much text to remove, @code{zap-to-char} uses
7682 a search function. Searches are used extensively in code that
7683 manipulates text, and we will focus attention on them as well as on the
7684 deletion command.
7685
7686 @ignore
7687 @c GNU Emacs version 19
7688 (defun zap-to-char (arg char) ; version 19 implementation
7689 "Kill up to and including ARG'th occurrence of CHAR.
7690 Goes backward if ARG is negative; error if CHAR not found."
7691 (interactive "*p\ncZap to char: ")
7692 (kill-region (point)
7693 (progn
7694 (search-forward
7695 (char-to-string char) nil nil arg)
7696 (point))))
7697 @end ignore
7698
7699 @need 1250
7700 Here is the complete text of the version 22 implementation of the function:
7701
7702 @c GNU Emacs 22
7703 @smallexample
7704 @group
7705 (defun zap-to-char (arg char)
7706 "Kill up to and including ARG'th occurrence of CHAR.
7707 Case is ignored if `case-fold-search' is non-nil in the current buffer.
7708 Goes backward if ARG is negative; error if CHAR not found."
7709 (interactive "p\ncZap to char: ")
7710 (if (char-table-p translation-table-for-input)
7711 (setq char (or (aref translation-table-for-input char) char)))
7712 (kill-region (point) (progn
7713 (search-forward (char-to-string char)
7714 nil nil arg)
7715 (point))))
7716 @end group
7717 @end smallexample
7718
7719 The documentation is thorough. You do need to know the jargon meaning
7720 of the word `kill'.
7721
7722 @node zap-to-char interactive
7723 @subsection The @code{interactive} Expression
7724
7725 @need 800
7726 The interactive expression in the @code{zap-to-char} command looks like
7727 this:
7728
7729 @smallexample
7730 (interactive "p\ncZap to char: ")
7731 @end smallexample
7732
7733 The part within quotation marks, @code{"p\ncZap to char:@: "}, specifies
7734 two different things. First, and most simply, is the @samp{p}.
7735 This part is separated from the next part by a newline, @samp{\n}.
7736 The @samp{p} means that the first argument to the function will be
7737 passed the value of a `processed prefix'. The prefix argument is
7738 passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number. If
7739 the function is called interactively without a prefix, 1 is passed to
7740 this argument.
7741
7742 The second part of @code{"p\ncZap to char:@: "} is
7743 @samp{cZap to char:@: }. In this part, the lower case @samp{c}
7744 indicates that @code{interactive} expects a prompt and that the
7745 argument will be a character. The prompt follows the @samp{c} and is
7746 the string @samp{Zap to char:@: } (with a space after the colon to
7747 make it look good).
7748
7749 What all this does is prepare the arguments to @code{zap-to-char} so they
7750 are of the right type, and give the user a prompt.
7751
7752 In a read-only buffer, the @code{zap-to-char} function copies the text
7753 to the kill ring, but does not remove it. The echo area displays a
7754 message saying that the buffer is read-only. Also, the terminal may
7755 beep or blink at you.
7756
7757 @node zap-to-char body
7758 @subsection The Body of @code{zap-to-char}
7759
7760 The body of the @code{zap-to-char} function contains the code that
7761 kills (that is, removes) the text in the region from the current
7762 position of the cursor up to and including the specified character.
7763
7764 The first part of the code looks like this:
7765
7766 @smallexample
7767 (if (char-table-p translation-table-for-input)
7768 (setq char (or (aref translation-table-for-input char) char)))
7769 (kill-region (point) (progn
7770 (search-forward (char-to-string char) nil nil arg)
7771 (point)))
7772 @end smallexample
7773
7774 @noindent
7775 @code{char-table-p} is an hitherto unseen function. It determines
7776 whether its argument is a character table. When it is, it sets the
7777 character passed to @code{zap-to-char} to one of them, if that
7778 character exists, or to the character itself. (This becomes important
7779 for certain characters in non-European languages. The @code{aref}
7780 function extracts an element from an array. It is an array-specific
7781 function that is not described in this document. @xref{Arrays, ,
7782 Arrays, elisp, The GNU Emacs Lisp Reference Manual}.)
7783
7784 @noindent
7785 @code{(point)} is the current position of the cursor.
7786
7787 The next part of the code is an expression using @code{progn}. The body
7788 of the @code{progn} consists of calls to @code{search-forward} and
7789 @code{point}.
7790
7791 It is easier to understand how @code{progn} works after learning about
7792 @code{search-forward}, so we will look at @code{search-forward} and
7793 then at @code{progn}.
7794
7795 @node search-forward
7796 @subsection The @code{search-forward} Function
7797 @findex search-forward
7798
7799 The @code{search-forward} function is used to locate the
7800 zapped-for-character in @code{zap-to-char}. If the search is
7801 successful, @code{search-forward} leaves point immediately after the
7802 last character in the target string. (In @code{zap-to-char}, the
7803 target string is just one character long. @code{zap-to-char} uses the
7804 function @code{char-to-string} to ensure that the computer treats that
7805 character as a string.) If the search is backwards,
7806 @code{search-forward} leaves point just before the first character in
7807 the target. Also, @code{search-forward} returns @code{t} for true.
7808 (Moving point is therefore a `side effect'.)
7809
7810 @need 1250
7811 In @code{zap-to-char}, the @code{search-forward} function looks like this:
7812
7813 @smallexample
7814 (search-forward (char-to-string char) nil nil arg)
7815 @end smallexample
7816
7817 The @code{search-forward} function takes four arguments:
7818
7819 @enumerate
7820 @item
7821 The first argument is the target, what is searched for. This must be a
7822 string, such as @samp{"z"}.
7823
7824 As it happens, the argument passed to @code{zap-to-char} is a single
7825 character. Because of the way computers are built, the Lisp
7826 interpreter may treat a single character as being different from a
7827 string of characters. Inside the computer, a single character has a
7828 different electronic format than a string of one character. (A single
7829 character can often be recorded in the computer using exactly one
7830 byte; but a string may be longer, and the computer needs to be ready
7831 for this.) Since the @code{search-forward} function searches for a
7832 string, the character that the @code{zap-to-char} function receives as
7833 its argument must be converted inside the computer from one format to
7834 the other; otherwise the @code{search-forward} function will fail.
7835 The @code{char-to-string} function is used to make this conversion.
7836
7837 @item
7838 The second argument bounds the search; it is specified as a position in
7839 the buffer. In this case, the search can go to the end of the buffer,
7840 so no bound is set and the second argument is @code{nil}.
7841
7842 @item
7843 The third argument tells the function what it should do if the search
7844 fails---it can signal an error (and print a message) or it can return
7845 @code{nil}. A @code{nil} as the third argument causes the function to
7846 signal an error when the search fails.
7847
7848 @item
7849 The fourth argument to @code{search-forward} is the repeat count---how
7850 many occurrences of the string to look for. This argument is optional
7851 and if the function is called without a repeat count, this argument is
7852 passed the value 1. If this argument is negative, the search goes
7853 backwards.
7854 @end enumerate
7855
7856 @need 800
7857 In template form, a @code{search-forward} expression looks like this:
7858
7859 @smallexample
7860 @group
7861 (search-forward "@var{target-string}"
7862 @var{limit-of-search}
7863 @var{what-to-do-if-search-fails}
7864 @var{repeat-count})
7865 @end group
7866 @end smallexample
7867
7868 We will look at @code{progn} next.
7869
7870 @node progn
7871 @subsection The @code{progn} Special Form
7872 @findex progn
7873
7874 @code{progn} is a special form that causes each of its arguments to be
7875 evaluated in sequence and then returns the value of the last one. The
7876 preceding expressions are evaluated only for the side effects they
7877 perform. The values produced by them are discarded.
7878
7879 @need 800
7880 The template for a @code{progn} expression is very simple:
7881
7882 @smallexample
7883 @group
7884 (progn
7885 @var{body}@dots{})
7886 @end group
7887 @end smallexample
7888
7889 In @code{zap-to-char}, the @code{progn} expression has to do two things:
7890 put point in exactly the right position; and return the location of
7891 point so that @code{kill-region} will know how far to kill to.
7892
7893 The first argument to the @code{progn} is @code{search-forward}. When
7894 @code{search-forward} finds the string, the function leaves point
7895 immediately after the last character in the target string. (In this
7896 case the target string is just one character long.) If the search is
7897 backwards, @code{search-forward} leaves point just before the first
7898 character in the target. The movement of point is a side effect.
7899
7900 The second and last argument to @code{progn} is the expression
7901 @code{(point)}. This expression returns the value of point, which in
7902 this case will be the location to which it has been moved by
7903 @code{search-forward}. (In the source, a line that tells the function
7904 to go to the previous character, if it is going forward, was commented
7905 out in 1999; I don't remember whether that feature or mis-feature was
7906 ever a part of the distributed source.) The value of @code{point} is
7907 returned by the @code{progn} expression and is passed to
7908 @code{kill-region} as @code{kill-region}'s second argument.
7909
7910 @node Summing up zap-to-char
7911 @subsection Summing up @code{zap-to-char}
7912
7913 Now that we have seen how @code{search-forward} and @code{progn} work,
7914 we can see how the @code{zap-to-char} function works as a whole.
7915
7916 The first argument to @code{kill-region} is the position of the cursor
7917 when the @code{zap-to-char} command is given---the value of point at
7918 that time. Within the @code{progn}, the search function then moves
7919 point to just after the zapped-to-character and @code{point} returns the
7920 value of this location. The @code{kill-region} function puts together
7921 these two values of point, the first one as the beginning of the region
7922 and the second one as the end of the region, and removes the region.
7923
7924 The @code{progn} special form is necessary because the
7925 @code{kill-region} command takes two arguments; and it would fail if
7926 @code{search-forward} and @code{point} expressions were written in
7927 sequence as two additional arguments. The @code{progn} expression is
7928 a single argument to @code{kill-region} and returns the one value that
7929 @code{kill-region} needs for its second argument.
7930
7931 @node kill-region
7932 @section @code{kill-region}
7933 @findex kill-region
7934
7935 The @code{zap-to-char} function uses the @code{kill-region} function.
7936 This function clips text from a region and copies that text to
7937 the kill ring, from which it may be retrieved.
7938
7939 @ignore
7940 GNU Emacs 22:
7941
7942 (defun kill-region (beg end &optional yank-handler)
7943 "Kill (\"cut\") text between point and mark.
7944 This deletes the text from the buffer and saves it in the kill ring.
7945 The command \\[yank] can retrieve it from there.
7946 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
7947
7948 If you want to append the killed region to the last killed text,
7949 use \\[append-next-kill] before \\[kill-region].
7950
7951 If the buffer is read-only, Emacs will beep and refrain from deleting
7952 the text, but put the text in the kill ring anyway. This means that
7953 you can use the killing commands to copy text from a read-only buffer.
7954
7955 This is the primitive for programs to kill text (as opposed to deleting it).
7956 Supply two arguments, character positions indicating the stretch of text
7957 to be killed.
7958 Any command that calls this function is a \"kill command\".
7959 If the previous command was also a kill command,
7960 the text killed this time appends to the text killed last time
7961 to make one entry in the kill ring.
7962
7963 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
7964 specifies the yank-handler text property to be set on the killed
7965 text. See `insert-for-yank'."
7966 ;; Pass point first, then mark, because the order matters
7967 ;; when calling kill-append.
7968 (interactive (list (point) (mark)))
7969 (unless (and beg end)
7970 (error "The mark is not set now, so there is no region"))
7971 (condition-case nil
7972 (let ((string (filter-buffer-substring beg end t)))
7973 (when string ;STRING is nil if BEG = END
7974 ;; Add that string to the kill ring, one way or another.
7975 (if (eq last-command 'kill-region)
7976 (kill-append string (< end beg) yank-handler)
7977 (kill-new string nil yank-handler)))
7978 (when (or string (eq last-command 'kill-region))
7979 (setq this-command 'kill-region))
7980 nil)
7981 ((buffer-read-only text-read-only)
7982 ;; The code above failed because the buffer, or some of the characters
7983 ;; in the region, are read-only.
7984 ;; We should beep, in case the user just isn't aware of this.
7985 ;; However, there's no harm in putting
7986 ;; the region's text in the kill ring, anyway.
7987 (copy-region-as-kill beg end)
7988 ;; Set this-command now, so it will be set even if we get an error.
7989 (setq this-command 'kill-region)
7990 ;; This should barf, if appropriate, and give us the correct error.
7991 (if kill-read-only-ok
7992 (progn (message "Read only text copied to kill ring") nil)
7993 ;; Signal an error if the buffer is read-only.
7994 (barf-if-buffer-read-only)
7995 ;; If the buffer isn't read-only, the text is.
7996 (signal 'text-read-only (list (current-buffer)))))))
7997 @end ignore
7998
7999 The Emacs 22 version of that function uses @code{condition-case} and
8000 @code{copy-region-as-kill}, both of which we will explain.
8001 @code{condition-case} is an important special form.
8002
8003 In essence, the @code{kill-region} function calls
8004 @code{condition-case}, which takes three arguments. In this function,
8005 the first argument does nothing. The second argument contains the
8006 code that does the work when all goes well. The third argument
8007 contains the code that is called in the event of an error.
8008
8009 @menu
8010 * Complete kill-region:: The function definition.
8011 * condition-case:: Dealing with a problem.
8012 * Lisp macro::
8013 @end menu
8014
8015 @ifnottex
8016 @node Complete kill-region
8017 @unnumberedsubsec The Complete @code{kill-region} Definition
8018 @end ifnottex
8019
8020 @need 1200
8021 We will go through the @code{condition-case} code in a moment. First,
8022 let us look at the definition of @code{kill-region}, with comments
8023 added:
8024
8025 @c GNU Emacs 22:
8026 @smallexample
8027 @group
8028 (defun kill-region (beg end)
8029 "Kill (\"cut\") text between point and mark.
8030 This deletes the text from the buffer and saves it in the kill ring.
8031 The command \\[yank] can retrieve it from there. @dots{} "
8032 @end group
8033
8034 @group
8035 ;; @bullet{} Since order matters, pass point first.
8036 (interactive (list (point) (mark)))
8037 ;; @bullet{} And tell us if we cannot cut the text.
8038 ;; `unless' is an `if' without a then-part.
8039 (unless (and beg end)
8040 (error "The mark is not set now, so there is no region"))
8041 @end group
8042
8043 @group
8044 ;; @bullet{} `condition-case' takes three arguments.
8045 ;; If the first argument is nil, as it is here,
8046 ;; information about the error signal is not
8047 ;; stored for use by another function.
8048 (condition-case nil
8049 @end group
8050
8051 @group
8052 ;; @bullet{} The second argument to `condition-case' tells the
8053 ;; Lisp interpreter what to do when all goes well.
8054 @end group
8055
8056 @group
8057 ;; It starts with a `let' function that extracts the string
8058 ;; and tests whether it exists. If so (that is what the
8059 ;; `when' checks), it calls an `if' function that determines
8060 ;; whether the previous command was another call to
8061 ;; `kill-region'; if it was, then the new text is appended to
8062 ;; the previous text; if not, then a different function,
8063 ;; `kill-new', is called.
8064 @end group
8065
8066 @group
8067 ;; The `kill-append' function concatenates the new string and
8068 ;; the old. The `kill-new' function inserts text into a new
8069 ;; item in the kill ring.
8070 @end group
8071
8072 @group
8073 ;; `when' is an `if' without an else-part. The second `when'
8074 ;; again checks whether the current string exists; in
8075 ;; addition, it checks whether the previous command was
8076 ;; another call to `kill-region'. If one or the other
8077 ;; condition is true, then it sets the current command to
8078 ;; be `kill-region'.
8079 @end group
8080 @group
8081 (let ((string (filter-buffer-substring beg end t)))
8082 (when string ;STRING is nil if BEG = END
8083 ;; Add that string to the kill ring, one way or another.
8084 (if (eq last-command 'kill-region)
8085 @end group
8086 @group
8087 ;; @minus{} `yank-handler' is an optional argument to
8088 ;; `kill-region' that tells the `kill-append' and
8089 ;; `kill-new' functions how deal with properties
8090 ;; added to the text, such as `bold' or `italics'.
8091 (kill-append string (< end beg) yank-handler)
8092 (kill-new string nil yank-handler)))
8093 (when (or string (eq last-command 'kill-region))
8094 (setq this-command 'kill-region))
8095 nil)
8096 @end group
8097
8098 @group
8099 ;; @bullet{} The third argument to `condition-case' tells the interpreter
8100 ;; what to do with an error.
8101 @end group
8102 @group
8103 ;; The third argument has a conditions part and a body part.
8104 ;; If the conditions are met (in this case,
8105 ;; if text or buffer are read-only)
8106 ;; then the body is executed.
8107 @end group
8108 @group
8109 ;; The first part of the third argument is the following:
8110 ((buffer-read-only text-read-only) ;; the if-part
8111 ;; @dots{} the then-part
8112 (copy-region-as-kill beg end)
8113 @end group
8114 @group
8115 ;; Next, also as part of the then-part, set this-command, so
8116 ;; it will be set in an error
8117 (setq this-command 'kill-region)
8118 ;; Finally, in the then-part, send a message if you may copy
8119 ;; the text to the kill ring without signaling an error, but
8120 ;; don't if you may not.
8121 @end group
8122 @group
8123 (if kill-read-only-ok
8124 (progn (message "Read only text copied to kill ring") nil)
8125 (barf-if-buffer-read-only)
8126 ;; If the buffer isn't read-only, the text is.
8127 (signal 'text-read-only (list (current-buffer)))))
8128 @end group
8129 @end smallexample
8130
8131 @ignore
8132 @c v 21
8133 @smallexample
8134 @group
8135 (defun kill-region (beg end)
8136 "Kill between point and mark.
8137 The text is deleted but saved in the kill ring."
8138 (interactive "r")
8139 @end group
8140
8141 @group
8142 ;; 1. `condition-case' takes three arguments.
8143 ;; If the first argument is nil, as it is here,
8144 ;; information about the error signal is not
8145 ;; stored for use by another function.
8146 (condition-case nil
8147 @end group
8148
8149 @group
8150 ;; 2. The second argument to `condition-case'
8151 ;; tells the Lisp interpreter what to do when all goes well.
8152 @end group
8153
8154 @group
8155 ;; The `delete-and-extract-region' function usually does the
8156 ;; work. If the beginning and ending of the region are both
8157 ;; the same, then the variable `string' will be empty, or nil
8158 (let ((string (delete-and-extract-region beg end)))
8159 @end group
8160
8161 @group
8162 ;; `when' is an `if' clause that cannot take an `else-part'.
8163 ;; Emacs normally sets the value of `last-command' to the
8164 ;; previous command.
8165 @end group
8166 @group
8167 ;; `kill-append' concatenates the new string and the old.
8168 ;; `kill-new' inserts text into a new item in the kill ring.
8169 (when string
8170 (if (eq last-command 'kill-region)
8171 ;; if true, prepend string
8172 (kill-append string (< end beg))
8173 (kill-new string)))
8174 (setq this-command 'kill-region))
8175 @end group
8176
8177 @group
8178 ;; 3. The third argument to `condition-case' tells the interpreter
8179 ;; what to do with an error.
8180 @end group
8181 @group
8182 ;; The third argument has a conditions part and a body part.
8183 ;; If the conditions are met (in this case,
8184 ;; if text or buffer are read-only)
8185 ;; then the body is executed.
8186 @end group
8187 @group
8188 ((buffer-read-only text-read-only) ;; this is the if-part
8189 ;; then...
8190 (copy-region-as-kill beg end)
8191 @end group
8192 @group
8193 (if kill-read-only-ok ;; usually this variable is nil
8194 (message "Read only text copied to kill ring")
8195 ;; or else, signal an error if the buffer is read-only;
8196 (barf-if-buffer-read-only)
8197 ;; and, in any case, signal that the text is read-only.
8198 (signal 'text-read-only (list (current-buffer)))))))
8199 @end group
8200 @end smallexample
8201 @end ignore
8202
8203 @node condition-case
8204 @subsection @code{condition-case}
8205 @findex condition-case
8206
8207 As we have seen earlier (@pxref{Making Errors, , Generate an Error
8208 Message}), when the Emacs Lisp interpreter has trouble evaluating an
8209 expression, it provides you with help; in the jargon, this is called
8210 ``signaling an error''. Usually, the computer stops the program and
8211 shows you a message.
8212
8213 However, some programs undertake complicated actions. They should not
8214 simply stop on an error. In the @code{kill-region} function, the most
8215 likely error is that you will try to kill text that is read-only and
8216 cannot be removed. So the @code{kill-region} function contains code
8217 to handle this circumstance. This code, which makes up the body of
8218 the @code{kill-region} function, is inside of a @code{condition-case}
8219 special form.
8220
8221 @need 800
8222 The template for @code{condition-case} looks like this:
8223
8224 @smallexample
8225 @group
8226 (condition-case
8227 @var{var}
8228 @var{bodyform}
8229 @var{error-handler}@dots{})
8230 @end group
8231 @end smallexample
8232
8233 The second argument, @var{bodyform}, is straightforward. The
8234 @code{condition-case} special form causes the Lisp interpreter to
8235 evaluate the code in @var{bodyform}. If no error occurs, the special
8236 form returns the code's value and produces the side-effects, if any.
8237
8238 In short, the @var{bodyform} part of a @code{condition-case}
8239 expression determines what should happen when everything works
8240 correctly.
8241
8242 However, if an error occurs, among its other actions, the function
8243 generating the error signal will define one or more error condition
8244 names.
8245
8246 An error handler is the third argument to @code{condition case}.
8247 An error handler has two parts, a @var{condition-name} and a
8248 @var{body}. If the @var{condition-name} part of an error handler
8249 matches a condition name generated by an error, then the @var{body}
8250 part of the error handler is run.
8251
8252 As you will expect, the @var{condition-name} part of an error handler
8253 may be either a single condition name or a list of condition names.
8254
8255 Also, a complete @code{condition-case} expression may contain more
8256 than one error handler. When an error occurs, the first applicable
8257 handler is run.
8258
8259 Lastly, the first argument to the @code{condition-case} expression,
8260 the @var{var} argument, is sometimes bound to a variable that
8261 contains information about the error. However, if that argument is
8262 nil, as is the case in @code{kill-region}, that information is
8263 discarded.
8264
8265 @need 1200
8266 In brief, in the @code{kill-region} function, the code
8267 @code{condition-case} works like this:
8268
8269 @smallexample
8270 @group
8271 @var{If no errors}, @var{run only this code}
8272 @var{but}, @var{if errors}, @var{run this other code}.
8273 @end group
8274 @end smallexample
8275
8276 @ignore
8277 2006 Oct 24
8278 In Emacs 22,
8279 copy-region-as-kill is short, 12 lines, and uses
8280 filter-buffer-substring, which is longer, 39 lines
8281 and has delete-and-extract-region in it.
8282 delete-and-extract-region is written in C.
8283
8284 see Initializing a Variable with @code{defvar}
8285 this is line 8054
8286 Initializing a Variable with @code{defvar} includes line 8350
8287 @end ignore
8288
8289 @node Lisp macro
8290 @subsection Lisp macro
8291 @cindex Macro, lisp
8292 @cindex Lisp macro
8293
8294 The part of the @code{condition-case} expression that is evaluated in
8295 the expectation that all goes well has a @code{when}. The code uses
8296 @code{when} to determine whether the @code{string} variable points to
8297 text that exists.
8298
8299 A @code{when} expression is simply a programmers' convenience. It is
8300 an @code{if} without the possibility of an else clause. In your mind,
8301 you can replace @code{when} with @code{if} and understand what goes
8302 on. That is what the Lisp interpreter does.
8303
8304 Technically speaking, @code{when} is a Lisp macro. A Lisp @dfn{macro}
8305 enables you to define new control constructs and other language
8306 features. It tells the interpreter how to compute another Lisp
8307 expression which will in turn compute the value. In this case, the
8308 `other expression' is an @code{if} expression.
8309
8310 The @code{kill-region} function definition also has an @code{unless}
8311 macro; it is the converse of @code{when}. The @code{unless} macro is
8312 an @code{if} without a then clause
8313
8314 For more about Lisp macros, see @ref{Macros, , Macros, elisp, The GNU
8315 Emacs Lisp Reference Manual}. The C programming language also
8316 provides macros. These are different, but also useful.
8317
8318 @ignore
8319 We will briefly look at C macros in
8320 @ref{Digression into C}.
8321 @end ignore
8322
8323 @need 1200
8324 Regarding the @code{when} macro, in the @code{condition-case}
8325 expression, when the string has content, then another conditional
8326 expression is executed. This is an @code{if} with both a then-part
8327 and an else-part.
8328
8329 @smallexample
8330 @group
8331 (if (eq last-command 'kill-region)
8332 (kill-append string (< end beg) yank-handler)
8333 (kill-new string nil yank-handler))
8334 @end group
8335 @end smallexample
8336
8337 The then-part is evaluated if the previous command was another call to
8338 @code{kill-region}; if not, the else-part is evaluated.
8339
8340 @code{yank-handler} is an optional argument to @code{kill-region} that
8341 tells the @code{kill-append} and @code{kill-new} functions how deal
8342 with properties added to the text, such as `bold' or `italics'.
8343
8344 @code{last-command} is a variable that comes with Emacs that we have
8345 not seen before. Normally, whenever a function is executed, Emacs
8346 sets the value of @code{last-command} to the previous command.
8347
8348 @need 1200
8349 In this segment of the definition, the @code{if} expression checks
8350 whether the previous command was @code{kill-region}. If it was,
8351
8352 @smallexample
8353 (kill-append string (< end beg) yank-handler)
8354 @end smallexample
8355
8356 @noindent
8357 concatenates a copy of the newly clipped text to the just previously
8358 clipped text in the kill ring.
8359
8360 @node copy-region-as-kill
8361 @section @code{copy-region-as-kill}
8362 @findex copy-region-as-kill
8363 @findex nthcdr
8364
8365 The @code{copy-region-as-kill} function copies a region of text from a
8366 buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8367 in the @code{kill-ring}.
8368
8369 If you call @code{copy-region-as-kill} immediately after a
8370 @code{kill-region} command, Emacs appends the newly copied text to the
8371 previously copied text. This means that if you yank back the text, you
8372 get it all, from both this and the previous operation. On the other
8373 hand, if some other command precedes the @code{copy-region-as-kill},
8374 the function copies the text into a separate entry in the kill ring.
8375
8376 @menu
8377 * Complete copy-region-as-kill:: The complete function definition.
8378 * copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
8379 @end menu
8380
8381 @ifnottex
8382 @node Complete copy-region-as-kill
8383 @unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8384 @end ifnottex
8385
8386 @need 1200
8387 Here is the complete text of the version 22 @code{copy-region-as-kill}
8388 function:
8389
8390 @smallexample
8391 @group
8392 (defun copy-region-as-kill (beg end)
8393 "Save the region as if killed, but don't kill it.
8394 In Transient Mark mode, deactivate the mark.
8395 If `interprogram-cut-function' is non-nil, also save the text for a window
8396 system cut and paste."
8397 (interactive "r")
8398 @end group
8399 @group
8400 (if (eq last-command 'kill-region)
8401 (kill-append (filter-buffer-substring beg end) (< end beg))
8402 (kill-new (filter-buffer-substring beg end)))
8403 @end group
8404 @group
8405 (if transient-mark-mode
8406 (setq deactivate-mark t))
8407 nil)
8408 @end group
8409 @end smallexample
8410
8411 @need 800
8412 As usual, this function can be divided into its component parts:
8413
8414 @smallexample
8415 @group
8416 (defun copy-region-as-kill (@var{argument-list})
8417 "@var{documentation}@dots{}"
8418 (interactive "r")
8419 @var{body}@dots{})
8420 @end group
8421 @end smallexample
8422
8423 The arguments are @code{beg} and @code{end} and the function is
8424 interactive with @code{"r"}, so the two arguments must refer to the
8425 beginning and end of the region. If you have been reading though this
8426 document from the beginning, understanding these parts of a function is
8427 almost becoming routine.
8428
8429 The documentation is somewhat confusing unless you remember that the
8430 word `kill' has a meaning different from usual. The `Transient Mark'
8431 and @code{interprogram-cut-function} comments explain certain
8432 side-effects.
8433
8434 After you once set a mark, a buffer always contains a region. If you
8435 wish, you can use Transient Mark mode to highlight the region
8436 temporarily. (No one wants to highlight the region all the time, so
8437 Transient Mark mode highlights it only at appropriate times. Many
8438 people turn off Transient Mark mode, so the region is never
8439 highlighted.)
8440
8441 Also, a windowing system allows you to copy, cut, and paste among
8442 different programs. In the X windowing system, for example, the
8443 @code{interprogram-cut-function} function is @code{x-select-text},
8444 which works with the windowing system's equivalent of the Emacs kill
8445 ring.
8446
8447 The body of the @code{copy-region-as-kill} function starts with an
8448 @code{if} clause. What this clause does is distinguish between two
8449 different situations: whether or not this command is executed
8450 immediately after a previous @code{kill-region} command. In the first
8451 case, the new region is appended to the previously copied text.
8452 Otherwise, it is inserted into the beginning of the kill ring as a
8453 separate piece of text from the previous piece.
8454
8455 The last two lines of the function prevent the region from lighting up
8456 if Transient Mark mode is turned on.
8457
8458 The body of @code{copy-region-as-kill} merits discussion in detail.
8459
8460 @node copy-region-as-kill body
8461 @subsection The Body of @code{copy-region-as-kill}
8462
8463 The @code{copy-region-as-kill} function works in much the same way as
8464 the @code{kill-region} function. Both are written so that two or more
8465 kills in a row combine their text into a single entry. If you yank
8466 back the text from the kill ring, you get it all in one piece.
8467 Moreover, kills that kill forward from the current position of the
8468 cursor are added to the end of the previously copied text and commands
8469 that copy text backwards add it to the beginning of the previously
8470 copied text. This way, the words in the text stay in the proper
8471 order.
8472
8473 Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8474 use of the @code{last-command} variable that keeps track of the
8475 previous Emacs command.
8476
8477 @menu
8478 * last-command & this-command::
8479 * kill-append function::
8480 * kill-new function::
8481 @end menu
8482
8483 @ifnottex
8484 @node last-command & this-command
8485 @unnumberedsubsubsec @code{last-command} and @code{this-command}
8486 @end ifnottex
8487
8488 Normally, whenever a function is executed, Emacs sets the value of
8489 @code{this-command} to the function being executed (which in this case
8490 would be @code{copy-region-as-kill}). At the same time, Emacs sets
8491 the value of @code{last-command} to the previous value of
8492 @code{this-command}.
8493
8494 In the first part of the body of the @code{copy-region-as-kill}
8495 function, an @code{if} expression determines whether the value of
8496 @code{last-command} is @code{kill-region}. If so, the then-part of
8497 the @code{if} expression is evaluated; it uses the @code{kill-append}
8498 function to concatenate the text copied at this call to the function
8499 with the text already in the first element (the @sc{car}) of the kill
8500 ring. On the other hand, if the value of @code{last-command} is not
8501 @code{kill-region}, then the @code{copy-region-as-kill} function
8502 attaches a new element to the kill ring using the @code{kill-new}
8503 function.
8504
8505 @need 1250
8506 The @code{if} expression reads as follows; it uses @code{eq}:
8507
8508 @smallexample
8509 @group
8510 (if (eq last-command 'kill-region)
8511 ;; @r{then-part}
8512 (kill-append (filter-buffer-substring beg end) (< end beg))
8513 ;; @r{else-part}
8514 (kill-new (filter-buffer-substring beg end)))
8515 @end group
8516 @end smallexample
8517
8518 @findex filter-buffer-substring
8519 (The @code{filter-buffer-substring} function returns a filtered
8520 substring of the buffer, if any. Optionally---the arguments are not
8521 here, so neither is done---the function may delete the initial text or
8522 return the text without its properties; this function is a replacement
8523 for the older @code{buffer-substring} function, which came before text
8524 properties were implemented.)
8525
8526 @findex eq @r{(example of use)}
8527 @noindent
8528 The @code{eq} function tests whether its first argument is the same Lisp
8529 object as its second argument. The @code{eq} function is similar to the
8530 @code{equal} function in that it is used to test for equality, but
8531 differs in that it determines whether two representations are actually
8532 the same object inside the computer, but with different names.
8533 @code{equal} determines whether the structure and contents of two
8534 expressions are the same.
8535
8536 If the previous command was @code{kill-region}, then the Emacs Lisp
8537 interpreter calls the @code{kill-append} function
8538
8539 @node kill-append function
8540 @unnumberedsubsubsec The @code{kill-append} function
8541 @findex kill-append
8542
8543 @need 800
8544 The @code{kill-append} function looks like this:
8545
8546 @c in GNU Emacs 22
8547 @smallexample
8548 @group
8549 (defun kill-append (string before-p &optional yank-handler)
8550 "Append STRING to the end of the latest kill in the kill ring.
8551 If BEFORE-P is non-nil, prepend STRING to the kill.
8552 @dots{} "
8553 (let* ((cur (car kill-ring)))
8554 (kill-new (if before-p (concat string cur) (concat cur string))
8555 (or (= (length cur) 0)
8556 (equal yank-handler
8557 (get-text-property 0 'yank-handler cur)))
8558 yank-handler)))
8559 @end group
8560 @end smallexample
8561
8562 @ignore
8563 was:
8564 (defun kill-append (string before-p)
8565 "Append STRING to the end of the latest kill in the kill ring.
8566 If BEFORE-P is non-nil, prepend STRING to the kill.
8567 If `interprogram-cut-function' is set, pass the resulting kill to
8568 it."
8569 (kill-new (if before-p
8570 (concat string (car kill-ring))
8571 (concat (car kill-ring) string))
8572 t))
8573 @end ignore
8574
8575 @noindent
8576 The @code{kill-append} function is fairly straightforward. It uses
8577 the @code{kill-new} function, which we will discuss in more detail in
8578 a moment.
8579
8580 (Also, the function provides an optional argument called
8581 @code{yank-handler}; when invoked, this argument tells the function
8582 how to deal with properties added to the text, such as `bold' or
8583 `italics'.)
8584
8585 @c !!! bug in GNU Emacs 22 version of kill-append ?
8586 It has a @code{let*} function to set the value of the first element of
8587 the kill ring to @code{cur}. (I do not know why the function does not
8588 use @code{let} instead; only one value is set in the expression.
8589 Perhaps this is a bug that produces no problems?)
8590
8591 Consider the conditional that is one of the two arguments to
8592 @code{kill-new}. It uses @code{concat} to concatenate the new text to
8593 the @sc{car} of the kill ring. Whether it prepends or appends the
8594 text depends on the results of an @code{if} expression:
8595
8596 @smallexample
8597 @group
8598 (if before-p ; @r{if-part}
8599 (concat string cur) ; @r{then-part}
8600 (concat cur string)) ; @r{else-part}
8601 @end group
8602 @end smallexample
8603
8604 @noindent
8605 If the region being killed is before the region that was killed in the
8606 last command, then it should be prepended before the material that was
8607 saved in the previous kill; and conversely, if the killed text follows
8608 what was just killed, it should be appended after the previous text.
8609 The @code{if} expression depends on the predicate @code{before-p} to
8610 decide whether the newly saved text should be put before or after the
8611 previously saved text.
8612
8613 The symbol @code{before-p} is the name of one of the arguments to
8614 @code{kill-append}. When the @code{kill-append} function is
8615 evaluated, it is bound to the value returned by evaluating the actual
8616 argument. In this case, this is the expression @code{(< end beg)}.
8617 This expression does not directly determine whether the killed text in
8618 this command is located before or after the kill text of the last
8619 command; what it does is determine whether the value of the variable
8620 @code{end} is less than the value of the variable @code{beg}. If it
8621 is, it means that the user is most likely heading towards the
8622 beginning of the buffer. Also, the result of evaluating the predicate
8623 expression, @code{(< end beg)}, will be true and the text will be
8624 prepended before the previous text. On the other hand, if the value of
8625 the variable @code{end} is greater than the value of the variable
8626 @code{beg}, the text will be appended after the previous text.
8627
8628 @need 800
8629 When the newly saved text will be prepended, then the string with the new
8630 text will be concatenated before the old text:
8631
8632 @smallexample
8633 (concat string cur)
8634 @end smallexample
8635
8636 @need 1200
8637 @noindent
8638 But if the text will be appended, it will be concatenated
8639 after the old text:
8640
8641 @smallexample
8642 (concat cur string))
8643 @end smallexample
8644
8645 To understand how this works, we first need to review the
8646 @code{concat} function. The @code{concat} function links together or
8647 unites two strings of text. The result is a string. For example:
8648
8649 @smallexample
8650 @group
8651 (concat "abc" "def")
8652 @result{} "abcdef"
8653 @end group
8654
8655 @group
8656 (concat "new "
8657 (car '("first element" "second element")))
8658 @result{} "new first element"
8659
8660 (concat (car
8661 '("first element" "second element")) " modified")
8662 @result{} "first element modified"
8663 @end group
8664 @end smallexample
8665
8666 We can now make sense of @code{kill-append}: it modifies the contents
8667 of the kill ring. The kill ring is a list, each element of which is
8668 saved text. The @code{kill-append} function uses the @code{kill-new}
8669 function which in turn uses the @code{setcar} function.
8670
8671 @node kill-new function
8672 @unnumberedsubsubsec The @code{kill-new} function
8673 @findex kill-new
8674
8675 @c in GNU Emacs 22, additional documentation to kill-new:
8676 @ignore
8677 Optional third arguments YANK-HANDLER controls how the STRING is later
8678 inserted into a buffer; see `insert-for-yank' for details.
8679 When a yank handler is specified, STRING must be non-empty (the yank
8680 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
8681
8682 When the yank handler has a non-nil PARAM element, the original STRING
8683 argument is not used by `insert-for-yank'. However, since Lisp code
8684 may access and use elements from the kill ring directly, the STRING
8685 argument should still be a \"useful\" string for such uses."
8686 @end ignore
8687 @need 1200
8688 The @code{kill-new} function looks like this:
8689
8690 @smallexample
8691 @group
8692 (defun kill-new (string &optional replace yank-handler)
8693 "Make STRING the latest kill in the kill ring.
8694 Set `kill-ring-yank-pointer' to point to it.
8695
8696 If `interprogram-cut-function' is non-nil, apply it to STRING.
8697 Optional second argument REPLACE non-nil means that STRING will replace
8698 the front of the kill ring, rather than being added to the list.
8699 @dots{}"
8700 @end group
8701 @group
8702 (if (> (length string) 0)
8703 (if yank-handler
8704 (put-text-property 0 (length string)
8705 'yank-handler yank-handler string))
8706 (if yank-handler
8707 (signal 'args-out-of-range
8708 (list string "yank-handler specified for empty string"))))
8709 @end group
8710 @group
8711 (if (fboundp 'menu-bar-update-yank-menu)
8712 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8713 @end group
8714 @group
8715 (if (and replace kill-ring)
8716 (setcar kill-ring string)
8717 (push string kill-ring)
8718 (if (> (length kill-ring) kill-ring-max)
8719 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8720 @end group
8721 @group
8722 (setq kill-ring-yank-pointer kill-ring)
8723 (if interprogram-cut-function
8724 (funcall interprogram-cut-function string (not replace))))
8725 @end group
8726 @end smallexample
8727 @ignore
8728 was:
8729 (defun kill-new (string &optional replace)
8730 "Make STRING the latest kill in the kill ring.
8731 Set the kill-ring-yank pointer to point to it.
8732 If `interprogram-cut-function' is non-nil, apply it to STRING.
8733 Optional second argument REPLACE non-nil means that STRING will replace
8734 the front of the kill ring, rather than being added to the list."
8735 (and (fboundp 'menu-bar-update-yank-menu)
8736 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8737 (if (and replace kill-ring)
8738 (setcar kill-ring string)
8739 (setq kill-ring (cons string kill-ring))
8740 (if (> (length kill-ring) kill-ring-max)
8741 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8742 (setq kill-ring-yank-pointer kill-ring)
8743 (if interprogram-cut-function
8744 (funcall interprogram-cut-function string (not replace))))
8745 @end ignore
8746
8747 (Notice that the function is not interactive.)
8748
8749 As usual, we can look at this function in parts.
8750
8751 The function definition has an optional @code{yank-handler} argument,
8752 which when invoked tells the function how to deal with properties
8753 added to the text, such as `bold' or `italics'. We will skip that.
8754
8755 @need 1200
8756 The first line of the documentation makes sense:
8757
8758 @smallexample
8759 Make STRING the latest kill in the kill ring.
8760 @end smallexample
8761
8762 @noindent
8763 Let's skip over the rest of the documentation for the moment.
8764
8765 @noindent
8766 Also, let's skip over the initial @code{if} expression and those lines
8767 of code involving @code{menu-bar-update-yank-menu}. We will explain
8768 them below.
8769
8770 @need 1200
8771 The critical lines are these:
8772
8773 @smallexample
8774 @group
8775 (if (and replace kill-ring)
8776 ;; @r{then}
8777 (setcar kill-ring string)
8778 @end group
8779 @group
8780 ;; @r{else}
8781 (push string kill-ring)
8782 @end group
8783 @group
8784 (setq kill-ring (cons string kill-ring))
8785 (if (> (length kill-ring) kill-ring-max)
8786 ;; @r{avoid overly long kill ring}
8787 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8788 @end group
8789 @group
8790 (setq kill-ring-yank-pointer kill-ring)
8791 (if interprogram-cut-function
8792 (funcall interprogram-cut-function string (not replace))))
8793 @end group
8794 @end smallexample
8795
8796 The conditional test is @w{@code{(and replace kill-ring)}}.
8797 This will be true when two conditions are met: the kill ring has
8798 something in it, and the @code{replace} variable is true.
8799
8800 @need 1250
8801 When the @code{kill-append} function sets @code{replace} to be true
8802 and when the kill ring has at least one item in it, the @code{setcar}
8803 expression is executed:
8804
8805 @smallexample
8806 (setcar kill-ring string)
8807 @end smallexample
8808
8809 The @code{setcar} function actually changes the first element of the
8810 @code{kill-ring} list to the value of @code{string}. It replaces the
8811 first element.
8812
8813 @need 1250
8814 On the other hand, if the kill ring is empty, or replace is false, the
8815 else-part of the condition is executed:
8816
8817 @smallexample
8818 (push string kill-ring)
8819 @end smallexample
8820
8821 @noindent
8822 @need 1250
8823 @code{push} puts its first argument onto the second. It is similar to
8824 the older
8825
8826 @smallexample
8827 (setq kill-ring (cons string kill-ring))
8828 @end smallexample
8829
8830 @noindent
8831 @need 1250
8832 or the newer
8833
8834 @smallexample
8835 (add-to-list kill-ring string)
8836 @end smallexample
8837
8838 @noindent
8839 When it is false, the expression first constructs a new version of the
8840 kill ring by prepending @code{string} to the existing kill ring as a
8841 new element (that is what the @code{push} does). Then it executes a
8842 second @code{if} clause. This second @code{if} clause keeps the kill
8843 ring from growing too long.
8844
8845 Let's look at these two expressions in order.
8846
8847 The @code{push} line of the else-part sets the new value of the kill
8848 ring to what results from adding the string being killed to the old
8849 kill ring.
8850
8851 We can see how this works with an example.
8852
8853 @need 800
8854 First,
8855
8856 @smallexample
8857 (setq example-list '("here is a clause" "another clause"))
8858 @end smallexample
8859
8860 @need 1200
8861 @noindent
8862 After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8863 @code{example-list} and see what it returns:
8864
8865 @smallexample
8866 @group
8867 example-list
8868 @result{} ("here is a clause" "another clause")
8869 @end group
8870 @end smallexample
8871
8872 @need 1200
8873 @noindent
8874 Now, we can add a new element on to this list by evaluating the
8875 following expression:
8876 @findex push, @r{example}
8877
8878 @smallexample
8879 (push "a third clause" example-list)
8880 @end smallexample
8881
8882 @need 800
8883 @noindent
8884 When we evaluate @code{example-list}, we find its value is:
8885
8886 @smallexample
8887 @group
8888 example-list
8889 @result{} ("a third clause" "here is a clause" "another clause")
8890 @end group
8891 @end smallexample
8892
8893 @noindent
8894 Thus, the third clause is added to the list by @code{push}.
8895
8896 @need 1200
8897 Now for the second part of the @code{if} clause. This expression
8898 keeps the kill ring from growing too long. It looks like this:
8899
8900 @smallexample
8901 @group
8902 (if (> (length kill-ring) kill-ring-max)
8903 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8904 @end group
8905 @end smallexample
8906
8907 The code checks whether the length of the kill ring is greater than
8908 the maximum permitted length. This is the value of
8909 @code{kill-ring-max} (which is 60, by default). If the length of the
8910 kill ring is too long, then this code sets the last element of the
8911 kill ring to @code{nil}. It does this by using two functions,
8912 @code{nthcdr} and @code{setcdr}.
8913
8914 We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8915 It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8916 @sc{car} of a list. In this case, however, @code{setcdr} will not be
8917 setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8918 function is used to cause it to set the @sc{cdr} of the next to last
8919 element of the kill ring---this means that since the @sc{cdr} of the
8920 next to last element is the last element of the kill ring, it will set
8921 the last element of the kill ring.
8922
8923 @findex nthcdr, @r{example}
8924 The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8925 list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8926 @dots{} It does this @var{N} times and returns the results.
8927 (@xref{nthcdr, , @code{nthcdr}}.)
8928
8929 @findex setcdr, @r{example}
8930 Thus, if we had a four element list that was supposed to be three
8931 elements long, we could set the @sc{cdr} of the next to last element
8932 to @code{nil}, and thereby shorten the list. (If you set the last
8933 element to some other value than @code{nil}, which you could do, then
8934 you would not have shortened the list. @xref{setcdr, ,
8935 @code{setcdr}}.)
8936
8937 You can see shortening by evaluating the following three expressions
8938 in turn. First set the value of @code{trees} to @code{(maple oak pine
8939 birch)}, then set the @sc{cdr} of its second @sc{cdr} to @code{nil}
8940 and then find the value of @code{trees}:
8941
8942 @smallexample
8943 @group
8944 (setq trees '(maple oak pine birch))
8945 @result{} (maple oak pine birch)
8946 @end group
8947
8948 @group
8949 (setcdr (nthcdr 2 trees) nil)
8950 @result{} nil
8951
8952 trees
8953 @result{} (maple oak pine)
8954 @end group
8955 @end smallexample
8956
8957 @noindent
8958 (The value returned by the @code{setcdr} expression is @code{nil} since
8959 that is what the @sc{cdr} is set to.)
8960
8961 To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8962 @sc{cdr} a number of times that is one less than the maximum permitted
8963 size of the kill ring and @code{setcdr} sets the @sc{cdr} of that
8964 element (which will be the rest of the elements in the kill ring) to
8965 @code{nil}. This prevents the kill ring from growing too long.
8966
8967 @need 800
8968 The next to last expression in the @code{kill-new} function is
8969
8970 @smallexample
8971 (setq kill-ring-yank-pointer kill-ring)
8972 @end smallexample
8973
8974 The @code{kill-ring-yank-pointer} is a global variable that is set to be
8975 the @code{kill-ring}.
8976
8977 Even though the @code{kill-ring-yank-pointer} is called a
8978 @samp{pointer}, it is a variable just like the kill ring. However, the
8979 name has been chosen to help humans understand how the variable is used.
8980
8981 @need 1200
8982 Now, to return to an early expression in the body of the function:
8983
8984 @smallexample
8985 @group
8986 (if (fboundp 'menu-bar-update-yank-menu)
8987 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8988 @end group
8989 @end smallexample
8990
8991 @noindent
8992 It starts with an @code{if} expression
8993
8994 In this case, the expression tests first to see whether
8995 @code{menu-bar-update-yank-menu} exists as a function, and if so,
8996 calls it. The @code{fboundp} function returns true if the symbol it
8997 is testing has a function definition that `is not void'. If the
8998 symbol's function definition were void, we would receive an error
8999 message, as we did when we created errors intentionally (@pxref{Making
9000 Errors, , Generate an Error Message}).
9001
9002 @noindent
9003 The then-part contains an expression whose first element is the
9004 function @code{and}.
9005
9006 @findex and
9007 The @code{and} special form evaluates each of its arguments until one
9008 of the arguments returns a value of @code{nil}, in which case the
9009 @code{and} expression returns @code{nil}; however, if none of the
9010 arguments returns a value of @code{nil}, the value resulting from
9011 evaluating the last argument is returned. (Since such a value is not
9012 @code{nil}, it is considered true in Emacs Lisp.) In other words, an
9013 @code{and} expression returns a true value only if all its arguments
9014 are true. (@xref{Second Buffer Related Review}.)
9015
9016 The expression determines whether the second argument to
9017 @code{menu-bar-update-yank-menu} is true or not.
9018 @ignore
9019 ;; If we're supposed to be extending an existing string, and that
9020 ;; string really is at the front of the menu, then update it in place.
9021 @end ignore
9022
9023 @code{menu-bar-update-yank-menu} is one of the functions that make it
9024 possible to use the `Select and Paste' menu in the Edit item of a menu
9025 bar; using a mouse, you can look at the various pieces of text you
9026 have saved and select one piece to paste.
9027
9028 The last expression in the @code{kill-new} function adds the newly
9029 copied string to whatever facility exists for copying and pasting
9030 among different programs running in a windowing system. In the X
9031 Windowing system, for example, the @code{x-select-text} function takes
9032 the string and stores it in memory operated by X. You can paste the
9033 string in another program, such as an Xterm.
9034
9035 @need 1200
9036 The expression looks like this:
9037
9038 @smallexample
9039 @group
9040 (if interprogram-cut-function
9041 (funcall interprogram-cut-function string (not replace))))
9042 @end group
9043 @end smallexample
9044
9045 If an @code{interprogram-cut-function} exists, then Emacs executes
9046 @code{funcall}, which in turn calls its first argument as a function
9047 and passes the remaining arguments to it. (Incidentally, as far as I
9048 can see, this @code{if} expression could be replaced by an @code{and}
9049 expression similar to the one in the first part of the function.)
9050
9051 We are not going to discuss windowing systems and other programs
9052 further, but merely note that this is a mechanism that enables GNU
9053 Emacs to work easily and well with other programs.
9054
9055 This code for placing text in the kill ring, either concatenated with
9056 an existing element or as a new element, leads us to the code for
9057 bringing back text that has been cut out of the buffer---the yank
9058 commands. However, before discussing the yank commands, it is better
9059 to learn how lists are implemented in a computer. This will make
9060 clear such mysteries as the use of the term `pointer'. But before
9061 that, we will digress into C.
9062
9063 @ignore
9064 @c is this true in Emacs 22? Does not seems to be
9065
9066 (If the @w{@code{(< end beg))}}
9067 expression is true, @code{kill-append} prepends the string to the just
9068 previously clipped text. For a detailed discussion, see
9069 @ref{kill-append function, , The @code{kill-append} function}.)
9070
9071 If you then yank back the text, i.e., `paste' it, you get both
9072 pieces of text at once. That way, if you delete two words in a row,
9073 and then yank them back, you get both words, in their proper order,
9074 with one yank. (The @w{@code{(< end beg))}} expression makes sure the
9075 order is correct.)
9076
9077 On the other hand, if the previous command is not @code{kill-region},
9078 then the @code{kill-new} function is called, which adds the text to
9079 the kill ring as the latest item, and sets the
9080 @code{kill-ring-yank-pointer} variable to point to it.
9081 @end ignore
9082 @ignore
9083
9084 @c Evidently, changed for Emacs 22. The zap-to-char command does not
9085 @c use the delete-and-extract-region function
9086
9087 2006 Oct 26, the Digression into C is now OK but should come after
9088 copy-region-as-kill and filter-buffer-substring
9089
9090 2006 Oct 24
9091 In Emacs 22,
9092 copy-region-as-kill is short, 12 lines, and uses
9093 filter-buffer-substring, which is longer, 39 lines
9094 and has delete-and-extract-region in it.
9095 delete-and-extract-region is written in C.
9096
9097 see Initializing a Variable with @code{defvar}
9098 @end ignore
9099
9100 @node Digression into C
9101 @section Digression into C
9102 @findex delete-and-extract-region
9103 @cindex C, a digression into
9104 @cindex Digression into C
9105
9106 The @code{copy-region-as-kill} function (@pxref{copy-region-as-kill, ,
9107 @code{copy-region-as-kill}}) uses the @code{filter-buffer-substring}
9108 function, which in turn uses the @code{delete-and-extract-region}
9109 function. It removes the contents of a region and you cannot get them
9110 back.
9111
9112 Unlike the other code discussed here, the
9113 @code{delete-and-extract-region} function is not written in Emacs
9114 Lisp; it is written in C and is one of the primitives of the GNU Emacs
9115 system. Since it is very simple, I will digress briefly from Lisp and
9116 describe it here.
9117
9118 @c GNU Emacs 22 in /usr/local/src/emacs/src/editfns.c
9119 @c the DEFUN for buffer-substring-no-properties
9120
9121 @need 1500
9122 Like many of the other Emacs primitives,
9123 @code{delete-and-extract-region} is written as an instance of a C
9124 macro, a macro being a template for code. The complete macro looks
9125 like this:
9126
9127 @smallexample
9128 @group
9129 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
9130 Sbuffer_substring_no_properties, 2, 2, 0,
9131 doc: /* Return the characters of part of the buffer,
9132 without the text properties.
9133 The two arguments START and END are character positions;
9134 they can be in either order. */)
9135 (start, end)
9136 Lisp_Object start, end;
9137 @{
9138 register int b, e;
9139
9140 validate_region (&start, &end);
9141 b = XINT (start);
9142 e = XINT (end);
9143
9144 return make_buffer_string (b, e, 0);
9145 @}
9146 @end group
9147 @end smallexample
9148
9149 Without going into the details of the macro writing process, let me
9150 point out that this macro starts with the word @code{DEFUN}. The word
9151 @code{DEFUN} was chosen since the code serves the same purpose as
9152 @code{defun} does in Lisp. (The @code{DEFUN} C macro is defined in
9153 @file{emacs/src/lisp.h}.)
9154
9155 The word @code{DEFUN} is followed by seven parts inside of
9156 parentheses:
9157
9158 @itemize @bullet
9159 @item
9160 The first part is the name given to the function in Lisp,
9161 @code{delete-and-extract-region}.
9162
9163 @item
9164 The second part is the name of the function in C,
9165 @code{Fdelete_and_extract_region}. By convention, it starts with
9166 @samp{F}. Since C does not use hyphens in names, underscores are used
9167 instead.
9168
9169 @item
9170 The third part is the name for the C constant structure that records
9171 information on this function for internal use. It is the name of the
9172 function in C but begins with an @samp{S} instead of an @samp{F}.
9173
9174 @item
9175 The fourth and fifth parts specify the minimum and maximum number of
9176 arguments the function can have. This function demands exactly 2
9177 arguments.
9178
9179 @item
9180 The sixth part is nearly like the argument that follows the
9181 @code{interactive} declaration in a function written in Lisp: a letter
9182 followed, perhaps, by a prompt. The only difference from the Lisp is
9183 when the macro is called with no arguments. Then you write a @code{0}
9184 (which is a `null string'), as in this macro.
9185
9186 If you were to specify arguments, you would place them between
9187 quotation marks. The C macro for @code{goto-char} includes
9188 @code{"NGoto char: "} in this position to indicate that the function
9189 expects a raw prefix, in this case, a numerical location in a buffer,
9190 and provides a prompt.
9191
9192 @item
9193 The seventh part is a documentation string, just like the one for a
9194 function written in Emacs Lisp, except that every newline must be
9195 written explicitly as @samp{\n} followed by a backslash and carriage
9196 return.
9197
9198 @need 1000
9199 Thus, the first two lines of documentation for @code{goto-char} are
9200 written like this:
9201
9202 @smallexample
9203 @group
9204 "Set point to POSITION, a number or marker.\n\
9205 Beginning of buffer is position (point-min), end is (point-max)."
9206 @end group
9207 @end smallexample
9208 @end itemize
9209
9210 @need 1200
9211 In a C macro, the formal parameters come next, with a statement of
9212 what kind of object they are, followed by what might be called the `body'
9213 of the macro. For @code{delete-and-extract-region} the `body'
9214 consists of the following four lines:
9215
9216 @smallexample
9217 @group
9218 validate_region (&start, &end);
9219 if (XINT (start) == XINT (end))
9220 return build_string ("");
9221 return del_range_1 (XINT (start), XINT (end), 1, 1);
9222 @end group
9223 @end smallexample
9224
9225 The @code{validate_region} function checks whether the values
9226 passed as the beginning and end of the region are the proper type and
9227 are within range. If the beginning and end positions are the same,
9228 then return and empty string.
9229
9230 The @code{del_range_1} function actually deletes the text. It is a
9231 complex function we will not look into. It updates the buffer and
9232 does other things. However, it is worth looking at the two arguments
9233 passed to @code{del_range}. These are @w{@code{XINT (start)}} and
9234 @w{@code{XINT (end)}}.
9235
9236 As far as the C language is concerned, @code{start} and @code{end} are
9237 two integers that mark the beginning and end of the region to be
9238 deleted@footnote{More precisely, and requiring more expert knowledge
9239 to understand, the two integers are of type `Lisp_Object', which can
9240 also be a C union instead of an integer type.}.
9241
9242 In early versions of Emacs, these two numbers were thirty-two bits
9243 long, but the code is slowly being generalized to handle other
9244 lengths. Three of the available bits are used to specify the type of
9245 information; the remaining bits are used as `content'.
9246
9247 @samp{XINT} is a C macro that extracts the relevant number from the
9248 longer collection of bits; the three other bits are discarded.
9249
9250 @need 800
9251 The command in @code{delete-and-extract-region} looks like this:
9252
9253 @smallexample
9254 del_range_1 (XINT (start), XINT (end), 1, 1);
9255 @end smallexample
9256
9257 @noindent
9258 It deletes the region between the beginning position, @code{start},
9259 and the ending position, @code{end}.
9260
9261 From the point of view of the person writing Lisp, Emacs is all very
9262 simple; but hidden underneath is a great deal of complexity to make it
9263 all work.
9264
9265 @node defvar
9266 @section Initializing a Variable with @code{defvar}
9267 @findex defvar
9268 @cindex Initializing a variable
9269 @cindex Variable initialization
9270
9271 @ignore
9272 2006 Oct 24
9273 In Emacs 22,
9274 copy-region-as-kill is short, 12 lines, and uses
9275 filter-buffer-substring, which is longer, 39 lines
9276 and has delete-and-extract-region in it.
9277 delete-and-extract-region is written in C.
9278
9279 see Initializing a Variable with @code{defvar}
9280
9281 @end ignore
9282
9283 The @code{copy-region-as-kill} function is written in Emacs Lisp. Two
9284 functions within it, @code{kill-append} and @code{kill-new}, copy a
9285 region in a buffer and save it in a variable called the
9286 @code{kill-ring}. This section describes how the @code{kill-ring}
9287 variable is created and initialized using the @code{defvar} special
9288 form.
9289
9290 (Again we note that the term @code{kill-ring} is a misnomer. The text
9291 that is clipped out of the buffer can be brought back; it is not a ring
9292 of corpses, but a ring of resurrectable text.)
9293
9294 In Emacs Lisp, a variable such as the @code{kill-ring} is created and
9295 given an initial value by using the @code{defvar} special form. The
9296 name comes from ``define variable''.
9297
9298 The @code{defvar} special form is similar to @code{setq} in that it sets
9299 the value of a variable. It is unlike @code{setq} in two ways: first,
9300 it only sets the value of the variable if the variable does not already
9301 have a value. If the variable already has a value, @code{defvar} does
9302 not override the existing value. Second, @code{defvar} has a
9303 documentation string.
9304
9305 (Another special form, @code{defcustom}, is designed for variables
9306 that people customize. It has more features than @code{defvar}.
9307 (@xref{defcustom, , Setting Variables with @code{defcustom}}.)
9308
9309 @menu
9310 * See variable current value::
9311 * defvar and asterisk::
9312 @end menu
9313
9314 @ifnottex
9315 @node See variable current value
9316 @unnumberedsubsec Seeing the Current Value of a Variable
9317 @end ifnottex
9318
9319 You can see the current value of a variable, any variable, by using
9320 the @code{describe-variable} function, which is usually invoked by
9321 typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
9322 (followed by @key{RET}) when prompted, you will see what is in your
9323 current kill ring---this may be quite a lot! Conversely, if you have
9324 been doing nothing this Emacs session except read this document, you
9325 may have nothing in it. Also, you will see the documentation for
9326 @code{kill-ring}:
9327
9328 @smallexample
9329 @group
9330 Documentation:
9331 List of killed text sequences.
9332 Since the kill ring is supposed to interact nicely with cut-and-paste
9333 facilities offered by window systems, use of this variable should
9334 @end group
9335 @group
9336 interact nicely with `interprogram-cut-function' and
9337 `interprogram-paste-function'. The functions `kill-new',
9338 `kill-append', and `current-kill' are supposed to implement this
9339 interaction; you may want to use them instead of manipulating the kill
9340 ring directly.
9341 @end group
9342 @end smallexample
9343
9344 @need 800
9345 The kill ring is defined by a @code{defvar} in the following way:
9346
9347 @smallexample
9348 @group
9349 (defvar kill-ring nil
9350 "List of killed text sequences.
9351 @dots{}")
9352 @end group
9353 @end smallexample
9354
9355 @noindent
9356 In this variable definition, the variable is given an initial value of
9357 @code{nil}, which makes sense, since if you have saved nothing, you want
9358 nothing back if you give a @code{yank} command. The documentation
9359 string is written just like the documentation string of a @code{defun}.
9360 As with the documentation string of the @code{defun}, the first line of
9361 the documentation should be a complete sentence, since some commands,
9362 like @code{apropos}, print only the first line of documentation.
9363 Succeeding lines should not be indented; otherwise they look odd when
9364 you use @kbd{C-h v} (@code{describe-variable}).
9365
9366 @node defvar and asterisk
9367 @subsection @code{defvar} and an asterisk
9368 @findex defvar @r{for a user customizable variable}
9369 @findex defvar @r{with an asterisk}
9370
9371 In the past, Emacs used the @code{defvar} special form both for
9372 internal variables that you would not expect a user to change and for
9373 variables that you do expect a user to change. Although you can still
9374 use @code{defvar} for user customizable variables, please use
9375 @code{defcustom} instead, since that special form provides a path into
9376 the Customization commands. (@xref{defcustom, , Specifying Variables
9377 using @code{defcustom}}.)
9378
9379 When you specified a variable using the @code{defvar} special form,
9380 you could distinguish a variable that a user might want to change from
9381 others by typing an asterisk, @samp{*}, in the first column of its
9382 documentation string. For example:
9383
9384 @smallexample
9385 @group
9386 (defvar shell-command-default-error-buffer nil
9387 "*Buffer name for `shell-command' @dots{} error output.
9388 @dots{} ")
9389 @end group
9390 @end smallexample
9391
9392 @findex set-variable
9393 @noindent
9394 You could (and still can) use the @code{set-variable} command to
9395 change the value of @code{shell-command-default-error-buffer}
9396 temporarily. However, options set using @code{set-variable} are set
9397 only for the duration of your editing session. The new values are not
9398 saved between sessions. Each time Emacs starts, it reads the original
9399 value, unless you change the value within your @file{.emacs} file,
9400 either by setting it manually or by using @code{customize}.
9401 @xref{Emacs Initialization, , Your @file{.emacs} File}.
9402
9403 For me, the major use of the @code{set-variable} command is to suggest
9404 variables that I might want to set in my @file{.emacs} file. There
9405 are now more than 700 such variables --- far too many to remember
9406 readily. Fortunately, you can press @key{TAB} after calling the
9407 @code{M-x set-variable} command to see the list of variables.
9408 (@xref{Examining, , Examining and Setting Variables, emacs,
9409 The GNU Emacs Manual}.)
9410
9411 @need 1250
9412 @node cons & search-fwd Review
9413 @section Review
9414
9415 Here is a brief summary of some recently introduced functions.
9416
9417 @table @code
9418 @item car
9419 @itemx cdr
9420 @code{car} returns the first element of a list; @code{cdr} returns the
9421 second and subsequent elements of a list.
9422
9423 @need 1250
9424 For example:
9425
9426 @smallexample
9427 @group
9428 (car '(1 2 3 4 5 6 7))
9429 @result{} 1
9430 (cdr '(1 2 3 4 5 6 7))
9431 @result{} (2 3 4 5 6 7)
9432 @end group
9433 @end smallexample
9434
9435 @item cons
9436 @code{cons} constructs a list by prepending its first argument to its
9437 second argument.
9438
9439 @need 1250
9440 For example:
9441
9442 @smallexample
9443 @group
9444 (cons 1 '(2 3 4))
9445 @result{} (1 2 3 4)
9446 @end group
9447 @end smallexample
9448
9449 @item funcall
9450 @code{funcall} evaluates its first argument as a function. It passes
9451 its remaining arguments to its first argument.
9452
9453 @item nthcdr
9454 Return the result of taking @sc{cdr} `n' times on a list.
9455 @iftex
9456 The
9457 @tex
9458 $n^{th}$
9459 @end tex
9460 @code{cdr}.
9461 @end iftex
9462 The `rest of the rest', as it were.
9463
9464 @need 1250
9465 For example:
9466
9467 @smallexample
9468 @group
9469 (nthcdr 3 '(1 2 3 4 5 6 7))
9470 @result{} (4 5 6 7)
9471 @end group
9472 @end smallexample
9473
9474 @item setcar
9475 @itemx setcdr
9476 @code{setcar} changes the first element of a list; @code{setcdr}
9477 changes the second and subsequent elements of a list.
9478
9479 @need 1250
9480 For example:
9481
9482 @smallexample
9483 @group
9484 (setq triple '(1 2 3))
9485
9486 (setcar triple '37)
9487
9488 triple
9489 @result{} (37 2 3)
9490
9491 (setcdr triple '("foo" "bar"))
9492
9493 triple
9494 @result{} (37 "foo" "bar")
9495 @end group
9496 @end smallexample
9497
9498 @item progn
9499 Evaluate each argument in sequence and then return the value of the
9500 last.
9501
9502 @need 1250
9503 For example:
9504
9505 @smallexample
9506 @group
9507 (progn 1 2 3 4)
9508 @result{} 4
9509 @end group
9510 @end smallexample
9511
9512 @item save-restriction
9513 Record whatever narrowing is in effect in the current buffer, if any,
9514 and restore that narrowing after evaluating the arguments.
9515
9516 @item search-forward
9517 Search for a string, and if the string is found, move point. With a
9518 regular expression, use the similar @code{re-search-forward}.
9519 (@xref{Regexp Search, , Regular Expression Searches}, for an
9520 explanation of regular expression patterns and searches.)
9521
9522 @need 1250
9523 @noindent
9524 @code{search-forward} and @code{re-search-forward} take four
9525 arguments:
9526
9527 @enumerate
9528 @item
9529 The string or regular expression to search for.
9530
9531 @item
9532 Optionally, the limit of the search.
9533
9534 @item
9535 Optionally, what to do if the search fails, return @code{nil} or an
9536 error message.
9537
9538 @item
9539 Optionally, how many times to repeat the search; if negative, the
9540 search goes backwards.
9541 @end enumerate
9542
9543 @item kill-region
9544 @itemx delete-and-extract-region
9545 @itemx copy-region-as-kill
9546
9547 @code{kill-region} cuts the text between point and mark from the
9548 buffer and stores that text in the kill ring, so you can get it back
9549 by yanking.
9550
9551 @code{copy-region-as-kill} copies the text between point and mark into
9552 the kill ring, from which you can get it by yanking. The function
9553 does not cut or remove the text from the buffer.
9554 @end table
9555
9556 @code{delete-and-extract-region} removes the text between point and
9557 mark from the buffer and throws it away. You cannot get it back.
9558 (This is not an interactive command.)
9559
9560 @need 1500
9561 @node search Exercises
9562 @section Searching Exercises
9563
9564 @itemize @bullet
9565 @item
9566 Write an interactive function that searches for a string. If the
9567 search finds the string, leave point after it and display a message
9568 that says ``Found!''. (Do not use @code{search-forward} for the name
9569 of this function; if you do, you will overwrite the existing version of
9570 @code{search-forward} that comes with Emacs. Use a name such as
9571 @code{test-search} instead.)
9572
9573 @item
9574 Write a function that prints the third element of the kill ring in the
9575 echo area, if any; if the kill ring does not contain a third element,
9576 print an appropriate message.
9577 @end itemize
9578
9579 @node List Implementation
9580 @chapter How Lists are Implemented
9581 @cindex Lists in a computer
9582
9583 In Lisp, atoms are recorded in a straightforward fashion; if the
9584 implementation is not straightforward in practice, it is, nonetheless,
9585 straightforward in theory. The atom @samp{rose}, for example, is
9586 recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
9587 @samp{e}. A list, on the other hand, is kept differently. The mechanism
9588 is equally simple, but it takes a moment to get used to the idea. A
9589 list is kept using a series of pairs of pointers. In the series, the
9590 first pointer in each pair points to an atom or to another list, and the
9591 second pointer in each pair points to the next pair, or to the symbol
9592 @code{nil}, which marks the end of the list.
9593
9594 A pointer itself is quite simply the electronic address of what is
9595 pointed to. Hence, a list is kept as a series of electronic addresses.
9596
9597 @menu
9598 * Lists diagrammed::
9599 * Symbols as Chest:: Exploring a powerful metaphor.
9600 * List Exercise::
9601 @end menu
9602
9603 @ifnottex
9604 @node Lists diagrammed
9605 @unnumberedsec Lists diagrammed
9606 @end ifnottex
9607
9608 For example, the list @code{(rose violet buttercup)} has three elements,
9609 @samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
9610 electronic address of @samp{rose} is recorded in a segment of computer
9611 memory along with the address that gives the electronic address of where
9612 the atom @samp{violet} is located; and that address (the one that tells
9613 where @samp{violet} is located) is kept along with an address that tells
9614 where the address for the atom @samp{buttercup} is located.
9615
9616 @need 1200
9617 This sounds more complicated than it is and is easier seen in a diagram:
9618
9619 @c clear print-postscript-figures
9620 @c !!! cons-cell-diagram #1
9621 @ifnottex
9622 @smallexample
9623 @group
9624 ___ ___ ___ ___ ___ ___
9625 |___|___|--> |___|___|--> |___|___|--> nil
9626 | | |
9627 | | |
9628 --> rose --> violet --> buttercup
9629 @end group
9630 @end smallexample
9631 @end ifnottex
9632 @ifset print-postscript-figures
9633 @sp 1
9634 @tex
9635 @center @image{cons-1}
9636 %%%% old method of including an image
9637 % \input /usr/local/lib/tex/inputs/psfig.tex
9638 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
9639 % \catcode`\@=0 %
9640 @end tex
9641 @sp 1
9642 @end ifset
9643 @ifclear print-postscript-figures
9644 @iftex
9645 @smallexample
9646 @group
9647 ___ ___ ___ ___ ___ ___
9648 |___|___|--> |___|___|--> |___|___|--> nil
9649 | | |
9650 | | |
9651 --> rose --> violet --> buttercup
9652 @end group
9653 @end smallexample
9654 @end iftex
9655 @end ifclear
9656
9657 @noindent
9658 In the diagram, each box represents a word of computer memory that
9659 holds a Lisp object, usually in the form of a memory address. The boxes,
9660 i.e.@: the addresses, are in pairs. Each arrow points to what the address
9661 is the address of, either an atom or another pair of addresses. The
9662 first box is the electronic address of @samp{rose} and the arrow points
9663 to @samp{rose}; the second box is the address of the next pair of boxes,
9664 the first part of which is the address of @samp{violet} and the second
9665 part of which is the address of the next pair. The very last box
9666 points to the symbol @code{nil}, which marks the end of the list.
9667
9668 @need 1200
9669 When a variable is set to a list with a function such as @code{setq},
9670 it stores the address of the first box in the variable. Thus,
9671 evaluation of the expression
9672
9673 @smallexample
9674 (setq bouquet '(rose violet buttercup))
9675 @end smallexample
9676
9677 @need 1250
9678 @noindent
9679 creates a situation like this:
9680
9681 @c cons-cell-diagram #2
9682 @ifnottex
9683 @smallexample
9684 @group
9685 bouquet
9686 |
9687 | ___ ___ ___ ___ ___ ___
9688 --> |___|___|--> |___|___|--> |___|___|--> nil
9689 | | |
9690 | | |
9691 --> rose --> violet --> buttercup
9692 @end group
9693 @end smallexample
9694 @end ifnottex
9695 @ifset print-postscript-figures
9696 @sp 1
9697 @tex
9698 @center @image{cons-2}
9699 %%%% old method of including an image
9700 % \input /usr/local/lib/tex/inputs/psfig.tex
9701 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
9702 % \catcode`\@=0 %
9703 @end tex
9704 @sp 1
9705 @end ifset
9706 @ifclear print-postscript-figures
9707 @iftex
9708 @smallexample
9709 @group
9710 bouquet
9711 |
9712 | ___ ___ ___ ___ ___ ___
9713 --> |___|___|--> |___|___|--> |___|___|--> nil
9714 | | |
9715 | | |
9716 --> rose --> violet --> buttercup
9717 @end group
9718 @end smallexample
9719 @end iftex
9720 @end ifclear
9721
9722 @noindent
9723 In this example, the symbol @code{bouquet} holds the address of the first
9724 pair of boxes.
9725
9726 @need 1200
9727 This same list can be illustrated in a different sort of box notation
9728 like this:
9729
9730 @c cons-cell-diagram #2a
9731 @ifnottex
9732 @smallexample
9733 @group
9734 bouquet
9735 |
9736 | -------------- --------------- ----------------
9737 | | car | cdr | | car | cdr | | car | cdr |
9738 -->| rose | o------->| violet | o------->| butter- | nil |
9739 | | | | | | | cup | |
9740 -------------- --------------- ----------------
9741 @end group
9742 @end smallexample
9743 @end ifnottex
9744 @ifset print-postscript-figures
9745 @sp 1
9746 @tex
9747 @center @image{cons-2a}
9748 %%%% old method of including an image
9749 % \input /usr/local/lib/tex/inputs/psfig.tex
9750 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9751 % \catcode`\@=0 %
9752 @end tex
9753 @sp 1
9754 @end ifset
9755 @ifclear print-postscript-figures
9756 @iftex
9757 @smallexample
9758 @group
9759 bouquet
9760 |
9761 | -------------- --------------- ----------------
9762 | | car | cdr | | car | cdr | | car | cdr |
9763 -->| rose | o------->| violet | o------->| butter- | nil |
9764 | | | | | | | cup | |
9765 -------------- --------------- ----------------
9766 @end group
9767 @end smallexample
9768 @end iftex
9769 @end ifclear
9770
9771 (Symbols consist of more than pairs of addresses, but the structure of
9772 a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9773 consists of a group of address-boxes, one of which is the address of
9774 the printed word @samp{bouquet}, a second of which is the address of a
9775 function definition attached to the symbol, if any, a third of which
9776 is the address of the first pair of address-boxes for the list
9777 @code{(rose violet buttercup)}, and so on. Here we are showing that
9778 the symbol's third address-box points to the first pair of
9779 address-boxes for the list.)
9780
9781 If a symbol is set to the @sc{cdr} of a list, the list itself is not
9782 changed; the symbol simply has an address further down the list. (In
9783 the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9784 evaluation of the following expression
9785
9786 @smallexample
9787 (setq flowers (cdr bouquet))
9788 @end smallexample
9789
9790 @need 800
9791 @noindent
9792 produces this:
9793
9794 @c cons-cell-diagram #3
9795 @ifnottex
9796 @sp 1
9797 @smallexample
9798 @group
9799 bouquet flowers
9800 | |
9801 | ___ ___ | ___ ___ ___ ___
9802 --> | | | --> | | | | | |
9803 |___|___|----> |___|___|--> |___|___|--> nil
9804 | | |
9805 | | |
9806 --> rose --> violet --> buttercup
9807 @end group
9808 @end smallexample
9809 @sp 1
9810 @end ifnottex
9811 @ifset print-postscript-figures
9812 @sp 1
9813 @tex
9814 @center @image{cons-3}
9815 %%%% old method of including an image
9816 % \input /usr/local/lib/tex/inputs/psfig.tex
9817 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9818 % \catcode`\@=0 %
9819 @end tex
9820 @sp 1
9821 @end ifset
9822 @ifclear print-postscript-figures
9823 @iftex
9824 @sp 1
9825 @smallexample
9826 @group
9827 bouquet flowers
9828 | |
9829 | ___ ___ | ___ ___ ___ ___
9830 --> | | | --> | | | | | |
9831 |___|___|----> |___|___|--> |___|___|--> nil
9832 | | |
9833 | | |
9834 --> rose --> violet --> buttercup
9835 @end group
9836 @end smallexample
9837 @sp 1
9838 @end iftex
9839 @end ifclear
9840
9841 @noindent
9842 The value of @code{flowers} is @code{(violet buttercup)}, which is
9843 to say, the symbol @code{flowers} holds the address of the pair of
9844 address-boxes, the first of which holds the address of @code{violet},
9845 and the second of which holds the address of @code{buttercup}.
9846
9847 A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9848 pair}. @xref{Cons Cell Type, , Cons Cell and List Types, elisp, The GNU Emacs Lisp
9849 Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9850 Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9851 information about cons cells and dotted pairs.
9852
9853 @need 1200
9854 The function @code{cons} adds a new pair of addresses to the front of
9855 a series of addresses like that shown above. For example, evaluating
9856 the expression
9857
9858 @smallexample
9859 (setq bouquet (cons 'lily bouquet))
9860 @end smallexample
9861
9862 @need 1500
9863 @noindent
9864 produces:
9865
9866 @c cons-cell-diagram #4
9867 @ifnottex
9868 @sp 1
9869 @smallexample
9870 @group
9871 bouquet flowers
9872 | |
9873 | ___ ___ ___ ___ | ___ ___ ___ ___
9874 --> | | | | | | --> | | | | | |
9875 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9876 | | | |
9877 | | | |
9878 --> lily --> rose --> violet --> buttercup
9879 @end group
9880 @end smallexample
9881 @sp 1
9882 @end ifnottex
9883 @ifset print-postscript-figures
9884 @sp 1
9885 @tex
9886 @center @image{cons-4}
9887 %%%% old method of including an image
9888 % \input /usr/local/lib/tex/inputs/psfig.tex
9889 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9890 % \catcode`\@=0 %
9891 @end tex
9892 @sp 1
9893 @end ifset
9894 @ifclear print-postscript-figures
9895 @iftex
9896 @sp 1
9897 @smallexample
9898 @group
9899 bouquet flowers
9900 | |
9901 | ___ ___ ___ ___ | ___ ___ ___ ___
9902 --> | | | | | | --> | | | | | |
9903 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9904 | | | |
9905 | | | |
9906 --> lily --> rose --> violet --> buttercup
9907 @end group
9908 @end smallexample
9909 @sp 1
9910 @end iftex
9911 @end ifclear
9912
9913 @need 1200
9914 @noindent
9915 However, this does not change the value of the symbol
9916 @code{flowers}, as you can see by evaluating the following,
9917
9918 @smallexample
9919 (eq (cdr (cdr bouquet)) flowers)
9920 @end smallexample
9921
9922 @noindent
9923 which returns @code{t} for true.
9924
9925 Until it is reset, @code{flowers} still has the value
9926 @code{(violet buttercup)}; that is, it has the address of the cons
9927 cell whose first address is of @code{violet}. Also, this does not
9928 alter any of the pre-existing cons cells; they are all still there.
9929
9930 Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9931 of the next cons cell in the series; to get the @sc{car} of a list,
9932 you get the address of the first element of the list; to @code{cons} a
9933 new element on a list, you add a new cons cell to the front of the list.
9934 That is all there is to it! The underlying structure of Lisp is
9935 brilliantly simple!
9936
9937 And what does the last address in a series of cons cells refer to? It
9938 is the address of the empty list, of @code{nil}.
9939
9940 In summary, when a Lisp variable is set to a value, it is provided with
9941 the address of the list to which the variable refers.
9942
9943 @node Symbols as Chest
9944 @section Symbols as a Chest of Drawers
9945 @cindex Symbols as a Chest of Drawers
9946 @cindex Chest of Drawers, metaphor for a symbol
9947 @cindex Drawers, Chest of, metaphor for a symbol
9948
9949 In an earlier section, I suggested that you might imagine a symbol as
9950 being a chest of drawers. The function definition is put in one
9951 drawer, the value in another, and so on. What is put in the drawer
9952 holding the value can be changed without affecting the contents of the
9953 drawer holding the function definition, and vice-verse.
9954
9955 Actually, what is put in each drawer is the address of the value or
9956 function definition. It is as if you found an old chest in the attic,
9957 and in one of its drawers you found a map giving you directions to
9958 where the buried treasure lies.
9959
9960 (In addition to its name, symbol definition, and variable value, a
9961 symbol has a `drawer' for a @dfn{property list} which can be used to
9962 record other information. Property lists are not discussed here; see
9963 @ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9964 Reference Manual}.)
9965
9966 @need 1500
9967 Here is a fanciful representation:
9968
9969 @c chest-of-drawers diagram
9970 @ifnottex
9971 @sp 1
9972 @smallexample
9973 @group
9974 Chest of Drawers Contents of Drawers
9975
9976 __ o0O0o __
9977 / \
9978 ---------------------
9979 | directions to | [map to]
9980 | symbol name | bouquet
9981 | |
9982 +---------------------+
9983 | directions to |
9984 | symbol definition | [none]
9985 | |
9986 +---------------------+
9987 | directions to | [map to]
9988 | variable value | (rose violet buttercup)
9989 | |
9990 +---------------------+
9991 | directions to |
9992 | property list | [not described here]
9993 | |
9994 +---------------------+
9995 |/ \|
9996 @end group
9997 @end smallexample
9998 @sp 1
9999 @end ifnottex
10000 @ifset print-postscript-figures
10001 @sp 1
10002 @tex
10003 @center @image{drawers}
10004 %%%% old method of including an image
10005 % \input /usr/local/lib/tex/inputs/psfig.tex
10006 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
10007 % \catcode`\@=0 %
10008 @end tex
10009 @sp 1
10010 @end ifset
10011 @ifclear print-postscript-figures
10012 @iftex
10013 @sp 1
10014 @smallexample
10015 @group
10016 Chest of Drawers Contents of Drawers
10017
10018 __ o0O0o __
10019 / \
10020 ---------------------
10021 | directions to | [map to]
10022 | symbol name | bouquet
10023 | |
10024 +---------------------+
10025 | directions to |
10026 | symbol definition | [none]
10027 | |
10028 +---------------------+
10029 | directions to | [map to]
10030 | variable value | (rose violet buttercup)
10031 | |
10032 +---------------------+
10033 | directions to |
10034 | property list | [not described here]
10035 | |
10036 +---------------------+
10037 |/ \|
10038 @end group
10039 @end smallexample
10040 @sp 1
10041 @end iftex
10042 @end ifclear
10043
10044 @node List Exercise
10045 @section Exercise
10046
10047 Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
10048 more flowers on to this list and set this new list to
10049 @code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
10050 What does the @code{more-flowers} list now contain?
10051
10052 @node Yanking
10053 @chapter Yanking Text Back
10054 @findex yank
10055 @cindex Text retrieval
10056 @cindex Retrieving text
10057 @cindex Pasting text
10058
10059 Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
10060 you can bring it back with a `yank' command. The text that is cut out of
10061 the buffer is put in the kill ring and the yank commands insert the
10062 appropriate contents of the kill ring back into a buffer (not necessarily
10063 the original buffer).
10064
10065 A simple @kbd{C-y} (@code{yank}) command inserts the first item from
10066 the kill ring into the current buffer. If the @kbd{C-y} command is
10067 followed immediately by @kbd{M-y}, the first element is replaced by
10068 the second element. Successive @kbd{M-y} commands replace the second
10069 element with the third, fourth, or fifth element, and so on. When the
10070 last element in the kill ring is reached, it is replaced by the first
10071 element and the cycle is repeated. (Thus the kill ring is called a
10072 `ring' rather than just a `list'. However, the actual data structure
10073 that holds the text is a list.
10074 @xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
10075 list is handled as a ring.)
10076
10077 @menu
10078 * Kill Ring Overview::
10079 * kill-ring-yank-pointer:: The kill ring is a list.
10080 * yank nthcdr Exercises:: The @code{kill-ring-yank-pointer} variable.
10081 @end menu
10082
10083 @node Kill Ring Overview
10084 @section Kill Ring Overview
10085 @cindex Kill ring overview
10086
10087 The kill ring is a list of textual strings. This is what it looks like:
10088
10089 @smallexample
10090 ("some text" "a different piece of text" "yet more text")
10091 @end smallexample
10092
10093 If this were the contents of my kill ring and I pressed @kbd{C-y}, the
10094 string of characters saying @samp{some text} would be inserted in this
10095 buffer where my cursor is located.
10096
10097 The @code{yank} command is also used for duplicating text by copying it.
10098 The copied text is not cut from the buffer, but a copy of it is put on the
10099 kill ring and is inserted by yanking it back.
10100
10101 Three functions are used for bringing text back from the kill ring:
10102 @code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
10103 which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
10104 which is used by the two other functions.
10105
10106 These functions refer to the kill ring through a variable called the
10107 @code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
10108 @code{yank} and @code{yank-pop} functions is:
10109
10110 @smallexample
10111 (insert (car kill-ring-yank-pointer))
10112 @end smallexample
10113
10114 @noindent
10115 (Well, no more. In GNU Emacs 22, the function has been replaced by
10116 @code{insert-for-yank} which calls @code{insert-for-yank-1}
10117 repetitively for each @code{yank-handler} segment. In turn,
10118 @code{insert-for-yank-1} strips text properties from the inserted text
10119 according to @code{yank-excluded-properties}. Otherwise, it is just
10120 like @code{insert}. We will stick with plain @code{insert} since it
10121 is easier to understand.)
10122
10123 To begin to understand how @code{yank} and @code{yank-pop} work, it is
10124 first necessary to look at the @code{kill-ring-yank-pointer} variable.
10125
10126 @node kill-ring-yank-pointer
10127 @section The @code{kill-ring-yank-pointer} Variable
10128
10129 @code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
10130 a variable. It points to something by being bound to the value of what
10131 it points to, like any other Lisp variable.
10132
10133 @need 1000
10134 Thus, if the value of the kill ring is:
10135
10136 @smallexample
10137 ("some text" "a different piece of text" "yet more text")
10138 @end smallexample
10139
10140 @need 1250
10141 @noindent
10142 and the @code{kill-ring-yank-pointer} points to the second clause, the
10143 value of @code{kill-ring-yank-pointer} is:
10144
10145 @smallexample
10146 ("a different piece of text" "yet more text")
10147 @end smallexample
10148
10149 As explained in the previous chapter (@pxref{List Implementation}), the
10150 computer does not keep two different copies of the text being pointed to
10151 by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
10152 words ``a different piece of text'' and ``yet more text'' are not
10153 duplicated. Instead, the two Lisp variables point to the same pieces of
10154 text. Here is a diagram:
10155
10156 @c cons-cell-diagram #5
10157 @ifnottex
10158 @smallexample
10159 @group
10160 kill-ring kill-ring-yank-pointer
10161 | |
10162 | ___ ___ | ___ ___ ___ ___
10163 ---> | | | --> | | | | | |
10164 |___|___|----> |___|___|--> |___|___|--> nil
10165 | | |
10166 | | |
10167 | | --> "yet more text"
10168 | |
10169 | --> "a different piece of text"
10170 |
10171 --> "some text"
10172 @end group
10173 @end smallexample
10174 @sp 1
10175 @end ifnottex
10176 @ifset print-postscript-figures
10177 @sp 1
10178 @tex
10179 @center @image{cons-5}
10180 %%%% old method of including an image
10181 % \input /usr/local/lib/tex/inputs/psfig.tex
10182 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
10183 % \catcode`\@=0 %
10184 @end tex
10185 @sp 1
10186 @end ifset
10187 @ifclear print-postscript-figures
10188 @iftex
10189 @smallexample
10190 @group
10191 kill-ring kill-ring-yank-pointer
10192 | |
10193 | ___ ___ | ___ ___ ___ ___
10194 ---> | | | --> | | | | | |
10195 |___|___|----> |___|___|--> |___|___|--> nil
10196 | | |
10197 | | |
10198 | | --> "yet more text"
10199 | |
10200 | --> "a different piece of text
10201 |
10202 --> "some text"
10203 @end group
10204 @end smallexample
10205 @sp 1
10206 @end iftex
10207 @end ifclear
10208
10209 Both the variable @code{kill-ring} and the variable
10210 @code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
10211 usually described as if it were actually what it is composed of. The
10212 @code{kill-ring} is spoken of as if it were the list rather than that it
10213 points to the list. Conversely, the @code{kill-ring-yank-pointer} is
10214 spoken of as pointing to a list.
10215
10216 These two ways of talking about the same thing sound confusing at first but
10217 make sense on reflection. The kill ring is generally thought of as the
10218 complete structure of data that holds the information of what has recently
10219 been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
10220 on the other hand, serves to indicate---that is, to `point to'---that part
10221 of the kill ring of which the first element (the @sc{car}) will be
10222 inserted.
10223
10224 @ignore
10225 In GNU Emacs 22, the @code{kill-new} function calls
10226
10227 @code{(setq kill-ring-yank-pointer kill-ring)}
10228
10229 (defun rotate-yank-pointer (arg)
10230 "Rotate the yanking point in the kill ring.
10231 With argument, rotate that many kills forward (or backward, if negative)."
10232 (interactive "p")
10233 (current-kill arg))
10234
10235 (defun current-kill (n &optional do-not-move)
10236 "Rotate the yanking point by N places, and then return that kill.
10237 If N is zero, `interprogram-paste-function' is set, and calling it
10238 returns a string, then that string is added to the front of the
10239 kill ring and returned as the latest kill.
10240 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
10241 yanking point; just return the Nth kill forward."
10242 (let ((interprogram-paste (and (= n 0)
10243 interprogram-paste-function
10244 (funcall interprogram-paste-function))))
10245 (if interprogram-paste
10246 (progn
10247 ;; Disable the interprogram cut function when we add the new
10248 ;; text to the kill ring, so Emacs doesn't try to own the
10249 ;; selection, with identical text.
10250 (let ((interprogram-cut-function nil))
10251 (kill-new interprogram-paste))
10252 interprogram-paste)
10253 (or kill-ring (error "Kill ring is empty"))
10254 (let ((ARGth-kill-element
10255 (nthcdr (mod (- n (length kill-ring-yank-pointer))
10256 (length kill-ring))
10257 kill-ring)))
10258 (or do-not-move
10259 (setq kill-ring-yank-pointer ARGth-kill-element))
10260 (car ARGth-kill-element)))))
10261
10262 @end ignore
10263
10264 @need 1500
10265 @node yank nthcdr Exercises
10266 @section Exercises with @code{yank} and @code{nthcdr}
10267
10268 @itemize @bullet
10269 @item
10270 Using @kbd{C-h v} (@code{describe-variable}), look at the value of
10271 your kill ring. Add several items to your kill ring; look at its
10272 value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
10273 around the kill ring. How many items were in your kill ring? Find
10274 the value of @code{kill-ring-max}. Was your kill ring full, or could
10275 you have kept more blocks of text within it?
10276
10277 @item
10278 Using @code{nthcdr} and @code{car}, construct a series of expressions
10279 to return the first, second, third, and fourth elements of a list.
10280 @end itemize
10281
10282 @node Loops & Recursion
10283 @chapter Loops and Recursion
10284 @cindex Loops and recursion
10285 @cindex Recursion and loops
10286 @cindex Repetition (loops)
10287
10288 Emacs Lisp has two primary ways to cause an expression, or a series of
10289 expressions, to be evaluated repeatedly: one uses a @code{while}
10290 loop, and the other uses @dfn{recursion}.
10291
10292 Repetition can be very valuable. For example, to move forward four
10293 sentences, you need only write a program that will move forward one
10294 sentence and then repeat the process four times. Since a computer does
10295 not get bored or tired, such repetitive action does not have the
10296 deleterious effects that excessive or the wrong kinds of repetition can
10297 have on humans.
10298
10299 People mostly write Emacs Lisp functions using @code{while} loops and
10300 their kin; but you can use recursion, which provides a very powerful
10301 way to think about and then to solve problems@footnote{You can write
10302 recursive functions to be frugal or wasteful of mental or computer
10303 resources; as it happens, methods that people find easy---that are
10304 frugal of `mental resources'---sometimes use considerable computer
10305 resources. Emacs was designed to run on machines that we now consider
10306 limited and its default settings are conservative. You may want to
10307 increase the values of @code{max-specpdl-size} and
10308 @code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
10309 15 and 30 times their default value.}.
10310
10311 @menu
10312 * while:: Causing a stretch of code to repeat.
10313 * dolist dotimes::
10314 * Recursion:: Causing a function to call itself.
10315 * Looping exercise::
10316 @end menu
10317
10318 @node while
10319 @section @code{while}
10320 @cindex Loops
10321 @findex while
10322
10323 The @code{while} special form tests whether the value returned by
10324 evaluating its first argument is true or false. This is similar to what
10325 the Lisp interpreter does with an @code{if}; what the interpreter does
10326 next, however, is different.
10327
10328 In a @code{while} expression, if the value returned by evaluating the
10329 first argument is false, the Lisp interpreter skips the rest of the
10330 expression (the @dfn{body} of the expression) and does not evaluate it.
10331 However, if the value is true, the Lisp interpreter evaluates the body
10332 of the expression and then again tests whether the first argument to
10333 @code{while} is true or false. If the value returned by evaluating the
10334 first argument is again true, the Lisp interpreter again evaluates the
10335 body of the expression.
10336
10337 @need 1200
10338 The template for a @code{while} expression looks like this:
10339
10340 @smallexample
10341 @group
10342 (while @var{true-or-false-test}
10343 @var{body}@dots{})
10344 @end group
10345 @end smallexample
10346
10347 @menu
10348 * Looping with while:: Repeat so long as test returns true.
10349 * Loop Example:: A @code{while} loop that uses a list.
10350 * print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
10351 * Incrementing Loop:: A loop with an incrementing counter.
10352 * Incrementing Loop Details::
10353 * Decrementing Loop:: A loop with a decrementing counter.
10354 @end menu
10355
10356 @ifnottex
10357 @node Looping with while
10358 @unnumberedsubsec Looping with @code{while}
10359 @end ifnottex
10360
10361 So long as the true-or-false-test of the @code{while} expression
10362 returns a true value when it is evaluated, the body is repeatedly
10363 evaluated. This process is called a loop since the Lisp interpreter
10364 repeats the same thing again and again, like an airplane doing a loop.
10365 When the result of evaluating the true-or-false-test is false, the
10366 Lisp interpreter does not evaluate the rest of the @code{while}
10367 expression and `exits the loop'.
10368
10369 Clearly, if the value returned by evaluating the first argument to
10370 @code{while} is always true, the body following will be evaluated
10371 again and again @dots{} and again @dots{} forever. Conversely, if the
10372 value returned is never true, the expressions in the body will never
10373 be evaluated. The craft of writing a @code{while} loop consists of
10374 choosing a mechanism such that the true-or-false-test returns true
10375 just the number of times that you want the subsequent expressions to
10376 be evaluated, and then have the test return false.
10377
10378 The value returned by evaluating a @code{while} is the value of the
10379 true-or-false-test. An interesting consequence of this is that a
10380 @code{while} loop that evaluates without error will return @code{nil}
10381 or false regardless of whether it has looped 1 or 100 times or none at
10382 all. A @code{while} expression that evaluates successfully never
10383 returns a true value! What this means is that @code{while} is always
10384 evaluated for its side effects, which is to say, the consequences of
10385 evaluating the expressions within the body of the @code{while} loop.
10386 This makes sense. It is not the mere act of looping that is desired,
10387 but the consequences of what happens when the expressions in the loop
10388 are repeatedly evaluated.
10389
10390 @node Loop Example
10391 @subsection A @code{while} Loop and a List
10392
10393 A common way to control a @code{while} loop is to test whether a list
10394 has any elements. If it does, the loop is repeated; but if it does not,
10395 the repetition is ended. Since this is an important technique, we will
10396 create a short example to illustrate it.
10397
10398 A simple way to test whether a list has elements is to evaluate the
10399 list: if it has no elements, it is an empty list and will return the
10400 empty list, @code{()}, which is a synonym for @code{nil} or false. On
10401 the other hand, a list with elements will return those elements when it
10402 is evaluated. Since Emacs Lisp considers as true any value that is not
10403 @code{nil}, a list that returns elements will test true in a
10404 @code{while} loop.
10405
10406 @need 1200
10407 For example, you can set the variable @code{empty-list} to @code{nil} by
10408 evaluating the following @code{setq} expression:
10409
10410 @smallexample
10411 (setq empty-list ())
10412 @end smallexample
10413
10414 @noindent
10415 After evaluating the @code{setq} expression, you can evaluate the
10416 variable @code{empty-list} in the usual way, by placing the cursor after
10417 the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
10418 echo area:
10419
10420 @smallexample
10421 empty-list
10422 @end smallexample
10423
10424 On the other hand, if you set a variable to be a list with elements, the
10425 list will appear when you evaluate the variable, as you can see by
10426 evaluating the following two expressions:
10427
10428 @smallexample
10429 @group
10430 (setq animals '(gazelle giraffe lion tiger))
10431
10432 animals
10433 @end group
10434 @end smallexample
10435
10436 Thus, to create a @code{while} loop that tests whether there are any
10437 items in the list @code{animals}, the first part of the loop will be
10438 written like this:
10439
10440 @smallexample
10441 @group
10442 (while animals
10443 @dots{}
10444 @end group
10445 @end smallexample
10446
10447 @noindent
10448 When the @code{while} tests its first argument, the variable
10449 @code{animals} is evaluated. It returns a list. So long as the list
10450 has elements, the @code{while} considers the results of the test to be
10451 true; but when the list is empty, it considers the results of the test
10452 to be false.
10453
10454 To prevent the @code{while} loop from running forever, some mechanism
10455 needs to be provided to empty the list eventually. An oft-used
10456 technique is to have one of the subsequent forms in the @code{while}
10457 expression set the value of the list to be the @sc{cdr} of the list.
10458 Each time the @code{cdr} function is evaluated, the list will be made
10459 shorter, until eventually only the empty list will be left. At this
10460 point, the test of the @code{while} loop will return false, and the
10461 arguments to the @code{while} will no longer be evaluated.
10462
10463 For example, the list of animals bound to the variable @code{animals}
10464 can be set to be the @sc{cdr} of the original list with the
10465 following expression:
10466
10467 @smallexample
10468 (setq animals (cdr animals))
10469 @end smallexample
10470
10471 @noindent
10472 If you have evaluated the previous expressions and then evaluate this
10473 expression, you will see @code{(giraffe lion tiger)} appear in the echo
10474 area. If you evaluate the expression again, @code{(lion tiger)} will
10475 appear in the echo area. If you evaluate it again and yet again,
10476 @code{(tiger)} appears and then the empty list, shown by @code{nil}.
10477
10478 A template for a @code{while} loop that uses the @code{cdr} function
10479 repeatedly to cause the true-or-false-test eventually to test false
10480 looks like this:
10481
10482 @smallexample
10483 @group
10484 (while @var{test-whether-list-is-empty}
10485 @var{body}@dots{}
10486 @var{set-list-to-cdr-of-list})
10487 @end group
10488 @end smallexample
10489
10490 This test and use of @code{cdr} can be put together in a function that
10491 goes through a list and prints each element of the list on a line of its
10492 own.
10493
10494 @node print-elements-of-list
10495 @subsection An Example: @code{print-elements-of-list}
10496 @findex print-elements-of-list
10497
10498 The @code{print-elements-of-list} function illustrates a @code{while}
10499 loop with a list.
10500
10501 @cindex @file{*scratch*} buffer
10502 The function requires several lines for its output. If you are
10503 reading this in a recent instance of GNU Emacs,
10504 @c GNU Emacs 21, GNU Emacs 22, or a later version,
10505 you can evaluate the following expression inside of Info, as usual.
10506
10507 If you are using an earlier version of Emacs, you need to copy the
10508 necessary expressions to your @file{*scratch*} buffer and evaluate
10509 them there. This is because the echo area had only one line in the
10510 earlier versions.
10511
10512 You can copy the expressions by marking the beginning of the region
10513 with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
10514 the end of the region and then copying the region using @kbd{M-w}
10515 (@code{kill-ring-save}, which calls @code{copy-region-as-kill} and
10516 then provides visual feedback). In the @file{*scratch*}
10517 buffer, you can yank the expressions back by typing @kbd{C-y}
10518 (@code{yank}).
10519
10520 After you have copied the expressions to the @file{*scratch*} buffer,
10521 evaluate each expression in turn. Be sure to evaluate the last
10522 expression, @code{(print-elements-of-list animals)}, by typing
10523 @kbd{C-u C-x C-e}, that is, by giving an argument to
10524 @code{eval-last-sexp}. This will cause the result of the evaluation
10525 to be printed in the @file{*scratch*} buffer instead of being printed
10526 in the echo area. (Otherwise you will see something like this in your
10527 echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
10528 each @samp{^J} stands for a `newline'.)
10529
10530 @need 1500
10531 In a recent instance of GNU Emacs, you can evaluate these expressions
10532 directly in the Info buffer, and the echo area will grow to show the
10533 results.
10534
10535 @smallexample
10536 @group
10537 (setq animals '(gazelle giraffe lion tiger))
10538
10539 (defun print-elements-of-list (list)
10540 "Print each element of LIST on a line of its own."
10541 (while list
10542 (print (car list))
10543 (setq list (cdr list))))
10544
10545 (print-elements-of-list animals)
10546 @end group
10547 @end smallexample
10548
10549 @need 1200
10550 @noindent
10551 When you evaluate the three expressions in sequence, you will see
10552 this:
10553
10554 @smallexample
10555 @group
10556 gazelle
10557
10558 giraffe
10559
10560 lion
10561
10562 tiger
10563 nil
10564 @end group
10565 @end smallexample
10566
10567 Each element of the list is printed on a line of its own (that is what
10568 the function @code{print} does) and then the value returned by the
10569 function is printed. Since the last expression in the function is the
10570 @code{while} loop, and since @code{while} loops always return
10571 @code{nil}, a @code{nil} is printed after the last element of the list.
10572
10573 @node Incrementing Loop
10574 @subsection A Loop with an Incrementing Counter
10575
10576 A loop is not useful unless it stops when it ought. Besides
10577 controlling a loop with a list, a common way of stopping a loop is to
10578 write the first argument as a test that returns false when the correct
10579 number of repetitions are complete. This means that the loop must
10580 have a counter---an expression that counts how many times the loop
10581 repeats itself.
10582
10583 @ifnottex
10584 @node Incrementing Loop Details
10585 @unnumberedsubsec Details of an Incrementing Loop
10586 @end ifnottex
10587
10588 The test for a loop with an incrementing counter can be an expression
10589 such as @code{(< count desired-number)} which returns @code{t} for
10590 true if the value of @code{count} is less than the
10591 @code{desired-number} of repetitions and @code{nil} for false if the
10592 value of @code{count} is equal to or is greater than the
10593 @code{desired-number}. The expression that increments the count can
10594 be a simple @code{setq} such as @code{(setq count (1+ count))}, where
10595 @code{1+} is a built-in function in Emacs Lisp that adds 1 to its
10596 argument. (The expression @w{@code{(1+ count)}} has the same result
10597 as @w{@code{(+ count 1)}}, but is easier for a human to read.)
10598
10599 @need 1250
10600 The template for a @code{while} loop controlled by an incrementing
10601 counter looks like this:
10602
10603 @smallexample
10604 @group
10605 @var{set-count-to-initial-value}
10606 (while (< count desired-number) ; @r{true-or-false-test}
10607 @var{body}@dots{}
10608 (setq count (1+ count))) ; @r{incrementer}
10609 @end group
10610 @end smallexample
10611
10612 @noindent
10613 Note that you need to set the initial value of @code{count}; usually it
10614 is set to 1.
10615
10616 @menu
10617 * Incrementing Example:: Counting pebbles in a triangle.
10618 * Inc Example parts:: The parts of the function definition.
10619 * Inc Example altogether:: Putting the function definition together.
10620 @end menu
10621
10622 @node Incrementing Example
10623 @unnumberedsubsubsec Example with incrementing counter
10624
10625 Suppose you are playing on the beach and decide to make a triangle of
10626 pebbles, putting one pebble in the first row, two in the second row,
10627 three in the third row and so on, like this:
10628
10629 @sp 1
10630 @c pebble diagram
10631 @ifnottex
10632 @smallexample
10633 @group
10634 *
10635 * *
10636 * * *
10637 * * * *
10638 @end group
10639 @end smallexample
10640 @end ifnottex
10641 @iftex
10642 @smallexample
10643 @group
10644 @bullet{}
10645 @bullet{} @bullet{}
10646 @bullet{} @bullet{} @bullet{}
10647 @bullet{} @bullet{} @bullet{} @bullet{}
10648 @end group
10649 @end smallexample
10650 @end iftex
10651 @sp 1
10652
10653 @noindent
10654 (About 2500 years ago, Pythagoras and others developed the beginnings of
10655 number theory by considering questions such as this.)
10656
10657 Suppose you want to know how many pebbles you will need to make a
10658 triangle with 7 rows?
10659
10660 Clearly, what you need to do is add up the numbers from 1 to 7. There
10661 are two ways to do this; start with the smallest number, one, and add up
10662 the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
10663 number and add the list going down: 7, 6, 5, 4 and so on. Because both
10664 mechanisms illustrate common ways of writing @code{while} loops, we will
10665 create two examples, one counting up and the other counting down. In
10666 this first example, we will start with 1 and add 2, 3, 4 and so on.
10667
10668 If you are just adding up a short list of numbers, the easiest way to do
10669 it is to add up all the numbers at once. However, if you do not know
10670 ahead of time how many numbers your list will have, or if you want to be
10671 prepared for a very long list, then you need to design your addition so
10672 that what you do is repeat a simple process many times instead of doing
10673 a more complex process once.
10674
10675 For example, instead of adding up all the pebbles all at once, what you
10676 can do is add the number of pebbles in the first row, 1, to the number
10677 in the second row, 2, and then add the total of those two rows to the
10678 third row, 3. Then you can add the number in the fourth row, 4, to the
10679 total of the first three rows; and so on.
10680
10681 The critical characteristic of the process is that each repetitive
10682 action is simple. In this case, at each step we add only two numbers,
10683 the number of pebbles in the row and the total already found. This
10684 process of adding two numbers is repeated again and again until the last
10685 row has been added to the total of all the preceding rows. In a more
10686 complex loop the repetitive action might not be so simple, but it will
10687 be simpler than doing everything all at once.
10688
10689 @node Inc Example parts
10690 @unnumberedsubsubsec The parts of the function definition
10691
10692 The preceding analysis gives us the bones of our function definition:
10693 first, we will need a variable that we can call @code{total} that will
10694 be the total number of pebbles. This will be the value returned by
10695 the function.
10696
10697 Second, we know that the function will require an argument: this
10698 argument will be the total number of rows in the triangle. It can be
10699 called @code{number-of-rows}.
10700
10701 Finally, we need a variable to use as a counter. We could call this
10702 variable @code{counter}, but a better name is @code{row-number}. That
10703 is because what the counter does in this function is count rows, and a
10704 program should be written to be as understandable as possible.
10705
10706 When the Lisp interpreter first starts evaluating the expressions in the
10707 function, the value of @code{total} should be set to zero, since we have
10708 not added anything to it. Then the function should add the number of
10709 pebbles in the first row to the total, and then add the number of
10710 pebbles in the second to the total, and then add the number of
10711 pebbles in the third row to the total, and so on, until there are no
10712 more rows left to add.
10713
10714 Both @code{total} and @code{row-number} are used only inside the
10715 function, so they can be declared as local variables with @code{let}
10716 and given initial values. Clearly, the initial value for @code{total}
10717 should be 0. The initial value of @code{row-number} should be 1,
10718 since we start with the first row. This means that the @code{let}
10719 statement will look like this:
10720
10721 @smallexample
10722 @group
10723 (let ((total 0)
10724 (row-number 1))
10725 @var{body}@dots{})
10726 @end group
10727 @end smallexample
10728
10729 After the internal variables are declared and bound to their initial
10730 values, we can begin the @code{while} loop. The expression that serves
10731 as the test should return a value of @code{t} for true so long as the
10732 @code{row-number} is less than or equal to the @code{number-of-rows}.
10733 (If the expression tests true only so long as the row number is less
10734 than the number of rows in the triangle, the last row will never be
10735 added to the total; hence the row number has to be either less than or
10736 equal to the number of rows.)
10737
10738 @need 1500
10739 @findex <= @r{(less than or equal)}
10740 Lisp provides the @code{<=} function that returns true if the value of
10741 its first argument is less than or equal to the value of its second
10742 argument and false otherwise. So the expression that the @code{while}
10743 will evaluate as its test should look like this:
10744
10745 @smallexample
10746 (<= row-number number-of-rows)
10747 @end smallexample
10748
10749 The total number of pebbles can be found by repeatedly adding the number
10750 of pebbles in a row to the total already found. Since the number of
10751 pebbles in the row is equal to the row number, the total can be found by
10752 adding the row number to the total. (Clearly, in a more complex
10753 situation, the number of pebbles in the row might be related to the row
10754 number in a more complicated way; if this were the case, the row number
10755 would be replaced by the appropriate expression.)
10756
10757 @smallexample
10758 (setq total (+ total row-number))
10759 @end smallexample
10760
10761 @noindent
10762 What this does is set the new value of @code{total} to be equal to the
10763 sum of adding the number of pebbles in the row to the previous total.
10764
10765 After setting the value of @code{total}, the conditions need to be
10766 established for the next repetition of the loop, if there is one. This
10767 is done by incrementing the value of the @code{row-number} variable,
10768 which serves as a counter. After the @code{row-number} variable has
10769 been incremented, the true-or-false-test at the beginning of the
10770 @code{while} loop tests whether its value is still less than or equal to
10771 the value of the @code{number-of-rows} and if it is, adds the new value
10772 of the @code{row-number} variable to the @code{total} of the previous
10773 repetition of the loop.
10774
10775 @need 1200
10776 The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10777 @code{row-number} variable can be incremented with this expression:
10778
10779 @smallexample
10780 (setq row-number (1+ row-number))
10781 @end smallexample
10782
10783 @node Inc Example altogether
10784 @unnumberedsubsubsec Putting the function definition together
10785
10786 We have created the parts for the function definition; now we need to
10787 put them together.
10788
10789 @need 800
10790 First, the contents of the @code{while} expression:
10791
10792 @smallexample
10793 @group
10794 (while (<= row-number number-of-rows) ; @r{true-or-false-test}
10795 (setq total (+ total row-number))
10796 (setq row-number (1+ row-number))) ; @r{incrementer}
10797 @end group
10798 @end smallexample
10799
10800 Along with the @code{let} expression varlist, this very nearly
10801 completes the body of the function definition. However, it requires
10802 one final element, the need for which is somewhat subtle.
10803
10804 The final touch is to place the variable @code{total} on a line by
10805 itself after the @code{while} expression. Otherwise, the value returned
10806 by the whole function is the value of the last expression that is
10807 evaluated in the body of the @code{let}, and this is the value
10808 returned by the @code{while}, which is always @code{nil}.
10809
10810 This may not be evident at first sight. It almost looks as if the
10811 incrementing expression is the last expression of the whole function.
10812 But that expression is part of the body of the @code{while}; it is the
10813 last element of the list that starts with the symbol @code{while}.
10814 Moreover, the whole of the @code{while} loop is a list within the body
10815 of the @code{let}.
10816
10817 @need 1250
10818 In outline, the function will look like this:
10819
10820 @smallexample
10821 @group
10822 (defun @var{name-of-function} (@var{argument-list})
10823 "@var{documentation}@dots{}"
10824 (let (@var{varlist})
10825 (while (@var{true-or-false-test})
10826 @var{body-of-while}@dots{} )
10827 @dots{} )) ; @r{Need final expression here.}
10828 @end group
10829 @end smallexample
10830
10831 The result of evaluating the @code{let} is what is going to be returned
10832 by the @code{defun} since the @code{let} is not embedded within any
10833 containing list, except for the @code{defun} as a whole. However, if
10834 the @code{while} is the last element of the @code{let} expression, the
10835 function will always return @code{nil}. This is not what we want!
10836 Instead, what we want is the value of the variable @code{total}. This
10837 is returned by simply placing the symbol as the last element of the list
10838 starting with @code{let}. It gets evaluated after the preceding
10839 elements of the list are evaluated, which means it gets evaluated after
10840 it has been assigned the correct value for the total.
10841
10842 It may be easier to see this by printing the list starting with
10843 @code{let} all on one line. This format makes it evident that the
10844 @var{varlist} and @code{while} expressions are the second and third
10845 elements of the list starting with @code{let}, and the @code{total} is
10846 the last element:
10847
10848 @smallexample
10849 @group
10850 (let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10851 @end group
10852 @end smallexample
10853
10854 @need 1200
10855 Putting everything together, the @code{triangle} function definition
10856 looks like this:
10857
10858 @smallexample
10859 @group
10860 (defun triangle (number-of-rows) ; @r{Version with}
10861 ; @r{ incrementing counter.}
10862 "Add up the number of pebbles in a triangle.
10863 The first row has one pebble, the second row two pebbles,
10864 the third row three pebbles, and so on.
10865 The argument is NUMBER-OF-ROWS."
10866 @end group
10867 @group
10868 (let ((total 0)
10869 (row-number 1))
10870 (while (<= row-number number-of-rows)
10871 (setq total (+ total row-number))
10872 (setq row-number (1+ row-number)))
10873 total))
10874 @end group
10875 @end smallexample
10876
10877 @need 1200
10878 After you have installed @code{triangle} by evaluating the function, you
10879 can try it out. Here are two examples:
10880
10881 @smallexample
10882 @group
10883 (triangle 4)
10884
10885 (triangle 7)
10886 @end group
10887 @end smallexample
10888
10889 @noindent
10890 The sum of the first four numbers is 10 and the sum of the first seven
10891 numbers is 28.
10892
10893 @node Decrementing Loop
10894 @subsection Loop with a Decrementing Counter
10895
10896 Another common way to write a @code{while} loop is to write the test
10897 so that it determines whether a counter is greater than zero. So long
10898 as the counter is greater than zero, the loop is repeated. But when
10899 the counter is equal to or less than zero, the loop is stopped. For
10900 this to work, the counter has to start out greater than zero and then
10901 be made smaller and smaller by a form that is evaluated
10902 repeatedly.
10903
10904 The test will be an expression such as @code{(> counter 0)} which
10905 returns @code{t} for true if the value of @code{counter} is greater
10906 than zero, and @code{nil} for false if the value of @code{counter} is
10907 equal to or less than zero. The expression that makes the number
10908 smaller and smaller can be a simple @code{setq} such as @code{(setq
10909 counter (1- counter))}, where @code{1-} is a built-in function in
10910 Emacs Lisp that subtracts 1 from its argument.
10911
10912 @need 1250
10913 The template for a decrementing @code{while} loop looks like this:
10914
10915 @smallexample
10916 @group
10917 (while (> counter 0) ; @r{true-or-false-test}
10918 @var{body}@dots{}
10919 (setq counter (1- counter))) ; @r{decrementer}
10920 @end group
10921 @end smallexample
10922
10923 @menu
10924 * Decrementing Example:: More pebbles on the beach.
10925 * Dec Example parts:: The parts of the function definition.
10926 * Dec Example altogether:: Putting the function definition together.
10927 @end menu
10928
10929 @node Decrementing Example
10930 @unnumberedsubsubsec Example with decrementing counter
10931
10932 To illustrate a loop with a decrementing counter, we will rewrite the
10933 @code{triangle} function so the counter decreases to zero.
10934
10935 This is the reverse of the earlier version of the function. In this
10936 case, to find out how many pebbles are needed to make a triangle with
10937 3 rows, add the number of pebbles in the third row, 3, to the number
10938 in the preceding row, 2, and then add the total of those two rows to
10939 the row that precedes them, which is 1.
10940
10941 Likewise, to find the number of pebbles in a triangle with 7 rows, add
10942 the number of pebbles in the seventh row, 7, to the number in the
10943 preceding row, which is 6, and then add the total of those two rows to
10944 the row that precedes them, which is 5, and so on. As in the previous
10945 example, each addition only involves adding two numbers, the total of
10946 the rows already added up and the number of pebbles in the row that is
10947 being added to the total. This process of adding two numbers is
10948 repeated again and again until there are no more pebbles to add.
10949
10950 We know how many pebbles to start with: the number of pebbles in the
10951 last row is equal to the number of rows. If the triangle has seven
10952 rows, the number of pebbles in the last row is 7. Likewise, we know how
10953 many pebbles are in the preceding row: it is one less than the number in
10954 the row.
10955
10956 @node Dec Example parts
10957 @unnumberedsubsubsec The parts of the function definition
10958
10959 We start with three variables: the total number of rows in the
10960 triangle; the number of pebbles in a row; and the total number of
10961 pebbles, which is what we want to calculate. These variables can be
10962 named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10963 @code{total}, respectively.
10964
10965 Both @code{total} and @code{number-of-pebbles-in-row} are used only
10966 inside the function and are declared with @code{let}. The initial
10967 value of @code{total} should, of course, be zero. However, the
10968 initial value of @code{number-of-pebbles-in-row} should be equal to
10969 the number of rows in the triangle, since the addition will start with
10970 the longest row.
10971
10972 @need 1250
10973 This means that the beginning of the @code{let} expression will look
10974 like this:
10975
10976 @smallexample
10977 @group
10978 (let ((total 0)
10979 (number-of-pebbles-in-row number-of-rows))
10980 @var{body}@dots{})
10981 @end group
10982 @end smallexample
10983
10984 The total number of pebbles can be found by repeatedly adding the number
10985 of pebbles in a row to the total already found, that is, by repeatedly
10986 evaluating the following expression:
10987
10988 @smallexample
10989 (setq total (+ total number-of-pebbles-in-row))
10990 @end smallexample
10991
10992 @noindent
10993 After the @code{number-of-pebbles-in-row} is added to the @code{total},
10994 the @code{number-of-pebbles-in-row} should be decremented by one, since
10995 the next time the loop repeats, the preceding row will be
10996 added to the total.
10997
10998 The number of pebbles in a preceding row is one less than the number of
10999 pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
11000 used to compute the number of pebbles in the preceding row. This can be
11001 done with the following expression:
11002
11003 @smallexample
11004 @group
11005 (setq number-of-pebbles-in-row
11006 (1- number-of-pebbles-in-row))
11007 @end group
11008 @end smallexample
11009
11010 Finally, we know that the @code{while} loop should stop making repeated
11011 additions when there are no pebbles in a row. So the test for
11012 the @code{while} loop is simply:
11013
11014 @smallexample
11015 (while (> number-of-pebbles-in-row 0)
11016 @end smallexample
11017
11018 @node Dec Example altogether
11019 @unnumberedsubsubsec Putting the function definition together
11020
11021 We can put these expressions together to create a function definition
11022 that works. However, on examination, we find that one of the local
11023 variables is unneeded!
11024
11025 @need 1250
11026 The function definition looks like this:
11027
11028 @smallexample
11029 @group
11030 ;;; @r{First subtractive version.}
11031 (defun triangle (number-of-rows)
11032 "Add up the number of pebbles in a triangle."
11033 (let ((total 0)
11034 (number-of-pebbles-in-row number-of-rows))
11035 (while (> number-of-pebbles-in-row 0)
11036 (setq total (+ total number-of-pebbles-in-row))
11037 (setq number-of-pebbles-in-row
11038 (1- number-of-pebbles-in-row)))
11039 total))
11040 @end group
11041 @end smallexample
11042
11043 As written, this function works.
11044
11045 However, we do not need @code{number-of-pebbles-in-row}.
11046
11047 @cindex Argument as local variable
11048 When the @code{triangle} function is evaluated, the symbol
11049 @code{number-of-rows} will be bound to a number, giving it an initial
11050 value. That number can be changed in the body of the function as if
11051 it were a local variable, without any fear that such a change will
11052 effect the value of the variable outside of the function. This is a
11053 very useful characteristic of Lisp; it means that the variable
11054 @code{number-of-rows} can be used anywhere in the function where
11055 @code{number-of-pebbles-in-row} is used.
11056
11057 @need 800
11058 Here is a second version of the function written a bit more cleanly:
11059
11060 @smallexample
11061 @group
11062 (defun triangle (number) ; @r{Second version.}
11063 "Return sum of numbers 1 through NUMBER inclusive."
11064 (let ((total 0))
11065 (while (> number 0)
11066 (setq total (+ total number))
11067 (setq number (1- number)))
11068 total))
11069 @end group
11070 @end smallexample
11071
11072 In brief, a properly written @code{while} loop will consist of three parts:
11073
11074 @enumerate
11075 @item
11076 A test that will return false after the loop has repeated itself the
11077 correct number of times.
11078
11079 @item
11080 An expression the evaluation of which will return the value desired
11081 after being repeatedly evaluated.
11082
11083 @item
11084 An expression to change the value passed to the true-or-false-test so
11085 that the test returns false after the loop has repeated itself the right
11086 number of times.
11087 @end enumerate
11088
11089 @node dolist dotimes
11090 @section Save your time: @code{dolist} and @code{dotimes}
11091
11092 In addition to @code{while}, both @code{dolist} and @code{dotimes}
11093 provide for looping. Sometimes these are quicker to write than the
11094 equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
11095 Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
11096
11097 @code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
11098 list': @code{dolist} automatically shortens the list each time it
11099 loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
11100 each shorter version of the list to the first of its arguments.
11101
11102 @code{dotimes} loops a specific number of times: you specify the number.
11103
11104 @menu
11105 * dolist::
11106 * dotimes::
11107 @end menu
11108
11109 @node dolist
11110 @unnumberedsubsec The @code{dolist} Macro
11111 @findex dolist
11112
11113 Suppose, for example, you want to reverse a list, so that
11114 ``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
11115
11116 @need 1250
11117 In practice, you would use the @code{reverse} function, like this:
11118
11119 @smallexample
11120 @group
11121 (setq animals '(gazelle giraffe lion tiger))
11122
11123 (reverse animals)
11124 @end group
11125 @end smallexample
11126
11127 @need 800
11128 @noindent
11129 Here is how you could reverse the list using a @code{while} loop:
11130
11131 @smallexample
11132 @group
11133 (setq animals '(gazelle giraffe lion tiger))
11134
11135 (defun reverse-list-with-while (list)
11136 "Using while, reverse the order of LIST."
11137 (let (value) ; make sure list starts empty
11138 (while list
11139 (setq value (cons (car list) value))
11140 (setq list (cdr list)))
11141 value))
11142
11143 (reverse-list-with-while animals)
11144 @end group
11145 @end smallexample
11146
11147 @need 800
11148 @noindent
11149 And here is how you could use the @code{dolist} macro:
11150
11151 @smallexample
11152 @group
11153 (setq animals '(gazelle giraffe lion tiger))
11154
11155 (defun reverse-list-with-dolist (list)
11156 "Using dolist, reverse the order of LIST."
11157 (let (value) ; make sure list starts empty
11158 (dolist (element list value)
11159 (setq value (cons element value)))))
11160
11161 (reverse-list-with-dolist animals)
11162 @end group
11163 @end smallexample
11164
11165 @need 1250
11166 @noindent
11167 In Info, you can place your cursor after the closing parenthesis of
11168 each expression and type @kbd{C-x C-e}; in each case, you should see
11169
11170 @smallexample
11171 (tiger lion giraffe gazelle)
11172 @end smallexample
11173
11174 @noindent
11175 in the echo area.
11176
11177 For this example, the existing @code{reverse} function is obviously best.
11178 The @code{while} loop is just like our first example (@pxref{Loop
11179 Example, , A @code{while} Loop and a List}). The @code{while} first
11180 checks whether the list has elements; if so, it constructs a new list
11181 by adding the first element of the list to the existing list (which in
11182 the first iteration of the loop is @code{nil}). Since the second
11183 element is prepended in front of the first element, and the third
11184 element is prepended in front of the second element, the list is reversed.
11185
11186 In the expression using a @code{while} loop,
11187 the @w{@code{(setq list (cdr list))}}
11188 expression shortens the list, so the @code{while} loop eventually
11189 stops. In addition, it provides the @code{cons} expression with a new
11190 first element by creating a new and shorter list at each repetition of
11191 the loop.
11192
11193 The @code{dolist} expression does very much the same as the
11194 @code{while} expression, except that the @code{dolist} macro does some
11195 of the work you have to do when writing a @code{while} expression.
11196
11197 Like a @code{while} loop, a @code{dolist} loops. What is different is
11198 that it automatically shortens the list each time it loops --- it
11199 `@sc{cdr}s down the list' on its own --- and it automatically binds
11200 the @sc{car} of each shorter version of the list to the first of its
11201 arguments.
11202
11203 In the example, the @sc{car} of each shorter version of the list is
11204 referred to using the symbol @samp{element}, the list itself is called
11205 @samp{list}, and the value returned is called @samp{value}. The
11206 remainder of the @code{dolist} expression is the body.
11207
11208 The @code{dolist} expression binds the @sc{car} of each shorter
11209 version of the list to @code{element} and then evaluates the body of
11210 the expression; and repeats the loop. The result is returned in
11211 @code{value}.
11212
11213 @node dotimes
11214 @unnumberedsubsec The @code{dotimes} Macro
11215 @findex dotimes
11216
11217 The @code{dotimes} macro is similar to @code{dolist}, except that it
11218 loops a specific number of times.
11219
11220 The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
11221 and so forth each time around the loop, and the value of the third
11222 argument is returned. You need to provide the value of the second
11223 argument, which is how many times the macro loops.
11224
11225 @need 1250
11226 For example, the following binds the numbers from 0 up to, but not
11227 including, the number 3 to the first argument, @var{number}, and then
11228 constructs a list of the three numbers. (The first number is 0, the
11229 second number is 1, and the third number is 2; this makes a total of
11230 three numbers in all, starting with zero as the first number.)
11231
11232 @smallexample
11233 @group
11234 (let (value) ; otherwise a value is a void variable
11235 (dotimes (number 3 value)
11236 (setq value (cons number value))))
11237
11238 @result{} (2 1 0)
11239 @end group
11240 @end smallexample
11241
11242 @noindent
11243 @code{dotimes} returns @code{value}, so the way to use
11244 @code{dotimes} is to operate on some expression @var{number} number of
11245 times and then return the result, either as a list or an atom.
11246
11247 @need 1250
11248 Here is an example of a @code{defun} that uses @code{dotimes} to add
11249 up the number of pebbles in a triangle.
11250
11251 @smallexample
11252 @group
11253 (defun triangle-using-dotimes (number-of-rows)
11254 "Using dotimes, add up the number of pebbles in a triangle."
11255 (let ((total 0)) ; otherwise a total is a void variable
11256 (dotimes (number number-of-rows total)
11257 (setq total (+ total (1+ number))))))
11258
11259 (triangle-using-dotimes 4)
11260 @end group
11261 @end smallexample
11262
11263 @node Recursion
11264 @section Recursion
11265 @cindex Recursion
11266
11267 A recursive function contains code that tells the Lisp interpreter to
11268 call a program that runs exactly like itself, but with slightly
11269 different arguments. The code runs exactly the same because it has
11270 the same name. However, even though the program has the same name, it
11271 is not the same entity. It is different. In the jargon, it is a
11272 different `instance'.
11273
11274 Eventually, if the program is written correctly, the `slightly
11275 different arguments' will become sufficiently different from the first
11276 arguments that the final instance will stop.
11277
11278 @menu
11279 * Building Robots:: Same model, different serial number ...
11280 * Recursive Definition Parts:: Walk until you stop ...
11281 * Recursion with list:: Using a list as the test whether to recurse.
11282 * Recursive triangle function::
11283 * Recursion with cond::
11284 * Recursive Patterns:: Often used templates.
11285 * No Deferment:: Don't store up work ...
11286 * No deferment solution::
11287 @end menu
11288
11289 @node Building Robots
11290 @subsection Building Robots: Extending the Metaphor
11291 @cindex Building robots
11292 @cindex Robots, building
11293
11294 It is sometimes helpful to think of a running program as a robot that
11295 does a job. In doing its job, a recursive function calls on a second
11296 robot to help it. The second robot is identical to the first in every
11297 way, except that the second robot helps the first and has been
11298 passed different arguments than the first.
11299
11300 In a recursive function, the second robot may call a third; and the
11301 third may call a fourth, and so on. Each of these is a different
11302 entity; but all are clones.
11303
11304 Since each robot has slightly different instructions---the arguments
11305 will differ from one robot to the next---the last robot should know
11306 when to stop.
11307
11308 Let's expand on the metaphor in which a computer program is a robot.
11309
11310 A function definition provides the blueprints for a robot. When you
11311 install a function definition, that is, when you evaluate a
11312 @code{defun} special form, you install the necessary equipment to
11313 build robots. It is as if you were in a factory, setting up an
11314 assembly line. Robots with the same name are built according to the
11315 same blueprints. So they have, as it were, the same `model number',
11316 but a different `serial number'.
11317
11318 We often say that a recursive function `calls itself'. What we mean
11319 is that the instructions in a recursive function cause the Lisp
11320 interpreter to run a different function that has the same name and
11321 does the same job as the first, but with different arguments.
11322
11323 It is important that the arguments differ from one instance to the
11324 next; otherwise, the process will never stop.
11325
11326 @node Recursive Definition Parts
11327 @subsection The Parts of a Recursive Definition
11328 @cindex Parts of a Recursive Definition
11329 @cindex Recursive Definition Parts
11330
11331 A recursive function typically contains a conditional expression which
11332 has three parts:
11333
11334 @enumerate
11335 @item
11336 A true-or-false-test that determines whether the function is called
11337 again, here called the @dfn{do-again-test}.
11338
11339 @item
11340 The name of the function. When this name is called, a new instance of
11341 the function---a new robot, as it were---is created and told what to do.
11342
11343 @item
11344 An expression that returns a different value each time the function is
11345 called, here called the @dfn{next-step-expression}. Consequently, the
11346 argument (or arguments) passed to the new instance of the function
11347 will be different from that passed to the previous instance. This
11348 causes the conditional expression, the @dfn{do-again-test}, to test
11349 false after the correct number of repetitions.
11350 @end enumerate
11351
11352 Recursive functions can be much simpler than any other kind of
11353 function. Indeed, when people first start to use them, they often look
11354 so mysteriously simple as to be incomprehensible. Like riding a
11355 bicycle, reading a recursive function definition takes a certain knack
11356 which is hard at first but then seems simple.
11357
11358 @need 1200
11359 There are several different common recursive patterns. A very simple
11360 pattern looks like this:
11361
11362 @smallexample
11363 @group
11364 (defun @var{name-of-recursive-function} (@var{argument-list})
11365 "@var{documentation}@dots{}"
11366 (if @var{do-again-test}
11367 @var{body}@dots{}
11368 (@var{name-of-recursive-function}
11369 @var{next-step-expression})))
11370 @end group
11371 @end smallexample
11372
11373 Each time a recursive function is evaluated, a new instance of it is
11374 created and told what to do. The arguments tell the instance what to do.
11375
11376 An argument is bound to the value of the next-step-expression. Each
11377 instance runs with a different value of the next-step-expression.
11378
11379 The value in the next-step-expression is used in the do-again-test.
11380
11381 The value returned by the next-step-expression is passed to the new
11382 instance of the function, which evaluates it (or some
11383 transmogrification of it) to determine whether to continue or stop.
11384 The next-step-expression is designed so that the do-again-test returns
11385 false when the function should no longer be repeated.
11386
11387 The do-again-test is sometimes called the @dfn{stop condition},
11388 since it stops the repetitions when it tests false.
11389
11390 @node Recursion with list
11391 @subsection Recursion with a List
11392
11393 The example of a @code{while} loop that printed the elements of a list
11394 of numbers can be written recursively. Here is the code, including
11395 an expression to set the value of the variable @code{animals} to a list.
11396
11397 If you are reading this in Info in Emacs, you can evaluate this
11398 expression directly in Info. Otherwise, you must copy the example
11399 to the @file{*scratch*} buffer and evaluate each expression there.
11400 Use @kbd{C-u C-x C-e} to evaluate the
11401 @code{(print-elements-recursively animals)} expression so that the
11402 results are printed in the buffer; otherwise the Lisp interpreter will
11403 try to squeeze the results into the one line of the echo area.
11404
11405 Also, place your cursor immediately after the last closing parenthesis
11406 of the @code{print-elements-recursively} function, before the comment.
11407 Otherwise, the Lisp interpreter will try to evaluate the comment.
11408
11409 @findex print-elements-recursively
11410 @smallexample
11411 @group
11412 (setq animals '(gazelle giraffe lion tiger))
11413
11414 (defun print-elements-recursively (list)
11415 "Print each element of LIST on a line of its own.
11416 Uses recursion."
11417 (when list ; @r{do-again-test}
11418 (print (car list)) ; @r{body}
11419 (print-elements-recursively ; @r{recursive call}
11420 (cdr list)))) ; @r{next-step-expression}
11421
11422 (print-elements-recursively animals)
11423 @end group
11424 @end smallexample
11425
11426 The @code{print-elements-recursively} function first tests whether
11427 there is any content in the list; if there is, the function prints the
11428 first element of the list, the @sc{car} of the list. Then the
11429 function `invokes itself', but gives itself as its argument, not the
11430 whole list, but the second and subsequent elements of the list, the
11431 @sc{cdr} of the list.
11432
11433 Put another way, if the list is not empty, the function invokes
11434 another instance of code that is similar to the initial code, but is a
11435 different thread of execution, with different arguments than the first
11436 instance.
11437
11438 Put in yet another way, if the list is not empty, the first robot
11439 assembles a second robot and tells it what to do; the second robot is
11440 a different individual from the first, but is the same model.
11441
11442 When the second evaluation occurs, the @code{when} expression is
11443 evaluated and if true, prints the first element of the list it
11444 receives as its argument (which is the second element of the original
11445 list). Then the function `calls itself' with the @sc{cdr} of the list
11446 it is invoked with, which (the second time around) is the @sc{cdr} of
11447 the @sc{cdr} of the original list.
11448
11449 Note that although we say that the function `calls itself', what we
11450 mean is that the Lisp interpreter assembles and instructs a new
11451 instance of the program. The new instance is a clone of the first,
11452 but is a separate individual.
11453
11454 Each time the function `invokes itself', it invokes itself on a
11455 shorter version of the original list. It creates a new instance that
11456 works on a shorter list.
11457
11458 Eventually, the function invokes itself on an empty list. It creates
11459 a new instance whose argument is @code{nil}. The conditional expression
11460 tests the value of @code{list}. Since the value of @code{list} is
11461 @code{nil}, the @code{when} expression tests false so the then-part is
11462 not evaluated. The function as a whole then returns @code{nil}.
11463
11464 @need 1200
11465 When you evaluate the expression @code{(print-elements-recursively
11466 animals)} in the @file{*scratch*} buffer, you see this result:
11467
11468 @smallexample
11469 @group
11470 gazelle
11471
11472 giraffe
11473
11474 lion
11475
11476 tiger
11477 nil
11478 @end group
11479 @end smallexample
11480
11481 @need 2000
11482 @node Recursive triangle function
11483 @subsection Recursion in Place of a Counter
11484 @findex triangle-recursively
11485
11486 @need 1200
11487 The @code{triangle} function described in a previous section can also
11488 be written recursively. It looks like this:
11489
11490 @smallexample
11491 @group
11492 (defun triangle-recursively (number)
11493 "Return the sum of the numbers 1 through NUMBER inclusive.
11494 Uses recursion."
11495 (if (= number 1) ; @r{do-again-test}
11496 1 ; @r{then-part}
11497 (+ number ; @r{else-part}
11498 (triangle-recursively ; @r{recursive call}
11499 (1- number))))) ; @r{next-step-expression}
11500
11501 (triangle-recursively 7)
11502 @end group
11503 @end smallexample
11504
11505 @noindent
11506 You can install this function by evaluating it and then try it by
11507 evaluating @code{(triangle-recursively 7)}. (Remember to put your
11508 cursor immediately after the last parenthesis of the function
11509 definition, before the comment.) The function evaluates to 28.
11510
11511 To understand how this function works, let's consider what happens in the
11512 various cases when the function is passed 1, 2, 3, or 4 as the value of
11513 its argument.
11514
11515 @menu
11516 * Recursive Example arg of 1 or 2::
11517 * Recursive Example arg of 3 or 4::
11518 @end menu
11519
11520 @ifnottex
11521 @node Recursive Example arg of 1 or 2
11522 @unnumberedsubsubsec An argument of 1 or 2
11523 @end ifnottex
11524
11525 First, what happens if the value of the argument is 1?
11526
11527 The function has an @code{if} expression after the documentation
11528 string. It tests whether the value of @code{number} is equal to 1; if
11529 so, Emacs evaluates the then-part of the @code{if} expression, which
11530 returns the number 1 as the value of the function. (A triangle with
11531 one row has one pebble in it.)
11532
11533 Suppose, however, that the value of the argument is 2. In this case,
11534 Emacs evaluates the else-part of the @code{if} expression.
11535
11536 @need 1200
11537 The else-part consists of an addition, the recursive call to
11538 @code{triangle-recursively} and a decrementing action; and it looks like
11539 this:
11540
11541 @smallexample
11542 (+ number (triangle-recursively (1- number)))
11543 @end smallexample
11544
11545 When Emacs evaluates this expression, the innermost expression is
11546 evaluated first; then the other parts in sequence. Here are the steps
11547 in detail:
11548
11549 @table @i
11550 @item Step 1 @w{ } Evaluate the innermost expression.
11551
11552 The innermost expression is @code{(1- number)} so Emacs decrements the
11553 value of @code{number} from 2 to 1.
11554
11555 @item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
11556
11557 The Lisp interpreter creates an individual instance of
11558 @code{triangle-recursively}. It does not matter that this function is
11559 contained within itself. Emacs passes the result Step 1 as the
11560 argument used by this instance of the @code{triangle-recursively}
11561 function
11562
11563 In this case, Emacs evaluates @code{triangle-recursively} with an
11564 argument of 1. This means that this evaluation of
11565 @code{triangle-recursively} returns 1.
11566
11567 @item Step 3 @w{ } Evaluate the value of @code{number}.
11568
11569 The variable @code{number} is the second element of the list that
11570 starts with @code{+}; its value is 2.
11571
11572 @item Step 4 @w{ } Evaluate the @code{+} expression.
11573
11574 The @code{+} expression receives two arguments, the first
11575 from the evaluation of @code{number} (Step 3) and the second from the
11576 evaluation of @code{triangle-recursively} (Step 2).
11577
11578 The result of the addition is the sum of 2 plus 1, and the number 3 is
11579 returned, which is correct. A triangle with two rows has three
11580 pebbles in it.
11581 @end table
11582
11583 @node Recursive Example arg of 3 or 4
11584 @unnumberedsubsubsec An argument of 3 or 4
11585
11586 Suppose that @code{triangle-recursively} is called with an argument of
11587 3.
11588
11589 @table @i
11590 @item Step 1 @w{ } Evaluate the do-again-test.
11591
11592 The @code{if} expression is evaluated first. This is the do-again
11593 test and returns false, so the else-part of the @code{if} expression
11594 is evaluated. (Note that in this example, the do-again-test causes
11595 the function to call itself when it tests false, not when it tests
11596 true.)
11597
11598 @item Step 2 @w{ } Evaluate the innermost expression of the else-part.
11599
11600 The innermost expression of the else-part is evaluated, which decrements
11601 3 to 2. This is the next-step-expression.
11602
11603 @item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
11604
11605 The number 2 is passed to the @code{triangle-recursively} function.
11606
11607 We already know what happens when Emacs evaluates @code{triangle-recursively} with
11608 an argument of 2. After going through the sequence of actions described
11609 earlier, it returns a value of 3. So that is what will happen here.
11610
11611 @item Step 4 @w{ } Evaluate the addition.
11612
11613 3 will be passed as an argument to the addition and will be added to the
11614 number with which the function was called, which is 3.
11615 @end table
11616
11617 @noindent
11618 The value returned by the function as a whole will be 6.
11619
11620 Now that we know what will happen when @code{triangle-recursively} is
11621 called with an argument of 3, it is evident what will happen if it is
11622 called with an argument of 4:
11623
11624 @quotation
11625 @need 800
11626 In the recursive call, the evaluation of
11627
11628 @smallexample
11629 (triangle-recursively (1- 4))
11630 @end smallexample
11631
11632 @need 800
11633 @noindent
11634 will return the value of evaluating
11635
11636 @smallexample
11637 (triangle-recursively 3)
11638 @end smallexample
11639
11640 @noindent
11641 which is 6 and this value will be added to 4 by the addition in the
11642 third line.
11643 @end quotation
11644
11645 @noindent
11646 The value returned by the function as a whole will be 10.
11647
11648 Each time @code{triangle-recursively} is evaluated, it evaluates a
11649 version of itself---a different instance of itself---with a smaller
11650 argument, until the argument is small enough so that it does not
11651 evaluate itself.
11652
11653 Note that this particular design for a recursive function
11654 requires that operations be deferred.
11655
11656 Before @code{(triangle-recursively 7)} can calculate its answer, it
11657 must call @code{(triangle-recursively 6)}; and before
11658 @code{(triangle-recursively 6)} can calculate its answer, it must call
11659 @code{(triangle-recursively 5)}; and so on. That is to say, the
11660 calculation that @code{(triangle-recursively 7)} makes must be
11661 deferred until @code{(triangle-recursively 6)} makes its calculation;
11662 and @code{(triangle-recursively 6)} must defer until
11663 @code{(triangle-recursively 5)} completes; and so on.
11664
11665 If each of these instances of @code{triangle-recursively} are thought
11666 of as different robots, the first robot must wait for the second to
11667 complete its job, which must wait until the third completes, and so
11668 on.
11669
11670 There is a way around this kind of waiting, which we will discuss in
11671 @ref{No Deferment, , Recursion without Deferments}.
11672
11673 @node Recursion with cond
11674 @subsection Recursion Example Using @code{cond}
11675 @findex cond
11676
11677 The version of @code{triangle-recursively} described earlier is written
11678 with the @code{if} special form. It can also be written using another
11679 special form called @code{cond}. The name of the special form
11680 @code{cond} is an abbreviation of the word @samp{conditional}.
11681
11682 Although the @code{cond} special form is not used as often in the
11683 Emacs Lisp sources as @code{if}, it is used often enough to justify
11684 explaining it.
11685
11686 @need 800
11687 The template for a @code{cond} expression looks like this:
11688
11689 @smallexample
11690 @group
11691 (cond
11692 @var{body}@dots{})
11693 @end group
11694 @end smallexample
11695
11696 @noindent
11697 where the @var{body} is a series of lists.
11698
11699 @need 800
11700 Written out more fully, the template looks like this:
11701
11702 @smallexample
11703 @group
11704 (cond
11705 (@var{first-true-or-false-test} @var{first-consequent})
11706 (@var{second-true-or-false-test} @var{second-consequent})
11707 (@var{third-true-or-false-test} @var{third-consequent})
11708 @dots{})
11709 @end group
11710 @end smallexample
11711
11712 When the Lisp interpreter evaluates the @code{cond} expression, it
11713 evaluates the first element (the @sc{car} or true-or-false-test) of
11714 the first expression in a series of expressions within the body of the
11715 @code{cond}.
11716
11717 If the true-or-false-test returns @code{nil} the rest of that
11718 expression, the consequent, is skipped and the true-or-false-test of the
11719 next expression is evaluated. When an expression is found whose
11720 true-or-false-test returns a value that is not @code{nil}, the
11721 consequent of that expression is evaluated. The consequent can be one
11722 or more expressions. If the consequent consists of more than one
11723 expression, the expressions are evaluated in sequence and the value of
11724 the last one is returned. If the expression does not have a consequent,
11725 the value of the true-or-false-test is returned.
11726
11727 If none of the true-or-false-tests test true, the @code{cond} expression
11728 returns @code{nil}.
11729
11730 @need 1250
11731 Written using @code{cond}, the @code{triangle} function looks like this:
11732
11733 @smallexample
11734 @group
11735 (defun triangle-using-cond (number)
11736 (cond ((<= number 0) 0)
11737 ((= number 1) 1)
11738 ((> number 1)
11739 (+ number (triangle-using-cond (1- number))))))
11740 @end group
11741 @end smallexample
11742
11743 @noindent
11744 In this example, the @code{cond} returns 0 if the number is less than or
11745 equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11746 number (triangle-using-cond (1- number)))} if the number is greater than
11747 1.
11748
11749 @node Recursive Patterns
11750 @subsection Recursive Patterns
11751 @cindex Recursive Patterns
11752
11753 Here are three common recursive patterns. Each involves a list.
11754 Recursion does not need to involve lists, but Lisp is designed for lists
11755 and this provides a sense of its primal capabilities.
11756
11757 @menu
11758 * Every::
11759 * Accumulate::
11760 * Keep::
11761 @end menu
11762
11763 @node Every
11764 @unnumberedsubsubsec Recursive Pattern: @emph{every}
11765 @cindex Every, type of recursive pattern
11766 @cindex Recursive pattern: every
11767
11768 In the @code{every} recursive pattern, an action is performed on every
11769 element of a list.
11770
11771 @need 1500
11772 The basic pattern is:
11773
11774 @itemize @bullet
11775 @item
11776 If a list be empty, return @code{nil}.
11777 @item
11778 Else, act on the beginning of the list (the @sc{car} of the list)
11779 @itemize @minus
11780 @item
11781 through a recursive call by the function on the rest (the
11782 @sc{cdr}) of the list,
11783 @item
11784 and, optionally, combine the acted-on element, using @code{cons},
11785 with the results of acting on the rest.
11786 @end itemize
11787 @end itemize
11788
11789 @need 1500
11790 Here is example:
11791
11792 @smallexample
11793 @group
11794 (defun square-each (numbers-list)
11795 "Square each of a NUMBERS LIST, recursively."
11796 (if (not numbers-list) ; do-again-test
11797 nil
11798 (cons
11799 (* (car numbers-list) (car numbers-list))
11800 (square-each (cdr numbers-list))))) ; next-step-expression
11801 @end group
11802
11803 @group
11804 (square-each '(1 2 3))
11805 @result{} (1 4 9)
11806 @end group
11807 @end smallexample
11808
11809 @need 1200
11810 @noindent
11811 If @code{numbers-list} is empty, do nothing. But if it has content,
11812 construct a list combining the square of the first number in the list
11813 with the result of the recursive call.
11814
11815 (The example follows the pattern exactly: @code{nil} is returned if
11816 the numbers' list is empty. In practice, you would write the
11817 conditional so it carries out the action when the numbers' list is not
11818 empty.)
11819
11820 The @code{print-elements-recursively} function (@pxref{Recursion with
11821 list, , Recursion with a List}) is another example of an @code{every}
11822 pattern, except in this case, rather than bring the results together
11823 using @code{cons}, we print each element of output.
11824
11825 @need 1250
11826 The @code{print-elements-recursively} function looks like this:
11827
11828 @smallexample
11829 @group
11830 (setq animals '(gazelle giraffe lion tiger))
11831 @end group
11832
11833 @group
11834 (defun print-elements-recursively (list)
11835 "Print each element of LIST on a line of its own.
11836 Uses recursion."
11837 (when list ; @r{do-again-test}
11838 (print (car list)) ; @r{body}
11839 (print-elements-recursively ; @r{recursive call}
11840 (cdr list)))) ; @r{next-step-expression}
11841
11842 (print-elements-recursively animals)
11843 @end group
11844 @end smallexample
11845
11846 @need 1500
11847 The pattern for @code{print-elements-recursively} is:
11848
11849 @itemize @bullet
11850 @item
11851 When the list is empty, do nothing.
11852 @item
11853 But when the list has at least one element,
11854 @itemize @minus
11855 @item
11856 act on the beginning of the list (the @sc{car} of the list),
11857 @item
11858 and make a recursive call on the rest (the @sc{cdr}) of the list.
11859 @end itemize
11860 @end itemize
11861
11862 @node Accumulate
11863 @unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11864 @cindex Accumulate, type of recursive pattern
11865 @cindex Recursive pattern: accumulate
11866
11867 Another recursive pattern is called the @code{accumulate} pattern. In
11868 the @code{accumulate} recursive pattern, an action is performed on
11869 every element of a list and the result of that action is accumulated
11870 with the results of performing the action on the other elements.
11871
11872 This is very like the `every' pattern using @code{cons}, except that
11873 @code{cons} is not used, but some other combiner.
11874
11875 @need 1500
11876 The pattern is:
11877
11878 @itemize @bullet
11879 @item
11880 If a list be empty, return zero or some other constant.
11881 @item
11882 Else, act on the beginning of the list (the @sc{car} of the list),
11883 @itemize @minus
11884 @item
11885 and combine that acted-on element, using @code{+} or
11886 some other combining function, with
11887 @item
11888 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11889 @end itemize
11890 @end itemize
11891
11892 @need 1500
11893 Here is an example:
11894
11895 @smallexample
11896 @group
11897 (defun add-elements (numbers-list)
11898 "Add the elements of NUMBERS-LIST together."
11899 (if (not numbers-list)
11900 0
11901 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11902 @end group
11903
11904 @group
11905 (add-elements '(1 2 3 4))
11906 @result{} 10
11907 @end group
11908 @end smallexample
11909
11910 @xref{Files List, , Making a List of Files}, for an example of the
11911 accumulate pattern.
11912
11913 @node Keep
11914 @unnumberedsubsubsec Recursive Pattern: @emph{keep}
11915 @cindex Keep, type of recursive pattern
11916 @cindex Recursive pattern: keep
11917
11918 A third recursive pattern is called the @code{keep} pattern.
11919 In the @code{keep} recursive pattern, each element of a list is tested;
11920 the element is acted on and the results are kept only if the element
11921 meets a criterion.
11922
11923 Again, this is very like the `every' pattern, except the element is
11924 skipped unless it meets a criterion.
11925
11926 @need 1500
11927 The pattern has three parts:
11928
11929 @itemize @bullet
11930 @item
11931 If a list be empty, return @code{nil}.
11932 @item
11933 Else, if the beginning of the list (the @sc{car} of the list) passes
11934 a test
11935 @itemize @minus
11936 @item
11937 act on that element and combine it, using @code{cons} with
11938 @item
11939 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11940 @end itemize
11941 @item
11942 Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11943 the test
11944 @itemize @minus
11945 @item
11946 skip on that element,
11947 @item
11948 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11949 @end itemize
11950 @end itemize
11951
11952 @need 1500
11953 Here is an example that uses @code{cond}:
11954
11955 @smallexample
11956 @group
11957 (defun keep-three-letter-words (word-list)
11958 "Keep three letter words in WORD-LIST."
11959 (cond
11960 ;; First do-again-test: stop-condition
11961 ((not word-list) nil)
11962
11963 ;; Second do-again-test: when to act
11964 ((eq 3 (length (symbol-name (car word-list))))
11965 ;; combine acted-on element with recursive call on shorter list
11966 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11967
11968 ;; Third do-again-test: when to skip element;
11969 ;; recursively call shorter list with next-step expression
11970 (t (keep-three-letter-words (cdr word-list)))))
11971 @end group
11972
11973 @group
11974 (keep-three-letter-words '(one two three four five six))
11975 @result{} (one two six)
11976 @end group
11977 @end smallexample
11978
11979 It goes without saying that you need not use @code{nil} as the test for
11980 when to stop; and you can, of course, combine these patterns.
11981
11982 @node No Deferment
11983 @subsection Recursion without Deferments
11984 @cindex Deferment in recursion
11985 @cindex Recursion without Deferments
11986
11987 Let's consider again what happens with the @code{triangle-recursively}
11988 function. We will find that the intermediate calculations are
11989 deferred until all can be done.
11990
11991 @need 800
11992 Here is the function definition:
11993
11994 @smallexample
11995 @group
11996 (defun triangle-recursively (number)
11997 "Return the sum of the numbers 1 through NUMBER inclusive.
11998 Uses recursion."
11999 (if (= number 1) ; @r{do-again-test}
12000 1 ; @r{then-part}
12001 (+ number ; @r{else-part}
12002 (triangle-recursively ; @r{recursive call}
12003 (1- number))))) ; @r{next-step-expression}
12004 @end group
12005 @end smallexample
12006
12007 What happens when we call this function with a argument of 7?
12008
12009 The first instance of the @code{triangle-recursively} function adds
12010 the number 7 to the value returned by a second instance of
12011 @code{triangle-recursively}, an instance that has been passed an
12012 argument of 6. That is to say, the first calculation is:
12013
12014 @smallexample
12015 (+ 7 (triangle-recursively 6))
12016 @end smallexample
12017
12018 @noindent
12019 The first instance of @code{triangle-recursively}---you may want to
12020 think of it as a little robot---cannot complete its job. It must hand
12021 off the calculation for @code{(triangle-recursively 6)} to a second
12022 instance of the program, to a second robot. This second individual is
12023 completely different from the first one; it is, in the jargon, a
12024 `different instantiation'. Or, put another way, it is a different
12025 robot. It is the same model as the first; it calculates triangle
12026 numbers recursively; but it has a different serial number.
12027
12028 And what does @code{(triangle-recursively 6)} return? It returns the
12029 number 6 added to the value returned by evaluating
12030 @code{triangle-recursively} with an argument of 5. Using the robot
12031 metaphor, it asks yet another robot to help it.
12032
12033 @need 800
12034 Now the total is:
12035
12036 @smallexample
12037 (+ 7 6 (triangle-recursively 5))
12038 @end smallexample
12039
12040 @need 800
12041 And what happens next?
12042
12043 @smallexample
12044 (+ 7 6 5 (triangle-recursively 4))
12045 @end smallexample
12046
12047 Each time @code{triangle-recursively} is called, except for the last
12048 time, it creates another instance of the program---another robot---and
12049 asks it to make a calculation.
12050
12051 @need 800
12052 Eventually, the full addition is set up and performed:
12053
12054 @smallexample
12055 (+ 7 6 5 4 3 2 1)
12056 @end smallexample
12057
12058 This design for the function defers the calculation of the first step
12059 until the second can be done, and defers that until the third can be
12060 done, and so on. Each deferment means the computer must remember what
12061 is being waited on. This is not a problem when there are only a few
12062 steps, as in this example. But it can be a problem when there are
12063 more steps.
12064
12065 @node No deferment solution
12066 @subsection No Deferment Solution
12067 @cindex No deferment solution
12068 @cindex Defermentless solution
12069 @cindex Solution without deferment
12070
12071 The solution to the problem of deferred operations is to write in a
12072 manner that does not defer operations@footnote{The phrase @dfn{tail
12073 recursive} is used to describe such a process, one that uses
12074 `constant space'.}. This requires
12075 writing to a different pattern, often one that involves writing two
12076 function definitions, an `initialization' function and a `helper'
12077 function.
12078
12079 The `initialization' function sets up the job; the `helper' function
12080 does the work.
12081
12082 @need 1200
12083 Here are the two function definitions for adding up numbers. They are
12084 so simple, I find them hard to understand.
12085
12086 @smallexample
12087 @group
12088 (defun triangle-initialization (number)
12089 "Return the sum of the numbers 1 through NUMBER inclusive.
12090 This is the `initialization' component of a two function
12091 duo that uses recursion."
12092 (triangle-recursive-helper 0 0 number))
12093 @end group
12094 @end smallexample
12095
12096 @smallexample
12097 @group
12098 (defun triangle-recursive-helper (sum counter number)
12099 "Return SUM, using COUNTER, through NUMBER inclusive.
12100 This is the `helper' component of a two function duo
12101 that uses recursion."
12102 (if (> counter number)
12103 sum
12104 (triangle-recursive-helper (+ sum counter) ; @r{sum}
12105 (1+ counter) ; @r{counter}
12106 number))) ; @r{number}
12107 @end group
12108 @end smallexample
12109
12110 @need 1250
12111 Install both function definitions by evaluating them, then call
12112 @code{triangle-initialization} with 2 rows:
12113
12114 @smallexample
12115 @group
12116 (triangle-initialization 2)
12117 @result{} 3
12118 @end group
12119 @end smallexample
12120
12121 The `initialization' function calls the first instance of the `helper'
12122 function with three arguments: zero, zero, and a number which is the
12123 number of rows in the triangle.
12124
12125 The first two arguments passed to the `helper' function are
12126 initialization values. These values are changed when
12127 @code{triangle-recursive-helper} invokes new instances.@footnote{The
12128 jargon is mildly confusing: @code{triangle-recursive-helper} uses a
12129 process that is iterative in a procedure that is recursive. The
12130 process is called iterative because the computer need only record the
12131 three values, @code{sum}, @code{counter}, and @code{number}; the
12132 procedure is recursive because the function `calls itself'. On the
12133 other hand, both the process and the procedure used by
12134 @code{triangle-recursively} are called recursive. The word
12135 `recursive' has different meanings in the two contexts.}
12136
12137 Let's see what happens when we have a triangle that has one row. (This
12138 triangle will have one pebble in it!)
12139
12140 @need 1200
12141 @code{triangle-initialization} will call its helper with
12142 the arguments @w{@code{0 0 1}}. That function will run the conditional
12143 test whether @code{(> counter number)}:
12144
12145 @smallexample
12146 (> 0 1)
12147 @end smallexample
12148
12149 @need 1200
12150 @noindent
12151 and find that the result is false, so it will invoke
12152 the else-part of the @code{if} clause:
12153
12154 @smallexample
12155 @group
12156 (triangle-recursive-helper
12157 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12158 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12159 number) ; @r{number stays the same}
12160 @end group
12161 @end smallexample
12162
12163 @need 800
12164 @noindent
12165 which will first compute:
12166
12167 @smallexample
12168 @group
12169 (triangle-recursive-helper (+ 0 0) ; @r{sum}
12170 (1+ 0) ; @r{counter}
12171 1) ; @r{number}
12172 @exdent which is:
12173
12174 (triangle-recursive-helper 0 1 1)
12175 @end group
12176 @end smallexample
12177
12178 Again, @code{(> counter number)} will be false, so again, the Lisp
12179 interpreter will evaluate @code{triangle-recursive-helper}, creating a
12180 new instance with new arguments.
12181
12182 @need 800
12183 This new instance will be;
12184
12185 @smallexample
12186 @group
12187 (triangle-recursive-helper
12188 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12189 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12190 number) ; @r{number stays the same}
12191
12192 @exdent which is:
12193
12194 (triangle-recursive-helper 1 2 1)
12195 @end group
12196 @end smallexample
12197
12198 In this case, the @code{(> counter number)} test will be true! So the
12199 instance will return the value of the sum, which will be 1, as
12200 expected.
12201
12202 Now, let's pass @code{triangle-initialization} an argument
12203 of 2, to find out how many pebbles there are in a triangle with two rows.
12204
12205 That function calls @code{(triangle-recursive-helper 0 0 2)}.
12206
12207 @need 800
12208 In stages, the instances called will be:
12209
12210 @smallexample
12211 @group
12212 @r{sum counter number}
12213 (triangle-recursive-helper 0 1 2)
12214
12215 (triangle-recursive-helper 1 2 2)
12216
12217 (triangle-recursive-helper 3 3 2)
12218 @end group
12219 @end smallexample
12220
12221 When the last instance is called, the @code{(> counter number)} test
12222 will be true, so the instance will return the value of @code{sum},
12223 which will be 3.
12224
12225 This kind of pattern helps when you are writing functions that can use
12226 many resources in a computer.
12227
12228 @need 1500
12229 @node Looping exercise
12230 @section Looping Exercise
12231
12232 @itemize @bullet
12233 @item
12234 Write a function similar to @code{triangle} in which each row has a
12235 value which is the square of the row number. Use a @code{while} loop.
12236
12237 @item
12238 Write a function similar to @code{triangle} that multiplies instead of
12239 adds the values.
12240
12241 @item
12242 Rewrite these two functions recursively. Rewrite these functions
12243 using @code{cond}.
12244
12245 @c comma in printed title causes problem in Info cross reference
12246 @item
12247 Write a function for Texinfo mode that creates an index entry at the
12248 beginning of a paragraph for every @samp{@@dfn} within the paragraph.
12249 (In a Texinfo file, @samp{@@dfn} marks a definition. This book is
12250 written in Texinfo.)
12251
12252 Many of the functions you will need are described in two of the
12253 previous chapters, @ref{Cutting & Storing Text, , Cutting and Storing
12254 Text}, and @ref{Yanking, , Yanking Text Back}. If you use
12255 @code{forward-paragraph} to put the index entry at the beginning of
12256 the paragraph, you will have to use @w{@kbd{C-h f}}
12257 (@code{describe-function}) to find out how to make the command go
12258 backwards.
12259
12260 For more information, see
12261 @ifinfo
12262 @ref{Indicating, , Indicating Definitions, texinfo}.
12263 @end ifinfo
12264 @ifhtml
12265 @ref{Indicating, , Indicating, texinfo, Texinfo Manual}, which goes to
12266 a Texinfo manual in the current directory. Or, if you are on the
12267 Internet, see
12268 @uref{http://www.gnu.org/software/texinfo/manual/texinfo/}
12269 @end ifhtml
12270 @iftex
12271 ``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
12272 Documentation Format}.
12273 @end iftex
12274 @end itemize
12275
12276 @node Regexp Search
12277 @chapter Regular Expression Searches
12278 @cindex Searches, illustrating
12279 @cindex Regular expression searches
12280 @cindex Patterns, searching for
12281 @cindex Motion by sentence and paragraph
12282 @cindex Sentences, movement by
12283 @cindex Paragraphs, movement by
12284
12285 Regular expression searches are used extensively in GNU Emacs. The
12286 two functions, @code{forward-sentence} and @code{forward-paragraph},
12287 illustrate these searches well. They use regular expressions to find
12288 where to move point. The phrase `regular expression' is often written
12289 as `regexp'.
12290
12291 Regular expression searches are described in @ref{Regexp Search, ,
12292 Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
12293 @ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
12294 Manual}. In writing this chapter, I am presuming that you have at
12295 least a mild acquaintance with them. The major point to remember is
12296 that regular expressions permit you to search for patterns as well as
12297 for literal strings of characters. For example, the code in
12298 @code{forward-sentence} searches for the pattern of possible
12299 characters that could mark the end of a sentence, and moves point to
12300 that spot.
12301
12302 Before looking at the code for the @code{forward-sentence} function, it
12303 is worth considering what the pattern that marks the end of a sentence
12304 must be. The pattern is discussed in the next section; following that
12305 is a description of the regular expression search function,
12306 @code{re-search-forward}. The @code{forward-sentence} function
12307 is described in the section following. Finally, the
12308 @code{forward-paragraph} function is described in the last section of
12309 this chapter. @code{forward-paragraph} is a complex function that
12310 introduces several new features.
12311
12312 @menu
12313 * sentence-end:: The regular expression for @code{sentence-end}.
12314 * re-search-forward:: Very similar to @code{search-forward}.
12315 * forward-sentence:: A straightforward example of regexp search.
12316 * forward-paragraph:: A somewhat complex example.
12317 * etags:: How to create your own @file{TAGS} table.
12318 * Regexp Review::
12319 * re-search Exercises::
12320 @end menu
12321
12322 @node sentence-end
12323 @section The Regular Expression for @code{sentence-end}
12324 @findex sentence-end
12325
12326 The symbol @code{sentence-end} is bound to the pattern that marks the
12327 end of a sentence. What should this regular expression be?
12328
12329 Clearly, a sentence may be ended by a period, a question mark, or an
12330 exclamation mark. Indeed, in English, only clauses that end with one
12331 of those three characters should be considered the end of a sentence.
12332 This means that the pattern should include the character set:
12333
12334 @smallexample
12335 [.?!]
12336 @end smallexample
12337
12338 However, we do not want @code{forward-sentence} merely to jump to a
12339 period, a question mark, or an exclamation mark, because such a character
12340 might be used in the middle of a sentence. A period, for example, is
12341 used after abbreviations. So other information is needed.
12342
12343 According to convention, you type two spaces after every sentence, but
12344 only one space after a period, a question mark, or an exclamation mark in
12345 the body of a sentence. So a period, a question mark, or an exclamation
12346 mark followed by two spaces is a good indicator of an end of sentence.
12347 However, in a file, the two spaces may instead be a tab or the end of a
12348 line. This means that the regular expression should include these three
12349 items as alternatives.
12350
12351 @need 800
12352 This group of alternatives will look like this:
12353
12354 @smallexample
12355 @group
12356 \\($\\| \\| \\)
12357 ^ ^^
12358 TAB SPC
12359 @end group
12360 @end smallexample
12361
12362 @noindent
12363 Here, @samp{$} indicates the end of the line, and I have pointed out
12364 where the tab and two spaces are inserted in the expression. Both are
12365 inserted by putting the actual characters into the expression.
12366
12367 Two backslashes, @samp{\\}, are required before the parentheses and
12368 vertical bars: the first backslash quotes the following backslash in
12369 Emacs; and the second indicates that the following character, the
12370 parenthesis or the vertical bar, is special.
12371
12372 @need 1000
12373 Also, a sentence may be followed by one or more carriage returns, like
12374 this:
12375
12376 @smallexample
12377 @group
12378 [
12379 ]*
12380 @end group
12381 @end smallexample
12382
12383 @noindent
12384 Like tabs and spaces, a carriage return is inserted into a regular
12385 expression by inserting it literally. The asterisk indicates that the
12386 @key{RET} is repeated zero or more times.
12387
12388 But a sentence end does not consist only of a period, a question mark or
12389 an exclamation mark followed by appropriate space: a closing quotation
12390 mark or a closing brace of some kind may precede the space. Indeed more
12391 than one such mark or brace may precede the space. These require a
12392 expression that looks like this:
12393
12394 @smallexample
12395 []\"')@}]*
12396 @end smallexample
12397
12398 In this expression, the first @samp{]} is the first character in the
12399 expression; the second character is @samp{"}, which is preceded by a
12400 @samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
12401 three characters are @samp{'}, @samp{)}, and @samp{@}}.
12402
12403 All this suggests what the regular expression pattern for matching the
12404 end of a sentence should be; and, indeed, if we evaluate
12405 @code{sentence-end} we find that it returns the following value:
12406
12407 @smallexample
12408 @group
12409 sentence-end
12410 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
12411 ]*"
12412 @end group
12413 @end smallexample
12414
12415 @noindent
12416 (Well, not in GNU Emacs 22; that is because of an effort to make the
12417 process simpler and to handle more glyphs and languages. When the
12418 value of @code{sentence-end} is @code{nil}, then use the value defined
12419 by the function @code{sentence-end}. (Here is a use of the difference
12420 between a value and a function in Emacs Lisp.) The function returns a
12421 value constructed from the variables @code{sentence-end-base},
12422 @code{sentence-end-double-space}, @code{sentence-end-without-period},
12423 and @code{sentence-end-without-space}. The critical variable is
12424 @code{sentence-end-base}; its global value is similar to the one
12425 described above but it also contains two additional quotation marks.
12426 These have differing degrees of curliness. The
12427 @code{sentence-end-without-period} variable, when true, tells Emacs
12428 that a sentence may end without a period, such as text in Thai.)
12429
12430 @ignore
12431 @noindent
12432 (Note that here the @key{TAB}, two spaces, and @key{RET} are shown
12433 literally in the pattern.)
12434
12435 This regular expression can be deciphered as follows:
12436
12437 @table @code
12438 @item [.?!]
12439 The first part of the pattern is the three characters, a period, a question
12440 mark and an exclamation mark, within square brackets. The pattern must
12441 begin with one or other of these characters.
12442
12443 @item []\"')@}]*
12444 The second part of the pattern is the group of closing braces and
12445 quotation marks, which can appear zero or more times. These may follow
12446 the period, question mark or exclamation mark. In a regular expression,
12447 the backslash, @samp{\}, followed by the double quotation mark,
12448 @samp{"}, indicates the class of string-quote characters. Usually, the
12449 double quotation mark is the only character in this class. The
12450 asterisk, @samp{*}, indicates that the items in the previous group (the
12451 group surrounded by square brackets, @samp{[]}) may be repeated zero or
12452 more times.
12453
12454 @item \\($\\| \\| \\)
12455 The third part of the pattern is one or other of: either the end of a
12456 line, or two blank spaces, or a tab. The double back-slashes are used
12457 to prevent Emacs from reading the parentheses and vertical bars as part
12458 of the search pattern; the parentheses are used to mark the group and
12459 the vertical bars are used to indicated that the patterns to either side
12460 of them are alternatives. The dollar sign is used to indicate the end
12461 of a line and both the two spaces and the tab are each inserted as is to
12462 indicate what they are.
12463
12464 @item [@key{RET}]*
12465 Finally, the last part of the pattern indicates that the end of the line
12466 or the whitespace following the period, question mark or exclamation
12467 mark may, but need not, be followed by one or more carriage returns. In
12468 the pattern, the carriage return is inserted as an actual carriage
12469 return between square brackets but here it is shown as @key{RET}.
12470 @end table
12471 @end ignore
12472
12473 @node re-search-forward
12474 @section The @code{re-search-forward} Function
12475 @findex re-search-forward
12476
12477 The @code{re-search-forward} function is very like the
12478 @code{search-forward} function. (@xref{search-forward, , The
12479 @code{search-forward} Function}.)
12480
12481 @code{re-search-forward} searches for a regular expression. If the
12482 search is successful, it leaves point immediately after the last
12483 character in the target. If the search is backwards, it leaves point
12484 just before the first character in the target. You may tell
12485 @code{re-search-forward} to return @code{t} for true. (Moving point
12486 is therefore a `side effect'.)
12487
12488 Like @code{search-forward}, the @code{re-search-forward} function takes
12489 four arguments:
12490
12491 @enumerate
12492 @item
12493 The first argument is the regular expression that the function searches
12494 for. The regular expression will be a string between quotation marks.
12495
12496 @item
12497 The optional second argument limits how far the function will search; it is a
12498 bound, which is specified as a position in the buffer.
12499
12500 @item
12501 The optional third argument specifies how the function responds to
12502 failure: @code{nil} as the third argument causes the function to
12503 signal an error (and print a message) when the search fails; any other
12504 value causes it to return @code{nil} if the search fails and @code{t}
12505 if the search succeeds.
12506
12507 @item
12508 The optional fourth argument is the repeat count. A negative repeat
12509 count causes @code{re-search-forward} to search backwards.
12510 @end enumerate
12511
12512 @need 800
12513 The template for @code{re-search-forward} looks like this:
12514
12515 @smallexample
12516 @group
12517 (re-search-forward "@var{regular-expression}"
12518 @var{limit-of-search}
12519 @var{what-to-do-if-search-fails}
12520 @var{repeat-count})
12521 @end group
12522 @end smallexample
12523
12524 The second, third, and fourth arguments are optional. However, if you
12525 want to pass a value to either or both of the last two arguments, you
12526 must also pass a value to all the preceding arguments. Otherwise, the
12527 Lisp interpreter will mistake which argument you are passing the value
12528 to.
12529
12530 @need 1200
12531 In the @code{forward-sentence} function, the regular expression will be
12532 the value of the variable @code{sentence-end}. In simple form, that is:
12533
12534 @smallexample
12535 @group
12536 "[.?!][]\"')@}]*\\($\\| \\| \\)[
12537 ]*"
12538 @end group
12539 @end smallexample
12540
12541 @noindent
12542 The limit of the search will be the end of the paragraph (since a
12543 sentence cannot go beyond a paragraph). If the search fails, the
12544 function will return @code{nil}; and the repeat count will be provided
12545 by the argument to the @code{forward-sentence} function.
12546
12547 @node forward-sentence
12548 @section @code{forward-sentence}
12549 @findex forward-sentence
12550
12551 The command to move the cursor forward a sentence is a straightforward
12552 illustration of how to use regular expression searches in Emacs Lisp.
12553 Indeed, the function looks longer and more complicated than it is; this
12554 is because the function is designed to go backwards as well as forwards;
12555 and, optionally, over more than one sentence. The function is usually
12556 bound to the key command @kbd{M-e}.
12557
12558 @menu
12559 * Complete forward-sentence::
12560 * fwd-sentence while loops:: Two @code{while} loops.
12561 * fwd-sentence re-search:: A regular expression search.
12562 @end menu
12563
12564 @ifnottex
12565 @node Complete forward-sentence
12566 @unnumberedsubsec Complete @code{forward-sentence} function definition
12567 @end ifnottex
12568
12569 @need 1250
12570 Here is the code for @code{forward-sentence}:
12571
12572 @c in GNU Emacs 22
12573 @smallexample
12574 @group
12575 (defun forward-sentence (&optional arg)
12576 "Move forward to next `sentence-end'. With argument, repeat.
12577 With negative argument, move backward repeatedly to `sentence-beginning'.
12578
12579 The variable `sentence-end' is a regular expression that matches ends of
12580 sentences. Also, every paragraph boundary terminates sentences as well."
12581 @end group
12582 @group
12583 (interactive "p")
12584 (or arg (setq arg 1))
12585 (let ((opoint (point))
12586 (sentence-end (sentence-end)))
12587 (while (< arg 0)
12588 (let ((pos (point))
12589 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12590 (if (and (re-search-backward sentence-end par-beg t)
12591 (or (< (match-end 0) pos)
12592 (re-search-backward sentence-end par-beg t)))
12593 (goto-char (match-end 0))
12594 (goto-char par-beg)))
12595 (setq arg (1+ arg)))
12596 @end group
12597 @group
12598 (while (> arg 0)
12599 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12600 (if (re-search-forward sentence-end par-end t)
12601 (skip-chars-backward " \t\n")
12602 (goto-char par-end)))
12603 (setq arg (1- arg)))
12604 (constrain-to-field nil opoint t)))
12605 @end group
12606 @end smallexample
12607
12608 @ignore
12609 GNU Emacs 21
12610 @smallexample
12611 @group
12612 (defun forward-sentence (&optional arg)
12613 "Move forward to next sentence-end. With argument, repeat.
12614 With negative argument, move backward repeatedly to sentence-beginning.
12615 Sentence ends are identified by the value of sentence-end
12616 treated as a regular expression. Also, every paragraph boundary
12617 terminates sentences as well."
12618 @end group
12619 @group
12620 (interactive "p")
12621 (or arg (setq arg 1))
12622 (while (< arg 0)
12623 (let ((par-beg
12624 (save-excursion (start-of-paragraph-text) (point))))
12625 (if (re-search-backward
12626 (concat sentence-end "[^ \t\n]") par-beg t)
12627 (goto-char (1- (match-end 0)))
12628 (goto-char par-beg)))
12629 (setq arg (1+ arg)))
12630 (while (> arg 0)
12631 (let ((par-end
12632 (save-excursion (end-of-paragraph-text) (point))))
12633 (if (re-search-forward sentence-end par-end t)
12634 (skip-chars-backward " \t\n")
12635 (goto-char par-end)))
12636 (setq arg (1- arg))))
12637 @end group
12638 @end smallexample
12639 @end ignore
12640
12641 The function looks long at first sight and it is best to look at its
12642 skeleton first, and then its muscle. The way to see the skeleton is to
12643 look at the expressions that start in the left-most columns:
12644
12645 @smallexample
12646 @group
12647 (defun forward-sentence (&optional arg)
12648 "@var{documentation}@dots{}"
12649 (interactive "p")
12650 (or arg (setq arg 1))
12651 (let ((opoint (point)) (sentence-end (sentence-end)))
12652 (while (< arg 0)
12653 (let ((pos (point))
12654 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12655 @var{rest-of-body-of-while-loop-when-going-backwards}
12656 (while (> arg 0)
12657 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12658 @var{rest-of-body-of-while-loop-when-going-forwards}
12659 @var{handle-forms-and-equivalent}
12660 @end group
12661 @end smallexample
12662
12663 This looks much simpler! The function definition consists of
12664 documentation, an @code{interactive} expression, an @code{or}
12665 expression, a @code{let} expression, and @code{while} loops.
12666
12667 Let's look at each of these parts in turn.
12668
12669 We note that the documentation is thorough and understandable.
12670
12671 The function has an @code{interactive "p"} declaration. This means
12672 that the processed prefix argument, if any, is passed to the
12673 function as its argument. (This will be a number.) If the function
12674 is not passed an argument (it is optional) then the argument
12675 @code{arg} will be bound to 1.
12676
12677 When @code{forward-sentence} is called non-interactively without an
12678 argument, @code{arg} is bound to @code{nil}. The @code{or} expression
12679 handles this. What it does is either leave the value of @code{arg} as
12680 it is, but only if @code{arg} is bound to a value; or it sets the
12681 value of @code{arg} to 1, in the case when @code{arg} is bound to
12682 @code{nil}.
12683
12684 Next is a @code{let}. That specifies the values of two local
12685 variables, @code{point} and @code{sentence-end}. The local value of
12686 point, from before the search, is used in the
12687 @code{constrain-to-field} function which handles forms and
12688 equivalents. The @code{sentence-end} variable is set by the
12689 @code{sentence-end} function.
12690
12691 @node fwd-sentence while loops
12692 @unnumberedsubsec The @code{while} loops
12693
12694 Two @code{while} loops follow. The first @code{while} has a
12695 true-or-false-test that tests true if the prefix argument for
12696 @code{forward-sentence} is a negative number. This is for going
12697 backwards. The body of this loop is similar to the body of the second
12698 @code{while} clause, but it is not exactly the same. We will skip
12699 this @code{while} loop and concentrate on the second @code{while}
12700 loop.
12701
12702 @need 1500
12703 The second @code{while} loop is for moving point forward. Its skeleton
12704 looks like this:
12705
12706 @smallexample
12707 @group
12708 (while (> arg 0) ; @r{true-or-false-test}
12709 (let @var{varlist}
12710 (if (@var{true-or-false-test})
12711 @var{then-part}
12712 @var{else-part}
12713 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
12714 @end group
12715 @end smallexample
12716
12717 The @code{while} loop is of the decrementing kind.
12718 (@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
12719 has a true-or-false-test that tests true so long as the counter (in
12720 this case, the variable @code{arg}) is greater than zero; and it has a
12721 decrementer that subtracts 1 from the value of the counter every time
12722 the loop repeats.
12723
12724 If no prefix argument is given to @code{forward-sentence}, which is
12725 the most common way the command is used, this @code{while} loop will
12726 run once, since the value of @code{arg} will be 1.
12727
12728 The body of the @code{while} loop consists of a @code{let} expression,
12729 which creates and binds a local variable, and has, as its body, an
12730 @code{if} expression.
12731
12732 @need 1250
12733 The body of the @code{while} loop looks like this:
12734
12735 @smallexample
12736 @group
12737 (let ((par-end
12738 (save-excursion (end-of-paragraph-text) (point))))
12739 (if (re-search-forward sentence-end par-end t)
12740 (skip-chars-backward " \t\n")
12741 (goto-char par-end)))
12742 @end group
12743 @end smallexample
12744
12745 The @code{let} expression creates and binds the local variable
12746 @code{par-end}. As we shall see, this local variable is designed to
12747 provide a bound or limit to the regular expression search. If the
12748 search fails to find a proper sentence ending in the paragraph, it will
12749 stop on reaching the end of the paragraph.
12750
12751 But first, let us examine how @code{par-end} is bound to the value of
12752 the end of the paragraph. What happens is that the @code{let} sets the
12753 value of @code{par-end} to the value returned when the Lisp interpreter
12754 evaluates the expression
12755
12756 @smallexample
12757 @group
12758 (save-excursion (end-of-paragraph-text) (point))
12759 @end group
12760 @end smallexample
12761
12762 @noindent
12763 In this expression, @code{(end-of-paragraph-text)} moves point to the
12764 end of the paragraph, @code{(point)} returns the value of point, and then
12765 @code{save-excursion} restores point to its original position. Thus,
12766 the @code{let} binds @code{par-end} to the value returned by the
12767 @code{save-excursion} expression, which is the position of the end of
12768 the paragraph. (The @code{end-of-paragraph-text} function uses
12769 @code{forward-paragraph}, which we will discuss shortly.)
12770
12771 @need 1200
12772 Emacs next evaluates the body of the @code{let}, which is an @code{if}
12773 expression that looks like this:
12774
12775 @smallexample
12776 @group
12777 (if (re-search-forward sentence-end par-end t) ; @r{if-part}
12778 (skip-chars-backward " \t\n") ; @r{then-part}
12779 (goto-char par-end))) ; @r{else-part}
12780 @end group
12781 @end smallexample
12782
12783 The @code{if} tests whether its first argument is true and if so,
12784 evaluates its then-part; otherwise, the Emacs Lisp interpreter
12785 evaluates the else-part. The true-or-false-test of the @code{if}
12786 expression is the regular expression search.
12787
12788 It may seem odd to have what looks like the `real work' of
12789 the @code{forward-sentence} function buried here, but this is a common
12790 way this kind of operation is carried out in Lisp.
12791
12792 @node fwd-sentence re-search
12793 @unnumberedsubsec The regular expression search
12794
12795 The @code{re-search-forward} function searches for the end of the
12796 sentence, that is, for the pattern defined by the @code{sentence-end}
12797 regular expression. If the pattern is found---if the end of the sentence is
12798 found---then the @code{re-search-forward} function does two things:
12799
12800 @enumerate
12801 @item
12802 The @code{re-search-forward} function carries out a side effect, which
12803 is to move point to the end of the occurrence found.
12804
12805 @item
12806 The @code{re-search-forward} function returns a value of true. This is
12807 the value received by the @code{if}, and means that the search was
12808 successful.
12809 @end enumerate
12810
12811 @noindent
12812 The side effect, the movement of point, is completed before the
12813 @code{if} function is handed the value returned by the successful
12814 conclusion of the search.
12815
12816 When the @code{if} function receives the value of true from a successful
12817 call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12818 which is the expression @code{(skip-chars-backward " \t\n")}. This
12819 expression moves backwards over any blank spaces, tabs or carriage
12820 returns until a printed character is found and then leaves point after
12821 the character. Since point has already been moved to the end of the
12822 pattern that marks the end of the sentence, this action leaves point
12823 right after the closing printed character of the sentence, which is
12824 usually a period.
12825
12826 On the other hand, if the @code{re-search-forward} function fails to
12827 find a pattern marking the end of the sentence, the function returns
12828 false. The false then causes the @code{if} to evaluate its third
12829 argument, which is @code{(goto-char par-end)}: it moves point to the
12830 end of the paragraph.
12831
12832 (And if the text is in a form or equivalent, and point may not move
12833 fully, then the @code{constrain-to-field} function comes into play.)
12834
12835 Regular expression searches are exceptionally useful and the pattern
12836 illustrated by @code{re-search-forward}, in which the search is the
12837 test of an @code{if} expression, is handy. You will see or write code
12838 incorporating this pattern often.
12839
12840 @node forward-paragraph
12841 @section @code{forward-paragraph}: a Goldmine of Functions
12842 @findex forward-paragraph
12843
12844 @ignore
12845 @c in GNU Emacs 22
12846 (defun forward-paragraph (&optional arg)
12847 "Move forward to end of paragraph.
12848 With argument ARG, do it ARG times;
12849 a negative argument ARG = -N means move backward N paragraphs.
12850
12851 A line which `paragraph-start' matches either separates paragraphs
12852 \(if `paragraph-separate' matches it also) or is the first line of a paragraph.
12853 A paragraph end is the beginning of a line which is not part of the paragraph
12854 to which the end of the previous line belongs, or the end of the buffer.
12855 Returns the count of paragraphs left to move."
12856 (interactive "p")
12857 (or arg (setq arg 1))
12858 (let* ((opoint (point))
12859 (fill-prefix-regexp
12860 (and fill-prefix (not (equal fill-prefix ""))
12861 (not paragraph-ignore-fill-prefix)
12862 (regexp-quote fill-prefix)))
12863 ;; Remove ^ from paragraph-start and paragraph-sep if they are there.
12864 ;; These regexps shouldn't be anchored, because we look for them
12865 ;; starting at the left-margin. This allows paragraph commands to
12866 ;; work normally with indented text.
12867 ;; This hack will not find problem cases like "whatever\\|^something".
12868 (parstart (if (and (not (equal "" paragraph-start))
12869 (equal ?^ (aref paragraph-start 0)))
12870 (substring paragraph-start 1)
12871 paragraph-start))
12872 (parsep (if (and (not (equal "" paragraph-separate))
12873 (equal ?^ (aref paragraph-separate 0)))
12874 (substring paragraph-separate 1)
12875 paragraph-separate))
12876 (parsep
12877 (if fill-prefix-regexp
12878 (concat parsep "\\|"
12879 fill-prefix-regexp "[ \t]*$")
12880 parsep))
12881 ;; This is used for searching.
12882 (sp-parstart (concat "^[ \t]*\\(?:" parstart "\\|" parsep "\\)"))
12883 start found-start)
12884 (while (and (< arg 0) (not (bobp)))
12885 (if (and (not (looking-at parsep))
12886 (re-search-backward "^\n" (max (1- (point)) (point-min)) t)
12887 (looking-at parsep))
12888 (setq arg (1+ arg))
12889 (setq start (point))
12890 ;; Move back over paragraph-separating lines.
12891 (forward-char -1) (beginning-of-line)
12892 (while (and (not (bobp))
12893 (progn (move-to-left-margin)
12894 (looking-at parsep)))
12895 (forward-line -1))
12896 (if (bobp)
12897 nil
12898 (setq arg (1+ arg))
12899 ;; Go to end of the previous (non-separating) line.
12900 (end-of-line)
12901 ;; Search back for line that starts or separates paragraphs.
12902 (if (if fill-prefix-regexp
12903 ;; There is a fill prefix; it overrides parstart.
12904 (let (multiple-lines)
12905 (while (and (progn (beginning-of-line) (not (bobp)))
12906 (progn (move-to-left-margin)
12907 (not (looking-at parsep)))
12908 (looking-at fill-prefix-regexp))
12909 (unless (= (point) start)
12910 (setq multiple-lines t))
12911 (forward-line -1))
12912 (move-to-left-margin)
12913 ;; This deleted code caused a long hanging-indent line
12914 ;; not to be filled together with the following lines.
12915 ;; ;; Don't move back over a line before the paragraph
12916 ;; ;; which doesn't start with fill-prefix
12917 ;; ;; unless that is the only line we've moved over.
12918 ;; (and (not (looking-at fill-prefix-regexp))
12919 ;; multiple-lines
12920 ;; (forward-line 1))
12921 (not (bobp)))
12922 (while (and (re-search-backward sp-parstart nil 1)
12923 (setq found-start t)
12924 ;; Found a candidate, but need to check if it is a
12925 ;; REAL parstart.
12926 (progn (setq start (point))
12927 (move-to-left-margin)
12928 (not (looking-at parsep)))
12929 (not (and (looking-at parstart)
12930 (or (not use-hard-newlines)
12931 (bobp)
12932 (get-text-property
12933 (1- start) 'hard)))))
12934 (setq found-start nil)
12935 (goto-char start))
12936 found-start)
12937 ;; Found one.
12938 (progn
12939 ;; Move forward over paragraph separators.
12940 ;; We know this cannot reach the place we started
12941 ;; because we know we moved back over a non-separator.
12942 (while (and (not (eobp))
12943 (progn (move-to-left-margin)
12944 (looking-at parsep)))
12945 (forward-line 1))
12946 ;; If line before paragraph is just margin, back up to there.
12947 (end-of-line 0)
12948 (if (> (current-column) (current-left-margin))
12949 (forward-char 1)
12950 (skip-chars-backward " \t")
12951 (if (not (bolp))
12952 (forward-line 1))))
12953 ;; No starter or separator line => use buffer beg.
12954 (goto-char (point-min))))))
12955
12956 (while (and (> arg 0) (not (eobp)))
12957 ;; Move forward over separator lines...
12958 (while (and (not (eobp))
12959 (progn (move-to-left-margin) (not (eobp)))
12960 (looking-at parsep))
12961 (forward-line 1))
12962 (unless (eobp) (setq arg (1- arg)))
12963 ;; ... and one more line.
12964 (forward-line 1)
12965 (if fill-prefix-regexp
12966 ;; There is a fill prefix; it overrides parstart.
12967 (while (and (not (eobp))
12968 (progn (move-to-left-margin) (not (eobp)))
12969 (not (looking-at parsep))
12970 (looking-at fill-prefix-regexp))
12971 (forward-line 1))
12972 (while (and (re-search-forward sp-parstart nil 1)
12973 (progn (setq start (match-beginning 0))
12974 (goto-char start)
12975 (not (eobp)))
12976 (progn (move-to-left-margin)
12977 (not (looking-at parsep)))
12978 (or (not (looking-at parstart))
12979 (and use-hard-newlines
12980 (not (get-text-property (1- start) 'hard)))))
12981 (forward-char 1))
12982 (if (< (point) (point-max))
12983 (goto-char start))))
12984 (constrain-to-field nil opoint t)
12985 ;; Return the number of steps that could not be done.
12986 arg))
12987 @end ignore
12988
12989 The @code{forward-paragraph} function moves point forward to the end
12990 of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12991 number of functions that are important in themselves, including
12992 @code{let*}, @code{match-beginning}, and @code{looking-at}.
12993
12994 The function definition for @code{forward-paragraph} is considerably
12995 longer than the function definition for @code{forward-sentence}
12996 because it works with a paragraph, each line of which may begin with a
12997 fill prefix.
12998
12999 A fill prefix consists of a string of characters that are repeated at
13000 the beginning of each line. For example, in Lisp code, it is a
13001 convention to start each line of a paragraph-long comment with
13002 @samp{;;; }. In Text mode, four blank spaces make up another common
13003 fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
13004 emacs, The GNU Emacs Manual}, for more information about fill
13005 prefixes.)
13006
13007 The existence of a fill prefix means that in addition to being able to
13008 find the end of a paragraph whose lines begin on the left-most
13009 column, the @code{forward-paragraph} function must be able to find the
13010 end of a paragraph when all or many of the lines in the buffer begin
13011 with the fill prefix.
13012
13013 Moreover, it is sometimes practical to ignore a fill prefix that
13014 exists, especially when blank lines separate paragraphs.
13015 This is an added complication.
13016
13017 @menu
13018 * forward-paragraph in brief:: Key parts of the function definition.
13019 * fwd-para let:: The @code{let*} expression.
13020 * fwd-para while:: The forward motion @code{while} loop.
13021 @end menu
13022
13023 @ifnottex
13024 @node forward-paragraph in brief
13025 @unnumberedsubsec Shortened @code{forward-paragraph} function definition
13026 @end ifnottex
13027
13028 Rather than print all of the @code{forward-paragraph} function, we
13029 will only print parts of it. Read without preparation, the function
13030 can be daunting!
13031
13032 @need 800
13033 In outline, the function looks like this:
13034
13035 @smallexample
13036 @group
13037 (defun forward-paragraph (&optional arg)
13038 "@var{documentation}@dots{}"
13039 (interactive "p")
13040 (or arg (setq arg 1))
13041 (let*
13042 @var{varlist}
13043 (while (and (< arg 0) (not (bobp))) ; @r{backward-moving-code}
13044 @dots{}
13045 (while (and (> arg 0) (not (eobp))) ; @r{forward-moving-code}
13046 @dots{}
13047 @end group
13048 @end smallexample
13049
13050 The first parts of the function are routine: the function's argument
13051 list consists of one optional argument. Documentation follows.
13052
13053 The lower case @samp{p} in the @code{interactive} declaration means
13054 that the processed prefix argument, if any, is passed to the function.
13055 This will be a number, and is the repeat count of how many paragraphs
13056 point will move. The @code{or} expression in the next line handles
13057 the common case when no argument is passed to the function, which occurs
13058 if the function is called from other code rather than interactively.
13059 This case was described earlier. (@xref{forward-sentence, The
13060 @code{forward-sentence} function}.) Now we reach the end of the
13061 familiar part of this function.
13062
13063 @node fwd-para let
13064 @unnumberedsubsec The @code{let*} expression
13065
13066 The next line of the @code{forward-paragraph} function begins a
13067 @code{let*} expression. This is a different than @code{let}. The
13068 symbol is @code{let*} not @code{let}.
13069
13070 The @code{let*} special form is like @code{let} except that Emacs sets
13071 each variable in sequence, one after another, and variables in the
13072 latter part of the varlist can make use of the values to which Emacs
13073 set variables in the earlier part of the varlist.
13074
13075 @ignore
13076 ( refappend save-excursion, , code save-excursion in code append-to-buffer .)
13077 @end ignore
13078
13079 (@ref{append save-excursion, , @code{save-excursion} in @code{append-to-buffer}}.)
13080
13081 In the @code{let*} expression in this function, Emacs binds a total of
13082 seven variables: @code{opoint}, @code{fill-prefix-regexp},
13083 @code{parstart}, @code{parsep}, @code{sp-parstart}, @code{start}, and
13084 @code{found-start}.
13085
13086 The variable @code{parsep} appears twice, first, to remove instances
13087 of @samp{^}, and second, to handle fill prefixes.
13088
13089 The variable @code{opoint} is just the value of @code{point}. As you
13090 can guess, it is used in a @code{constrain-to-field} expression, just
13091 as in @code{forward-sentence}.
13092
13093 The variable @code{fill-prefix-regexp} is set to the value returned by
13094 evaluating the following list:
13095
13096 @smallexample
13097 @group
13098 (and fill-prefix
13099 (not (equal fill-prefix ""))
13100 (not paragraph-ignore-fill-prefix)
13101 (regexp-quote fill-prefix))
13102 @end group
13103 @end smallexample
13104
13105 @noindent
13106 This is an expression whose first element is the @code{and} special form.
13107
13108 As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
13109 function}), the @code{and} special form evaluates each of its
13110 arguments until one of the arguments returns a value of @code{nil}, in
13111 which case the @code{and} expression returns @code{nil}; however, if
13112 none of the arguments returns a value of @code{nil}, the value
13113 resulting from evaluating the last argument is returned. (Since such
13114 a value is not @code{nil}, it is considered true in Lisp.) In other
13115 words, an @code{and} expression returns a true value only if all its
13116 arguments are true.
13117 @findex and
13118
13119 In this case, the variable @code{fill-prefix-regexp} is bound to a
13120 non-@code{nil} value only if the following four expressions produce a
13121 true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
13122 @code{fill-prefix-regexp} is bound to @code{nil}.
13123
13124 @table @code
13125 @item fill-prefix
13126 When this variable is evaluated, the value of the fill prefix, if any,
13127 is returned. If there is no fill prefix, this variable returns
13128 @code{nil}.
13129
13130 @item (not (equal fill-prefix "")
13131 This expression checks whether an existing fill prefix is an empty
13132 string, that is, a string with no characters in it. An empty string is
13133 not a useful fill prefix.
13134
13135 @item (not paragraph-ignore-fill-prefix)
13136 This expression returns @code{nil} if the variable
13137 @code{paragraph-ignore-fill-prefix} has been turned on by being set to a
13138 true value such as @code{t}.
13139
13140 @item (regexp-quote fill-prefix)
13141 This is the last argument to the @code{and} special form. If all the
13142 arguments to the @code{and} are true, the value resulting from
13143 evaluating this expression will be returned by the @code{and} expression
13144 and bound to the variable @code{fill-prefix-regexp},
13145 @end table
13146
13147 @findex regexp-quote
13148 @noindent
13149 The result of evaluating this @code{and} expression successfully is that
13150 @code{fill-prefix-regexp} will be bound to the value of
13151 @code{fill-prefix} as modified by the @code{regexp-quote} function.
13152 What @code{regexp-quote} does is read a string and return a regular
13153 expression that will exactly match the string and match nothing else.
13154 This means that @code{fill-prefix-regexp} will be set to a value that
13155 will exactly match the fill prefix if the fill prefix exists.
13156 Otherwise, the variable will be set to @code{nil}.
13157
13158 The next two local variables in the @code{let*} expression are
13159 designed to remove instances of @samp{^} from @code{parstart} and
13160 @code{parsep}, the local variables which indicate the paragraph start
13161 and the paragraph separator. The next expression sets @code{parsep}
13162 again. That is to handle fill prefixes.
13163
13164 This is the setting that requires the definition call @code{let*}
13165 rather than @code{let}. The true-or-false-test for the @code{if}
13166 depends on whether the variable @code{fill-prefix-regexp} evaluates to
13167 @code{nil} or some other value.
13168
13169 If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
13170 the else-part of the @code{if} expression and binds @code{parsep} to
13171 its local value. (@code{parsep} is a regular expression that matches
13172 what separates paragraphs.)
13173
13174 But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
13175 the then-part of the @code{if} expression and binds @code{parsep} to a
13176 regular expression that includes the @code{fill-prefix-regexp} as part
13177 of the pattern.
13178
13179 Specifically, @code{parsep} is set to the original value of the
13180 paragraph separate regular expression concatenated with an alternative
13181 expression that consists of the @code{fill-prefix-regexp} followed by
13182 optional whitespace to the end of the line. The whitespace is defined
13183 by @w{@code{"[ \t]*$"}}.) The @samp{\\|} defines this portion of the
13184 regexp as an alternative to @code{parsep}.
13185
13186 According to a comment in the code, the next local variable,
13187 @code{sp-parstart}, is used for searching, and then the final two,
13188 @code{start} and @code{found-start}, are set to @code{nil}.
13189
13190 Now we get into the body of the @code{let*}. The first part of the body
13191 of the @code{let*} deals with the case when the function is given a
13192 negative argument and is therefore moving backwards. We will skip this
13193 section.
13194
13195 @node fwd-para while
13196 @unnumberedsubsec The forward motion @code{while} loop
13197
13198 The second part of the body of the @code{let*} deals with forward
13199 motion. It is a @code{while} loop that repeats itself so long as the
13200 value of @code{arg} is greater than zero. In the most common use of
13201 the function, the value of the argument is 1, so the body of the
13202 @code{while} loop is evaluated exactly once, and the cursor moves
13203 forward one paragraph.
13204
13205 @ignore
13206 (while (and (> arg 0) (not (eobp)))
13207
13208 ;; Move forward over separator lines...
13209 (while (and (not (eobp))
13210 (progn (move-to-left-margin) (not (eobp)))
13211 (looking-at parsep))
13212 (forward-line 1))
13213 (unless (eobp) (setq arg (1- arg)))
13214 ;; ... and one more line.
13215 (forward-line 1)
13216
13217 (if fill-prefix-regexp
13218 ;; There is a fill prefix; it overrides parstart.
13219 (while (and (not (eobp))
13220 (progn (move-to-left-margin) (not (eobp)))
13221 (not (looking-at parsep))
13222 (looking-at fill-prefix-regexp))
13223 (forward-line 1))
13224
13225 (while (and (re-search-forward sp-parstart nil 1)
13226 (progn (setq start (match-beginning 0))
13227 (goto-char start)
13228 (not (eobp)))
13229 (progn (move-to-left-margin)
13230 (not (looking-at parsep)))
13231 (or (not (looking-at parstart))
13232 (and use-hard-newlines
13233 (not (get-text-property (1- start) 'hard)))))
13234 (forward-char 1))
13235
13236 (if (< (point) (point-max))
13237 (goto-char start))))
13238 @end ignore
13239
13240 This part handles three situations: when point is between paragraphs,
13241 when there is a fill prefix and when there is no fill prefix.
13242
13243 @need 800
13244 The @code{while} loop looks like this:
13245
13246 @smallexample
13247 @group
13248 ;; @r{going forwards and not at the end of the buffer}
13249 (while (and (> arg 0) (not (eobp)))
13250
13251 ;; @r{between paragraphs}
13252 ;; Move forward over separator lines...
13253 (while (and (not (eobp))
13254 (progn (move-to-left-margin) (not (eobp)))
13255 (looking-at parsep))
13256 (forward-line 1))
13257 ;; @r{This decrements the loop}
13258 (unless (eobp) (setq arg (1- arg)))
13259 ;; ... and one more line.
13260 (forward-line 1)
13261 @end group
13262
13263 @group
13264 (if fill-prefix-regexp
13265 ;; There is a fill prefix; it overrides parstart;
13266 ;; we go forward line by line
13267 (while (and (not (eobp))
13268 (progn (move-to-left-margin) (not (eobp)))
13269 (not (looking-at parsep))
13270 (looking-at fill-prefix-regexp))
13271 (forward-line 1))
13272 @end group
13273
13274 @group
13275 ;; There is no fill prefix;
13276 ;; we go forward character by character
13277 (while (and (re-search-forward sp-parstart nil 1)
13278 (progn (setq start (match-beginning 0))
13279 (goto-char start)
13280 (not (eobp)))
13281 (progn (move-to-left-margin)
13282 (not (looking-at parsep)))
13283 (or (not (looking-at parstart))
13284 (and use-hard-newlines
13285 (not (get-text-property (1- start) 'hard)))))
13286 (forward-char 1))
13287 @end group
13288
13289 @group
13290 ;; and if there is no fill prefix and if we are not at the end,
13291 ;; go to whatever was found in the regular expression search
13292 ;; for sp-parstart
13293 (if (< (point) (point-max))
13294 (goto-char start))))
13295 @end group
13296 @end smallexample
13297
13298 @findex eobp
13299 We can see that this is a decrementing counter @code{while} loop,
13300 using the expression @code{(setq arg (1- arg))} as the decrementer.
13301 That expression is not far from the @code{while}, but is hidden in
13302 another Lisp macro, an @code{unless} macro. Unless we are at the end
13303 of the buffer --- that is what the @code{eobp} function determines; it
13304 is an abbreviation of @samp{End Of Buffer P} --- we decrease the value
13305 of @code{arg} by one.
13306
13307 (If we are at the end of the buffer, we cannot go forward any more and
13308 the next loop of the @code{while} expression will test false since the
13309 test is an @code{and} with @code{(not (eobp))}. The @code{not}
13310 function means exactly as you expect; it is another name for
13311 @code{null}, a function that returns true when its argument is false.)
13312
13313 Interestingly, the loop count is not decremented until we leave the
13314 space between paragraphs, unless we come to the end of buffer or stop
13315 seeing the local value of the paragraph separator.
13316
13317 That second @code{while} also has a @code{(move-to-left-margin)}
13318 expression. The function is self-explanatory. It is inside a
13319 @code{progn} expression and not the last element of its body, so it is
13320 only invoked for its side effect, which is to move point to the left
13321 margin of the current line.
13322
13323 @findex looking-at
13324 The @code{looking-at} function is also self-explanatory; it returns
13325 true if the text after point matches the regular expression given as
13326 its argument.
13327
13328 The rest of the body of the loop looks difficult at first, but makes
13329 sense as you come to understand it.
13330
13331 @need 800
13332 First consider what happens if there is a fill prefix:
13333
13334 @smallexample
13335 @group
13336 (if fill-prefix-regexp
13337 ;; There is a fill prefix; it overrides parstart;
13338 ;; we go forward line by line
13339 (while (and (not (eobp))
13340 (progn (move-to-left-margin) (not (eobp)))
13341 (not (looking-at parsep))
13342 (looking-at fill-prefix-regexp))
13343 (forward-line 1))
13344 @end group
13345 @end smallexample
13346
13347 @noindent
13348 This expression moves point forward line by line so long
13349 as four conditions are true:
13350
13351 @enumerate
13352 @item
13353 Point is not at the end of the buffer.
13354
13355 @item
13356 We can move to the left margin of the text and are
13357 not at the end of the buffer.
13358
13359 @item
13360 The text following point does not separate paragraphs.
13361
13362 @item
13363 The pattern following point is the fill prefix regular expression.
13364 @end enumerate
13365
13366 The last condition may be puzzling, until you remember that point was
13367 moved to the beginning of the line early in the @code{forward-paragraph}
13368 function. This means that if the text has a fill prefix, the
13369 @code{looking-at} function will see it.
13370
13371 @need 1250
13372 Consider what happens when there is no fill prefix.
13373
13374 @smallexample
13375 @group
13376 (while (and (re-search-forward sp-parstart nil 1)
13377 (progn (setq start (match-beginning 0))
13378 (goto-char start)
13379 (not (eobp)))
13380 (progn (move-to-left-margin)
13381 (not (looking-at parsep)))
13382 (or (not (looking-at parstart))
13383 (and use-hard-newlines
13384 (not (get-text-property (1- start) 'hard)))))
13385 (forward-char 1))
13386 @end group
13387 @end smallexample
13388
13389 @noindent
13390 This @code{while} loop has us searching forward for
13391 @code{sp-parstart}, which is the combination of possible whitespace
13392 with a the local value of the start of a paragraph or of a paragraph
13393 separator. (The latter two are within an expression starting
13394 @code{\(?:} so that they are not referenced by the
13395 @code{match-beginning} function.)
13396
13397 @need 800
13398 The two expressions,
13399
13400 @smallexample
13401 @group
13402 (setq start (match-beginning 0))
13403 (goto-char start)
13404 @end group
13405 @end smallexample
13406
13407 @noindent
13408 mean go to the start of the text matched by the regular expression
13409 search.
13410
13411 The @code{(match-beginning 0)} expression is new. It returns a number
13412 specifying the location of the start of the text that was matched by
13413 the last search.
13414
13415 The @code{match-beginning} function is used here because of a
13416 characteristic of a forward search: a successful forward search,
13417 regardless of whether it is a plain search or a regular expression
13418 search, moves point to the end of the text that is found. In this
13419 case, a successful search moves point to the end of the pattern for
13420 @code{sp-parstart}.
13421
13422 However, we want to put point at the end of the current paragraph, not
13423 somewhere else. Indeed, since the search possibly includes the
13424 paragraph separator, point may end up at the beginning of the next one
13425 unless we use an expression that includes @code{match-beginning}.
13426
13427 @findex match-beginning
13428 When given an argument of 0, @code{match-beginning} returns the
13429 position that is the start of the text matched by the most recent
13430 search. In this case, the most recent search looks for
13431 @code{sp-parstart}. The @code{(match-beginning 0)} expression returns
13432 the beginning position of that pattern, rather than the end position
13433 of that pattern.
13434
13435 (Incidentally, when passed a positive number as an argument, the
13436 @code{match-beginning} function returns the location of point at that
13437 parenthesized expression in the last search unless that parenthesized
13438 expression begins with @code{\(?:}. I don't know why @code{\(?:}
13439 appears here since the argument is 0.)
13440
13441 @need 1250
13442 The last expression when there is no fill prefix is
13443
13444 @smallexample
13445 @group
13446 (if (< (point) (point-max))
13447 (goto-char start))))
13448 @end group
13449 @end smallexample
13450
13451 @noindent
13452 This says that if there is no fill prefix and if we are not at the
13453 end, point should move to the beginning of whatever was found by the
13454 regular expression search for @code{sp-parstart}.
13455
13456 The full definition for the @code{forward-paragraph} function not only
13457 includes code for going forwards, but also code for going backwards.
13458
13459 If you are reading this inside of GNU Emacs and you want to see the
13460 whole function, you can type @kbd{C-h f} (@code{describe-function})
13461 and the name of the function. This gives you the function
13462 documentation and the name of the library containing the function's
13463 source. Place point over the name of the library and press the RET
13464 key; you will be taken directly to the source. (Be sure to install
13465 your sources! Without them, you are like a person who tries to drive
13466 a car with his eyes shut!)
13467
13468 @node etags
13469 @section Create Your Own @file{TAGS} File
13470 @findex etags
13471 @cindex @file{TAGS} file, create own
13472
13473 Besides @kbd{C-h f} (@code{describe-function}), another way to see the
13474 source of a function is to type @kbd{M-.} (@code{find-tag}) and the
13475 name of the function when prompted for it. This is a good habit to
13476 get into. The @kbd{M-.} (@code{find-tag}) command takes you directly
13477 to the source for a function, variable, or node. The function depends
13478 on tags tables to tell it where to go.
13479
13480 If the @code{find-tag} function first asks you for the name of a
13481 @file{TAGS} table, give it the name of a @file{TAGS} file such as
13482 @file{/usr/local/src/emacs/src/TAGS}. (The exact path to your
13483 @file{TAGS} file depends on how your copy of Emacs was installed. I
13484 just told you the location that provides both my C and my Emacs Lisp
13485 sources.)
13486
13487 You can also create your own @file{TAGS} file for directories that
13488 lack one.
13489
13490 You often need to build and install tags tables yourself. They are
13491 not built automatically. A tags table is called a @file{TAGS} file;
13492 the name is in upper case letters.
13493
13494 You can create a @file{TAGS} file by calling the @code{etags} program
13495 that comes as a part of the Emacs distribution. Usually, @code{etags}
13496 is compiled and installed when Emacs is built. (@code{etags} is not
13497 an Emacs Lisp function or a part of Emacs; it is a C program.)
13498
13499 @need 1250
13500 To create a @file{TAGS} file, first switch to the directory in which
13501 you want to create the file. In Emacs you can do this with the
13502 @kbd{M-x cd} command, or by visiting a file in the directory, or by
13503 listing the directory with @kbd{C-x d} (@code{dired}). Then run the
13504 compile command, with @w{@code{etags *.el}} as the command to execute
13505
13506 @smallexample
13507 M-x compile RET etags *.el RET
13508 @end smallexample
13509
13510 @noindent
13511 to create a @file{TAGS} file for Emacs Lisp.
13512
13513 For example, if you have a large number of files in your
13514 @file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
13515 of which I load 12---you can create a @file{TAGS} file for the Emacs
13516 Lisp files in that directory.
13517
13518 @need 1250
13519 The @code{etags} program takes all the usual shell `wildcards'. For
13520 example, if you have two directories for which you want a single
13521 @file{TAGS} file, type @w{@code{etags *.el ../elisp/*.el}}, where
13522 @file{../elisp/} is the second directory:
13523
13524 @smallexample
13525 M-x compile RET etags *.el ../elisp/*.el RET
13526 @end smallexample
13527
13528 @need 1250
13529 Type
13530
13531 @smallexample
13532 M-x compile RET etags --help RET
13533 @end smallexample
13534
13535 @noindent
13536 to see a list of the options accepted by @code{etags} as well as a
13537 list of supported languages.
13538
13539 The @code{etags} program handles more than 20 languages, including
13540 Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, HTML, Java,
13541 LaTeX, Pascal, Perl, PostScript, Python, TeX, Texinfo, makefiles, and
13542 most assemblers. The program has no switches for specifying the
13543 language; it recognizes the language in an input file according to its
13544 file name and contents.
13545
13546 @file{etags} is very helpful when you are writing code yourself and
13547 want to refer back to functions you have already written. Just run
13548 @code{etags} again at intervals as you write new functions, so they
13549 become part of the @file{TAGS} file.
13550
13551 If you think an appropriate @file{TAGS} file already exists for what
13552 you want, but do not know where it is, you can use the @code{locate}
13553 program to attempt to find it.
13554
13555 Type @w{@kbd{M-x locate @key{RET} TAGS @key{RET}}} and Emacs will list
13556 for you the full path names of all your @file{TAGS} files. On my
13557 system, this command lists 34 @file{TAGS} files. On the other hand, a
13558 `plain vanilla' system I recently installed did not contain any
13559 @file{TAGS} files.
13560
13561 If the tags table you want has been created, you can use the @code{M-x
13562 visit-tags-table} command to specify it. Otherwise, you will need to
13563 create the tag table yourself and then use @code{M-x
13564 visit-tags-table}.
13565
13566 @subsubheading Building Tags in the Emacs sources
13567 @cindex Building Tags in the Emacs sources
13568 @cindex Tags in the Emacs sources
13569 @findex make tags
13570
13571 The GNU Emacs sources come with a @file{Makefile} that contains a
13572 sophisticated @code{etags} command that creates, collects, and merges
13573 tags tables from all over the Emacs sources and puts the information
13574 into one @file{TAGS} file in the @file{src/} directory. (The
13575 @file{src/} directory is below the top level of your Emacs directory.)
13576
13577 @need 1250
13578 To build this @file{TAGS} file, go to the top level of your Emacs
13579 source directory and run the compile command @code{make tags}:
13580
13581 @smallexample
13582 M-x compile RET make tags RET
13583 @end smallexample
13584
13585 @noindent
13586 (The @code{make tags} command works well with the GNU Emacs sources,
13587 as well as with some other source packages.)
13588
13589 For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
13590 Manual}.
13591
13592 @node Regexp Review
13593 @section Review
13594
13595 Here is a brief summary of some recently introduced functions.
13596
13597 @table @code
13598 @item while
13599 Repeatedly evaluate the body of the expression so long as the first
13600 element of the body tests true. Then return @code{nil}. (The
13601 expression is evaluated only for its side effects.)
13602
13603 @need 1250
13604 For example:
13605
13606 @smallexample
13607 @group
13608 (let ((foo 2))
13609 (while (> foo 0)
13610 (insert (format "foo is %d.\n" foo))
13611 (setq foo (1- foo))))
13612
13613 @result{} foo is 2.
13614 foo is 1.
13615 nil
13616 @end group
13617 @end smallexample
13618
13619 @noindent
13620 (The @code{insert} function inserts its arguments at point; the
13621 @code{format} function returns a string formatted from its arguments
13622 the way @code{message} formats its arguments; @code{\n} produces a new
13623 line.)
13624
13625 @item re-search-forward
13626 Search for a pattern, and if the pattern is found, move point to rest
13627 just after it.
13628
13629 @noindent
13630 Takes four arguments, like @code{search-forward}:
13631
13632 @enumerate
13633 @item
13634 A regular expression that specifies the pattern to search for.
13635 (Remember to put quotation marks around this argument!)
13636
13637 @item
13638 Optionally, the limit of the search.
13639
13640 @item
13641 Optionally, what to do if the search fails, return @code{nil} or an
13642 error message.
13643
13644 @item
13645 Optionally, how many times to repeat the search; if negative, the
13646 search goes backwards.
13647 @end enumerate
13648
13649 @item let*
13650 Bind some variables locally to particular values,
13651 and then evaluate the remaining arguments, returning the value of the
13652 last one. While binding the local variables, use the local values of
13653 variables bound earlier, if any.
13654
13655 @need 1250
13656 For example:
13657
13658 @smallexample
13659 @group
13660 (let* ((foo 7)
13661 (bar (* 3 foo)))
13662 (message "`bar' is %d." bar))
13663 @result{} `bar' is 21.
13664 @end group
13665 @end smallexample
13666
13667 @item match-beginning
13668 Return the position of the start of the text found by the last regular
13669 expression search.
13670
13671 @item looking-at
13672 Return @code{t} for true if the text after point matches the argument,
13673 which should be a regular expression.
13674
13675 @item eobp
13676 Return @code{t} for true if point is at the end of the accessible part
13677 of a buffer. The end of the accessible part is the end of the buffer
13678 if the buffer is not narrowed; it is the end of the narrowed part if
13679 the buffer is narrowed.
13680 @end table
13681
13682 @need 1500
13683 @node re-search Exercises
13684 @section Exercises with @code{re-search-forward}
13685
13686 @itemize @bullet
13687 @item
13688 Write a function to search for a regular expression that matches two
13689 or more blank lines in sequence.
13690
13691 @item
13692 Write a function to search for duplicated words, such as `the the'.
13693 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
13694 Manual}, for information on how to write a regexp (a regular
13695 expression) to match a string that is composed of two identical
13696 halves. You can devise several regexps; some are better than others.
13697 The function I use is described in an appendix, along with several
13698 regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
13699 @end itemize
13700
13701 @node Counting Words
13702 @chapter Counting: Repetition and Regexps
13703 @cindex Repetition for word counting
13704 @cindex Regular expressions for word counting
13705
13706 Repetition and regular expression searches are powerful tools that you
13707 often use when you write code in Emacs Lisp. This chapter illustrates
13708 the use of regular expression searches through the construction of
13709 word count commands using @code{while} loops and recursion.
13710
13711 @menu
13712 * Why Count Words::
13713 * @value{COUNT-WORDS}:: Use a regexp, but find a problem.
13714 * recursive-count-words:: Start with case of no words in region.
13715 * Counting Exercise::
13716 @end menu
13717
13718 @ifnottex
13719 @node Why Count Words
13720 @unnumberedsec Counting words
13721 @end ifnottex
13722
13723 The standard Emacs distribution contains functions for counting the
13724 number of lines and words within a region.
13725
13726 Certain types of writing ask you to count words. Thus, if you write
13727 an essay, you may be limited to 800 words; if you write a novel, you
13728 may discipline yourself to write 1000 words a day. It seems odd, but
13729 for a long time, Emacs lacked a word count command. Perhaps people used
13730 Emacs mostly for code or types of documentation that did not require
13731 word counts; or perhaps they restricted themselves to the operating
13732 system word count command, @code{wc}. Alternatively, people may have
13733 followed the publishers' convention and computed a word count by
13734 dividing the number of characters in a document by five.
13735
13736 There are many ways to implement a command to count words. Here are
13737 some examples, which you may wish to compare with the standard Emacs
13738 command, @code{count-words-region}.
13739
13740 @node @value{COUNT-WORDS}
13741 @section The @code{@value{COUNT-WORDS}} Function
13742 @findex @value{COUNT-WORDS}
13743
13744 A word count command could count words in a line, paragraph, region,
13745 or buffer. What should the command cover? You could design the
13746 command to count the number of words in a complete buffer. However,
13747 the Emacs tradition encourages flexibility---you may want to count
13748 words in just a section, rather than all of a buffer. So it makes
13749 more sense to design the command to count the number of words in a
13750 region. Once you have a command to count words in a region, you can,
13751 if you wish, count words in a whole buffer by marking it with
13752 @w{@kbd{C-x h}} (@code{mark-whole-buffer}).
13753
13754 Clearly, counting words is a repetitive act: starting from the
13755 beginning of the region, you count the first word, then the second
13756 word, then the third word, and so on, until you reach the end of the
13757 region. This means that word counting is ideally suited to recursion
13758 or to a @code{while} loop.
13759
13760 @menu
13761 * Design @value{COUNT-WORDS}:: The definition using a @code{while} loop.
13762 * Whitespace Bug:: The Whitespace Bug in @code{@value{COUNT-WORDS}}.
13763 @end menu
13764
13765 @ifnottex
13766 @node Design @value{COUNT-WORDS}
13767 @unnumberedsubsec Designing @code{@value{COUNT-WORDS}}
13768 @end ifnottex
13769
13770 First, we will implement the word count command with a @code{while}
13771 loop, then with recursion. The command will, of course, be
13772 interactive.
13773
13774 @need 800
13775 The template for an interactive function definition is, as always:
13776
13777 @smallexample
13778 @group
13779 (defun @var{name-of-function} (@var{argument-list})
13780 "@var{documentation}@dots{}"
13781 (@var{interactive-expression}@dots{})
13782 @var{body}@dots{})
13783 @end group
13784 @end smallexample
13785
13786 What we need to do is fill in the slots.
13787
13788 The name of the function should be self-explanatory and similar to the
13789 existing @code{count-lines-region} name. This makes the name easier
13790 to remember. @code{count-words-region} is the obvious choice. Since
13791 that name is now used for the standard Emacs command to count words, we
13792 will name our implementation @code{@value{COUNT-WORDS}}.
13793
13794 The function counts words within a region. This means that the
13795 argument list must contain symbols that are bound to the two
13796 positions, the beginning and end of the region. These two positions
13797 can be called @samp{beginning} and @samp{end} respectively. The first
13798 line of the documentation should be a single sentence, since that is
13799 all that is printed as documentation by a command such as
13800 @code{apropos}. The interactive expression will be of the form
13801 @samp{(interactive "r")}, since that will cause Emacs to pass the
13802 beginning and end of the region to the function's argument list. All
13803 this is routine.
13804
13805 The body of the function needs to be written to do three tasks:
13806 first, to set up conditions under which the @code{while} loop can
13807 count words, second, to run the @code{while} loop, and third, to send
13808 a message to the user.
13809
13810 When a user calls @code{@value{COUNT-WORDS}}, point may be at the
13811 beginning or the end of the region. However, the counting process
13812 must start at the beginning of the region. This means we will want
13813 to put point there if it is not already there. Executing
13814 @code{(goto-char beginning)} ensures this. Of course, we will want to
13815 return point to its expected position when the function finishes its
13816 work. For this reason, the body must be enclosed in a
13817 @code{save-excursion} expression.
13818
13819 The central part of the body of the function consists of a
13820 @code{while} loop in which one expression jumps point forward word by
13821 word, and another expression counts those jumps. The true-or-false-test
13822 of the @code{while} loop should test true so long as point should jump
13823 forward, and false when point is at the end of the region.
13824
13825 We could use @code{(forward-word 1)} as the expression for moving point
13826 forward word by word, but it is easier to see what Emacs identifies as a
13827 `word' if we use a regular expression search.
13828
13829 A regular expression search that finds the pattern for which it is
13830 searching leaves point after the last character matched. This means
13831 that a succession of successful word searches will move point forward
13832 word by word.
13833
13834 As a practical matter, we want the regular expression search to jump
13835 over whitespace and punctuation between words as well as over the
13836 words themselves. A regexp that refuses to jump over interword
13837 whitespace would never jump more than one word! This means that
13838 the regexp should include the whitespace and punctuation that follows
13839 a word, if any, as well as the word itself. (A word may end a buffer
13840 and not have any following whitespace or punctuation, so that part of
13841 the regexp must be optional.)
13842
13843 Thus, what we want for the regexp is a pattern defining one or more
13844 word constituent characters followed, optionally, by one or more
13845 characters that are not word constituents. The regular expression for
13846 this is:
13847
13848 @smallexample
13849 \w+\W*
13850 @end smallexample
13851
13852 @noindent
13853 The buffer's syntax table determines which characters are and are not
13854 word constituents. For more information about syntax,
13855 @pxref{Syntax Tables, , Syntax Tables, elisp, The GNU Emacs Lisp
13856 Reference Manual}.
13857
13858 @need 800
13859 The search expression looks like this:
13860
13861 @smallexample
13862 (re-search-forward "\\w+\\W*")
13863 @end smallexample
13864
13865 @noindent
13866 (Note that paired backslashes precede the @samp{w} and @samp{W}. A
13867 single backslash has special meaning to the Emacs Lisp interpreter.
13868 It indicates that the following character is interpreted differently
13869 than usual. For example, the two characters, @samp{\n}, stand for
13870 @samp{newline}, rather than for a backslash followed by @samp{n}. Two
13871 backslashes in a row stand for an ordinary, `unspecial' backslash, so
13872 Emacs Lisp interpreter ends of seeing a single backslash followed by a
13873 letter. So it discovers the letter is special.)
13874
13875 We need a counter to count how many words there are; this variable
13876 must first be set to 0 and then incremented each time Emacs goes
13877 around the @code{while} loop. The incrementing expression is simply:
13878
13879 @smallexample
13880 (setq count (1+ count))
13881 @end smallexample
13882
13883 Finally, we want to tell the user how many words there are in the
13884 region. The @code{message} function is intended for presenting this
13885 kind of information to the user. The message has to be phrased so
13886 that it reads properly regardless of how many words there are in the
13887 region: we don't want to say that ``there are 1 words in the region''.
13888 The conflict between singular and plural is ungrammatical. We can
13889 solve this problem by using a conditional expression that evaluates
13890 different messages depending on the number of words in the region.
13891 There are three possibilities: no words in the region, one word in the
13892 region, and more than one word. This means that the @code{cond}
13893 special form is appropriate.
13894
13895 @need 1500
13896 All this leads to the following function definition:
13897
13898 @smallexample
13899 @group
13900 ;;; @r{First version; has bugs!}
13901 (defun @value{COUNT-WORDS} (beginning end)
13902 "Print number of words in the region.
13903 Words are defined as at least one word-constituent
13904 character followed by at least one character that
13905 is not a word-constituent. The buffer's syntax
13906 table determines which characters these are."
13907 (interactive "r")
13908 (message "Counting words in region ... ")
13909 @end group
13910
13911 @group
13912 ;;; @r{1. Set up appropriate conditions.}
13913 (save-excursion
13914 (goto-char beginning)
13915 (let ((count 0))
13916 @end group
13917
13918 @group
13919 ;;; @r{2. Run the} while @r{loop.}
13920 (while (< (point) end)
13921 (re-search-forward "\\w+\\W*")
13922 (setq count (1+ count)))
13923 @end group
13924
13925 @group
13926 ;;; @r{3. Send a message to the user.}
13927 (cond ((zerop count)
13928 (message
13929 "The region does NOT have any words."))
13930 ((= 1 count)
13931 (message
13932 "The region has 1 word."))
13933 (t
13934 (message
13935 "The region has %d words." count))))))
13936 @end group
13937 @end smallexample
13938
13939 @noindent
13940 As written, the function works, but not in all circumstances.
13941
13942 @node Whitespace Bug
13943 @subsection The Whitespace Bug in @code{@value{COUNT-WORDS}}
13944
13945 The @code{@value{COUNT-WORDS}} command described in the preceding
13946 section has two bugs, or rather, one bug with two manifestations.
13947 First, if you mark a region containing only whitespace in the middle
13948 of some text, the @code{@value{COUNT-WORDS}} command tells you that the
13949 region contains one word! Second, if you mark a region containing
13950 only whitespace at the end of the buffer or the accessible portion of
13951 a narrowed buffer, the command displays an error message that looks
13952 like this:
13953
13954 @smallexample
13955 Search failed: "\\w+\\W*"
13956 @end smallexample
13957
13958 If you are reading this in Info in GNU Emacs, you can test for these
13959 bugs yourself.
13960
13961 First, evaluate the function in the usual manner to install it.
13962 @ifinfo
13963 Here is a copy of the definition. Place your cursor after the closing
13964 parenthesis and type @kbd{C-x C-e} to install it.
13965
13966 @smallexample
13967 @group
13968 ;; @r{First version; has bugs!}
13969 (defun @value{COUNT-WORDS} (beginning end)
13970 "Print number of words in the region.
13971 Words are defined as at least one word-constituent character followed
13972 by at least one character that is not a word-constituent. The buffer's
13973 syntax table determines which characters these are."
13974 @end group
13975 @group
13976 (interactive "r")
13977 (message "Counting words in region ... ")
13978 @end group
13979
13980 @group
13981 ;;; @r{1. Set up appropriate conditions.}
13982 (save-excursion
13983 (goto-char beginning)
13984 (let ((count 0))
13985 @end group
13986
13987 @group
13988 ;;; @r{2. Run the} while @r{loop.}
13989 (while (< (point) end)
13990 (re-search-forward "\\w+\\W*")
13991 (setq count (1+ count)))
13992 @end group
13993
13994 @group
13995 ;;; @r{3. Send a message to the user.}
13996 (cond ((zerop count)
13997 (message "The region does NOT have any words."))
13998 ((= 1 count) (message "The region has 1 word."))
13999 (t (message "The region has %d words." count))))))
14000 @end group
14001 @end smallexample
14002 @end ifinfo
14003
14004 @need 1000
14005 If you wish, you can also install this keybinding by evaluating it:
14006
14007 @smallexample
14008 (global-set-key "\C-c=" '@value{COUNT-WORDS})
14009 @end smallexample
14010
14011 To conduct the first test, set mark and point to the beginning and end
14012 of the following line and then type @kbd{C-c =} (or @kbd{M-x
14013 @value{COUNT-WORDS}} if you have not bound @kbd{C-c =}):
14014
14015 @smallexample
14016 one two three
14017 @end smallexample
14018
14019 @noindent
14020 Emacs will tell you, correctly, that the region has three words.
14021
14022 Repeat the test, but place mark at the beginning of the line and place
14023 point just @emph{before} the word @samp{one}. Again type the command
14024 @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}). Emacs should tell you
14025 that the region has no words, since it is composed only of the
14026 whitespace at the beginning of the line. But instead Emacs tells you
14027 that the region has one word!
14028
14029 For the third test, copy the sample line to the end of the
14030 @file{*scratch*} buffer and then type several spaces at the end of the
14031 line. Place mark right after the word @samp{three} and point at the
14032 end of line. (The end of the line will be the end of the buffer.)
14033 Type @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}) as you did before.
14034 Again, Emacs should tell you that the region has no words, since it is
14035 composed only of the whitespace at the end of the line. Instead,
14036 Emacs displays an error message saying @samp{Search failed}.
14037
14038 The two bugs stem from the same problem.
14039
14040 Consider the first manifestation of the bug, in which the command
14041 tells you that the whitespace at the beginning of the line contains
14042 one word. What happens is this: The @code{M-x @value{COUNT-WORDS}}
14043 command moves point to the beginning of the region. The @code{while}
14044 tests whether the value of point is smaller than the value of
14045 @code{end}, which it is. Consequently, the regular expression search
14046 looks for and finds the first word. It leaves point after the word.
14047 @code{count} is set to one. The @code{while} loop repeats; but this
14048 time the value of point is larger than the value of @code{end}, the
14049 loop is exited; and the function displays a message saying the number
14050 of words in the region is one. In brief, the regular expression
14051 search looks for and finds the word even though it is outside
14052 the marked region.
14053
14054 In the second manifestation of the bug, the region is whitespace at
14055 the end of the buffer. Emacs says @samp{Search failed}. What happens
14056 is that the true-or-false-test in the @code{while} loop tests true, so
14057 the search expression is executed. But since there are no more words
14058 in the buffer, the search fails.
14059
14060 In both manifestations of the bug, the search extends or attempts to
14061 extend outside of the region.
14062
14063 The solution is to limit the search to the region---this is a fairly
14064 simple action, but as you may have come to expect, it is not quite as
14065 simple as you might think.
14066
14067 As we have seen, the @code{re-search-forward} function takes a search
14068 pattern as its first argument. But in addition to this first,
14069 mandatory argument, it accepts three optional arguments. The optional
14070 second argument bounds the search. The optional third argument, if
14071 @code{t}, causes the function to return @code{nil} rather than signal
14072 an error if the search fails. The optional fourth argument is a
14073 repeat count. (In Emacs, you can see a function's documentation by
14074 typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
14075
14076 In the @code{@value{COUNT-WORDS}} definition, the value of the end of
14077 the region is held by the variable @code{end} which is passed as an
14078 argument to the function. Thus, we can add @code{end} as an argument
14079 to the regular expression search expression:
14080
14081 @smallexample
14082 (re-search-forward "\\w+\\W*" end)
14083 @end smallexample
14084
14085 However, if you make only this change to the @code{@value{COUNT-WORDS}}
14086 definition and then test the new version of the definition on a
14087 stretch of whitespace, you will receive an error message saying
14088 @samp{Search failed}.
14089
14090 What happens is this: the search is limited to the region, and fails
14091 as you expect because there are no word-constituent characters in the
14092 region. Since it fails, we receive an error message. But we do not
14093 want to receive an error message in this case; we want to receive the
14094 message that "The region does NOT have any words."
14095
14096 The solution to this problem is to provide @code{re-search-forward}
14097 with a third argument of @code{t}, which causes the function to return
14098 @code{nil} rather than signal an error if the search fails.
14099
14100 However, if you make this change and try it, you will see the message
14101 ``Counting words in region ... '' and @dots{} you will keep on seeing
14102 that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
14103
14104 Here is what happens: the search is limited to the region, as before,
14105 and it fails because there are no word-constituent characters in the
14106 region, as expected. Consequently, the @code{re-search-forward}
14107 expression returns @code{nil}. It does nothing else. In particular,
14108 it does not move point, which it does as a side effect if it finds the
14109 search target. After the @code{re-search-forward} expression returns
14110 @code{nil}, the next expression in the @code{while} loop is evaluated.
14111 This expression increments the count. Then the loop repeats. The
14112 true-or-false-test tests true because the value of point is still less
14113 than the value of end, since the @code{re-search-forward} expression
14114 did not move point. @dots{} and the cycle repeats @dots{}
14115
14116 The @code{@value{COUNT-WORDS}} definition requires yet another
14117 modification, to cause the true-or-false-test of the @code{while} loop
14118 to test false if the search fails. Put another way, there are two
14119 conditions that must be satisfied in the true-or-false-test before the
14120 word count variable is incremented: point must still be within the
14121 region and the search expression must have found a word to count.
14122
14123 Since both the first condition and the second condition must be true
14124 together, the two expressions, the region test and the search
14125 expression, can be joined with an @code{and} special form and embedded in
14126 the @code{while} loop as the true-or-false-test, like this:
14127
14128 @smallexample
14129 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
14130 @end smallexample
14131
14132 @c colon in printed section title causes problem in Info cross reference
14133 @c also trouble with an overfull hbox
14134 @iftex
14135 @noindent
14136 (For information about @code{and}, see
14137 @ref{kill-new function, , The @code{kill-new} function}.)
14138 @end iftex
14139 @ifinfo
14140 @noindent
14141 (@xref{kill-new function, , The @code{kill-new} function}, for
14142 information about @code{and}.)
14143 @end ifinfo
14144
14145 The @code{re-search-forward} expression returns @code{t} if the search
14146 succeeds and as a side effect moves point. Consequently, as words are
14147 found, point is moved through the region. When the search expression
14148 fails to find another word, or when point reaches the end of the
14149 region, the true-or-false-test tests false, the @code{while} loop
14150 exits, and the @code{@value{COUNT-WORDS}} function displays one or
14151 other of its messages.
14152
14153 After incorporating these final changes, the @code{@value{COUNT-WORDS}}
14154 works without bugs (or at least, without bugs that I have found!).
14155 Here is what it looks like:
14156
14157 @smallexample
14158 @group
14159 ;;; @r{Final version:} @code{while}
14160 (defun @value{COUNT-WORDS} (beginning end)
14161 "Print number of words in the region."
14162 (interactive "r")
14163 (message "Counting words in region ... ")
14164 @end group
14165
14166 @group
14167 ;;; @r{1. Set up appropriate conditions.}
14168 (save-excursion
14169 (let ((count 0))
14170 (goto-char beginning)
14171 @end group
14172
14173 @group
14174 ;;; @r{2. Run the} while @r{loop.}
14175 (while (and (< (point) end)
14176 (re-search-forward "\\w+\\W*" end t))
14177 (setq count (1+ count)))
14178 @end group
14179
14180 @group
14181 ;;; @r{3. Send a message to the user.}
14182 (cond ((zerop count)
14183 (message
14184 "The region does NOT have any words."))
14185 ((= 1 count)
14186 (message
14187 "The region has 1 word."))
14188 (t
14189 (message
14190 "The region has %d words." count))))))
14191 @end group
14192 @end smallexample
14193
14194 @node recursive-count-words
14195 @section Count Words Recursively
14196 @cindex Count words recursively
14197 @cindex Recursively counting words
14198 @cindex Words, counted recursively
14199
14200 You can write the function for counting words recursively as well as
14201 with a @code{while} loop. Let's see how this is done.
14202
14203 First, we need to recognize that the @code{@value{COUNT-WORDS}}
14204 function has three jobs: it sets up the appropriate conditions for
14205 counting to occur; it counts the words in the region; and it sends a
14206 message to the user telling how many words there are.
14207
14208 If we write a single recursive function to do everything, we will
14209 receive a message for every recursive call. If the region contains 13
14210 words, we will receive thirteen messages, one right after the other.
14211 We don't want this! Instead, we must write two functions to do the
14212 job, one of which (the recursive function) will be used inside of the
14213 other. One function will set up the conditions and display the
14214 message; the other will return the word count.
14215
14216 Let us start with the function that causes the message to be displayed.
14217 We can continue to call this @code{@value{COUNT-WORDS}}.
14218
14219 This is the function that the user will call. It will be interactive.
14220 Indeed, it will be similar to our previous versions of this
14221 function, except that it will call @code{recursive-count-words} to
14222 determine how many words are in the region.
14223
14224 @need 1250
14225 We can readily construct a template for this function, based on our
14226 previous versions:
14227
14228 @smallexample
14229 @group
14230 ;; @r{Recursive version; uses regular expression search}
14231 (defun @value{COUNT-WORDS} (beginning end)
14232 "@var{documentation}@dots{}"
14233 (@var{interactive-expression}@dots{})
14234 @end group
14235 @group
14236
14237 ;;; @r{1. Set up appropriate conditions.}
14238 (@var{explanatory message})
14239 (@var{set-up functions}@dots{}
14240 @end group
14241 @group
14242
14243 ;;; @r{2. Count the words.}
14244 @var{recursive call}
14245 @end group
14246 @group
14247
14248 ;;; @r{3. Send a message to the user.}
14249 @var{message providing word count}))
14250 @end group
14251 @end smallexample
14252
14253 The definition looks straightforward, except that somehow the count
14254 returned by the recursive call must be passed to the message
14255 displaying the word count. A little thought suggests that this can be
14256 done by making use of a @code{let} expression: we can bind a variable
14257 in the varlist of a @code{let} expression to the number of words in
14258 the region, as returned by the recursive call; and then the
14259 @code{cond} expression, using binding, can display the value to the
14260 user.
14261
14262 Often, one thinks of the binding within a @code{let} expression as
14263 somehow secondary to the `primary' work of a function. But in this
14264 case, what you might consider the `primary' job of the function,
14265 counting words, is done within the @code{let} expression.
14266
14267 @need 1250
14268 Using @code{let}, the function definition looks like this:
14269
14270 @smallexample
14271 @group
14272 (defun @value{COUNT-WORDS} (beginning end)
14273 "Print number of words in the region."
14274 (interactive "r")
14275 @end group
14276
14277 @group
14278 ;;; @r{1. Set up appropriate conditions.}
14279 (message "Counting words in region ... ")
14280 (save-excursion
14281 (goto-char beginning)
14282 @end group
14283
14284 @group
14285 ;;; @r{2. Count the words.}
14286 (let ((count (recursive-count-words end)))
14287 @end group
14288
14289 @group
14290 ;;; @r{3. Send a message to the user.}
14291 (cond ((zerop count)
14292 (message
14293 "The region does NOT have any words."))
14294 ((= 1 count)
14295 (message
14296 "The region has 1 word."))
14297 (t
14298 (message
14299 "The region has %d words." count))))))
14300 @end group
14301 @end smallexample
14302
14303 Next, we need to write the recursive counting function.
14304
14305 A recursive function has at least three parts: the `do-again-test', the
14306 `next-step-expression', and the recursive call.
14307
14308 The do-again-test determines whether the function will or will not be
14309 called again. Since we are counting words in a region and can use a
14310 function that moves point forward for every word, the do-again-test
14311 can check whether point is still within the region. The do-again-test
14312 should find the value of point and determine whether point is before,
14313 at, or after the value of the end of the region. We can use the
14314 @code{point} function to locate point. Clearly, we must pass the
14315 value of the end of the region to the recursive counting function as an
14316 argument.
14317
14318 In addition, the do-again-test should also test whether the search finds a
14319 word. If it does not, the function should not call itself again.
14320
14321 The next-step-expression changes a value so that when the recursive
14322 function is supposed to stop calling itself, it stops. More
14323 precisely, the next-step-expression changes a value so that at the
14324 right time, the do-again-test stops the recursive function from
14325 calling itself again. In this case, the next-step-expression can be
14326 the expression that moves point forward, word by word.
14327
14328 The third part of a recursive function is the recursive call.
14329
14330 Somewhere, also, we also need a part that does the `work' of the
14331 function, a part that does the counting. A vital part!
14332
14333 @need 1250
14334 But already, we have an outline of the recursive counting function:
14335
14336 @smallexample
14337 @group
14338 (defun recursive-count-words (region-end)
14339 "@var{documentation}@dots{}"
14340 @var{do-again-test}
14341 @var{next-step-expression}
14342 @var{recursive call})
14343 @end group
14344 @end smallexample
14345
14346 Now we need to fill in the slots. Let's start with the simplest cases
14347 first: if point is at or beyond the end of the region, there cannot
14348 be any words in the region, so the function should return zero.
14349 Likewise, if the search fails, there are no words to count, so the
14350 function should return zero.
14351
14352 On the other hand, if point is within the region and the search
14353 succeeds, the function should call itself again.
14354
14355 @need 800
14356 Thus, the do-again-test should look like this:
14357
14358 @smallexample
14359 @group
14360 (and (< (point) region-end)
14361 (re-search-forward "\\w+\\W*" region-end t))
14362 @end group
14363 @end smallexample
14364
14365 Note that the search expression is part of the do-again-test---the
14366 function returns @code{t} if its search succeeds and @code{nil} if it
14367 fails. (@xref{Whitespace Bug, , The Whitespace Bug in
14368 @code{@value{COUNT-WORDS}}}, for an explanation of how
14369 @code{re-search-forward} works.)
14370
14371 The do-again-test is the true-or-false test of an @code{if} clause.
14372 Clearly, if the do-again-test succeeds, the then-part of the @code{if}
14373 clause should call the function again; but if it fails, the else-part
14374 should return zero since either point is outside the region or the
14375 search failed because there were no words to find.
14376
14377 But before considering the recursive call, we need to consider the
14378 next-step-expression. What is it? Interestingly, it is the search
14379 part of the do-again-test.
14380
14381 In addition to returning @code{t} or @code{nil} for the
14382 do-again-test, @code{re-search-forward} moves point forward as a side
14383 effect of a successful search. This is the action that changes the
14384 value of point so that the recursive function stops calling itself
14385 when point completes its movement through the region. Consequently,
14386 the @code{re-search-forward} expression is the next-step-expression.
14387
14388 @need 1200
14389 In outline, then, the body of the @code{recursive-count-words}
14390 function looks like this:
14391
14392 @smallexample
14393 @group
14394 (if @var{do-again-test-and-next-step-combined}
14395 ;; @r{then}
14396 @var{recursive-call-returning-count}
14397 ;; @r{else}
14398 @var{return-zero})
14399 @end group
14400 @end smallexample
14401
14402 How to incorporate the mechanism that counts?
14403
14404 If you are not used to writing recursive functions, a question like
14405 this can be troublesome. But it can and should be approached
14406 systematically.
14407
14408 We know that the counting mechanism should be associated in some way
14409 with the recursive call. Indeed, since the next-step-expression moves
14410 point forward by one word, and since a recursive call is made for
14411 each word, the counting mechanism must be an expression that adds one
14412 to the value returned by a call to @code{recursive-count-words}.
14413
14414 @need 800
14415 Consider several cases:
14416
14417 @itemize @bullet
14418 @item
14419 If there are two words in the region, the function should return
14420 a value resulting from adding one to the value returned when it counts
14421 the first word, plus the number returned when it counts the remaining
14422 words in the region, which in this case is one.
14423
14424 @item
14425 If there is one word in the region, the function should return
14426 a value resulting from adding one to the value returned when it counts
14427 that word, plus the number returned when it counts the remaining
14428 words in the region, which in this case is zero.
14429
14430 @item
14431 If there are no words in the region, the function should return zero.
14432 @end itemize
14433
14434 From the sketch we can see that the else-part of the @code{if} returns
14435 zero for the case of no words. This means that the then-part of the
14436 @code{if} must return a value resulting from adding one to the value
14437 returned from a count of the remaining words.
14438
14439 @need 1200
14440 The expression will look like this, where @code{1+} is a function that
14441 adds one to its argument.
14442
14443 @smallexample
14444 (1+ (recursive-count-words region-end))
14445 @end smallexample
14446
14447 @need 1200
14448 The whole @code{recursive-count-words} function will then look like
14449 this:
14450
14451 @smallexample
14452 @group
14453 (defun recursive-count-words (region-end)
14454 "@var{documentation}@dots{}"
14455
14456 ;;; @r{1. do-again-test}
14457 (if (and (< (point) region-end)
14458 (re-search-forward "\\w+\\W*" region-end t))
14459 @end group
14460
14461 @group
14462 ;;; @r{2. then-part: the recursive call}
14463 (1+ (recursive-count-words region-end))
14464
14465 ;;; @r{3. else-part}
14466 0))
14467 @end group
14468 @end smallexample
14469
14470 @need 1250
14471 Let's examine how this works:
14472
14473 If there are no words in the region, the else part of the @code{if}
14474 expression is evaluated and consequently the function returns zero.
14475
14476 If there is one word in the region, the value of point is less than
14477 the value of @code{region-end} and the search succeeds. In this case,
14478 the true-or-false-test of the @code{if} expression tests true, and the
14479 then-part of the @code{if} expression is evaluated. The counting
14480 expression is evaluated. This expression returns a value (which will
14481 be the value returned by the whole function) that is the sum of one
14482 added to the value returned by a recursive call.
14483
14484 Meanwhile, the next-step-expression has caused point to jump over the
14485 first (and in this case only) word in the region. This means that
14486 when @code{(recursive-count-words region-end)} is evaluated a second
14487 time, as a result of the recursive call, the value of point will be
14488 equal to or greater than the value of region end. So this time,
14489 @code{recursive-count-words} will return zero. The zero will be added
14490 to one, and the original evaluation of @code{recursive-count-words}
14491 will return one plus zero, which is one, which is the correct amount.
14492
14493 Clearly, if there are two words in the region, the first call to
14494 @code{recursive-count-words} returns one added to the value returned
14495 by calling @code{recursive-count-words} on a region containing the
14496 remaining word---that is, it adds one to one, producing two, which is
14497 the correct amount.
14498
14499 Similarly, if there are three words in the region, the first call to
14500 @code{recursive-count-words} returns one added to the value returned
14501 by calling @code{recursive-count-words} on a region containing the
14502 remaining two words---and so on and so on.
14503
14504 @need 1250
14505 @noindent
14506 With full documentation the two functions look like this:
14507
14508 @need 1250
14509 @noindent
14510 The recursive function:
14511
14512 @findex recursive-count-words
14513 @smallexample
14514 @group
14515 (defun recursive-count-words (region-end)
14516 "Number of words between point and REGION-END."
14517 @end group
14518
14519 @group
14520 ;;; @r{1. do-again-test}
14521 (if (and (< (point) region-end)
14522 (re-search-forward "\\w+\\W*" region-end t))
14523 @end group
14524
14525 @group
14526 ;;; @r{2. then-part: the recursive call}
14527 (1+ (recursive-count-words region-end))
14528
14529 ;;; @r{3. else-part}
14530 0))
14531 @end group
14532 @end smallexample
14533
14534 @need 800
14535 @noindent
14536 The wrapper:
14537
14538 @smallexample
14539 @group
14540 ;;; @r{Recursive version}
14541 (defun @value{COUNT-WORDS} (beginning end)
14542 "Print number of words in the region.
14543 @end group
14544
14545 @group
14546 Words are defined as at least one word-constituent
14547 character followed by at least one character that is
14548 not a word-constituent. The buffer's syntax table
14549 determines which characters these are."
14550 @end group
14551 @group
14552 (interactive "r")
14553 (message "Counting words in region ... ")
14554 (save-excursion
14555 (goto-char beginning)
14556 (let ((count (recursive-count-words end)))
14557 @end group
14558 @group
14559 (cond ((zerop count)
14560 (message
14561 "The region does NOT have any words."))
14562 @end group
14563 @group
14564 ((= 1 count)
14565 (message "The region has 1 word."))
14566 (t
14567 (message
14568 "The region has %d words." count))))))
14569 @end group
14570 @end smallexample
14571
14572 @node Counting Exercise
14573 @section Exercise: Counting Punctuation
14574
14575 Using a @code{while} loop, write a function to count the number of
14576 punctuation marks in a region---period, comma, semicolon, colon,
14577 exclamation mark, and question mark. Do the same using recursion.
14578
14579 @node Words in a defun
14580 @chapter Counting Words in a @code{defun}
14581 @cindex Counting words in a @code{defun}
14582 @cindex Word counting in a @code{defun}
14583
14584 Our next project is to count the number of words in a function
14585 definition. Clearly, this can be done using some variant of
14586 @code{@value{COUNT-WORDS}}. @xref{Counting Words, , Counting Words:
14587 Repetition and Regexps}. If we are just going to count the words in
14588 one definition, it is easy enough to mark the definition with the
14589 @kbd{C-M-h} (@code{mark-defun}) command, and then call
14590 @code{@value{COUNT-WORDS}}.
14591
14592 However, I am more ambitious: I want to count the words and symbols in
14593 every definition in the Emacs sources and then print a graph that
14594 shows how many functions there are of each length: how many contain 40
14595 to 49 words or symbols, how many contain 50 to 59 words or symbols,
14596 and so on. I have often been curious how long a typical function is,
14597 and this will tell.
14598
14599 @menu
14600 * Divide and Conquer::
14601 * Words and Symbols:: What to count?
14602 * Syntax:: What constitutes a word or symbol?
14603 * count-words-in-defun:: Very like @code{@value{COUNT-WORDS}}.
14604 * Several defuns:: Counting several defuns in a file.
14605 * Find a File:: Do you want to look at a file?
14606 * lengths-list-file:: A list of the lengths of many definitions.
14607 * Several files:: Counting in definitions in different files.
14608 * Several files recursively:: Recursively counting in different files.
14609 * Prepare the data:: Prepare the data for display in a graph.
14610 @end menu
14611
14612 @ifnottex
14613 @node Divide and Conquer
14614 @unnumberedsec Divide and Conquer
14615 @end ifnottex
14616
14617 Described in one phrase, the histogram project is daunting; but
14618 divided into numerous small steps, each of which we can take one at a
14619 time, the project becomes less fearsome. Let us consider what the
14620 steps must be:
14621
14622 @itemize @bullet
14623 @item
14624 First, write a function to count the words in one definition. This
14625 includes the problem of handling symbols as well as words.
14626
14627 @item
14628 Second, write a function to list the numbers of words in each function
14629 in a file. This function can use the @code{count-words-in-defun}
14630 function.
14631
14632 @item
14633 Third, write a function to list the numbers of words in each function
14634 in each of several files. This entails automatically finding the
14635 various files, switching to them, and counting the words in the
14636 definitions within them.
14637
14638 @item
14639 Fourth, write a function to convert the list of numbers that we
14640 created in step three to a form that will be suitable for printing as
14641 a graph.
14642
14643 @item
14644 Fifth, write a function to print the results as a graph.
14645 @end itemize
14646
14647 This is quite a project! But if we take each step slowly, it will not
14648 be difficult.
14649
14650 @node Words and Symbols
14651 @section What to Count?
14652 @cindex Words and symbols in defun
14653
14654 When we first start thinking about how to count the words in a
14655 function definition, the first question is (or ought to be) what are
14656 we going to count? When we speak of `words' with respect to a Lisp
14657 function definition, we are actually speaking, in large part, of
14658 `symbols'. For example, the following @code{multiply-by-seven}
14659 function contains the five symbols @code{defun},
14660 @code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
14661 addition, in the documentation string, it contains the four words
14662 @samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
14663 symbol @samp{number} is repeated, so the definition contains a total
14664 of ten words and symbols.
14665
14666 @smallexample
14667 @group
14668 (defun multiply-by-seven (number)
14669 "Multiply NUMBER by seven."
14670 (* 7 number))
14671 @end group
14672 @end smallexample
14673
14674 @noindent
14675 However, if we mark the @code{multiply-by-seven} definition with
14676 @kbd{C-M-h} (@code{mark-defun}), and then call
14677 @code{@value{COUNT-WORDS}} on it, we will find that
14678 @code{@value{COUNT-WORDS}} claims the definition has eleven words, not
14679 ten! Something is wrong!
14680
14681 The problem is twofold: @code{@value{COUNT-WORDS}} does not count the
14682 @samp{*} as a word, and it counts the single symbol,
14683 @code{multiply-by-seven}, as containing three words. The hyphens are
14684 treated as if they were interword spaces rather than intraword
14685 connectors: @samp{multiply-by-seven} is counted as if it were written
14686 @samp{multiply by seven}.
14687
14688 The cause of this confusion is the regular expression search within
14689 the @code{@value{COUNT-WORDS}} definition that moves point forward word
14690 by word. In the canonical version of @code{@value{COUNT-WORDS}}, the
14691 regexp is:
14692
14693 @smallexample
14694 "\\w+\\W*"
14695 @end smallexample
14696
14697 @noindent
14698 This regular expression is a pattern defining one or more word
14699 constituent characters possibly followed by one or more characters
14700 that are not word constituents. What is meant by `word constituent
14701 characters' brings us to the issue of syntax, which is worth a section
14702 of its own.
14703
14704 @node Syntax
14705 @section What Constitutes a Word or Symbol?
14706 @cindex Syntax categories and tables
14707
14708 Emacs treats different characters as belonging to different
14709 @dfn{syntax categories}. For example, the regular expression,
14710 @samp{\\w+}, is a pattern specifying one or more @emph{word
14711 constituent} characters. Word constituent characters are members of
14712 one syntax category. Other syntax categories include the class of
14713 punctuation characters, such as the period and the comma, and the
14714 class of whitespace characters, such as the blank space and the tab
14715 character. (For more information, @pxref{Syntax Tables, , Syntax
14716 Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
14717
14718 Syntax tables specify which characters belong to which categories.
14719 Usually, a hyphen is not specified as a `word constituent character'.
14720 Instead, it is specified as being in the `class of characters that are
14721 part of symbol names but not words.' This means that the
14722 @code{@value{COUNT-WORDS}} function treats it in the same way it treats
14723 an interword white space, which is why @code{@value{COUNT-WORDS}}
14724 counts @samp{multiply-by-seven} as three words.
14725
14726 There are two ways to cause Emacs to count @samp{multiply-by-seven} as
14727 one symbol: modify the syntax table or modify the regular expression.
14728
14729 We could redefine a hyphen as a word constituent character by
14730 modifying the syntax table that Emacs keeps for each mode. This
14731 action would serve our purpose, except that a hyphen is merely the
14732 most common character within symbols that is not typically a word
14733 constituent character; there are others, too.
14734
14735 Alternatively, we can redefine the regexp used in the
14736 @code{@value{COUNT-WORDS}} definition so as to include symbols. This
14737 procedure has the merit of clarity, but the task is a little tricky.
14738
14739 @need 1200
14740 The first part is simple enough: the pattern must match ``at least one
14741 character that is a word or symbol constituent''. Thus:
14742
14743 @smallexample
14744 "\\(\\w\\|\\s_\\)+"
14745 @end smallexample
14746
14747 @noindent
14748 The @samp{\\(} is the first part of the grouping construct that
14749 includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
14750 by the @samp{\\|}. The @samp{\\w} matches any word-constituent
14751 character and the @samp{\\s_} matches any character that is part of a
14752 symbol name but not a word-constituent character. The @samp{+}
14753 following the group indicates that the word or symbol constituent
14754 characters must be matched at least once.
14755
14756 However, the second part of the regexp is more difficult to design.
14757 What we want is to follow the first part with ``optionally one or more
14758 characters that are not constituents of a word or symbol''. At first,
14759 I thought I could define this with the following:
14760
14761 @smallexample
14762 "\\(\\W\\|\\S_\\)*"
14763 @end smallexample
14764
14765 @noindent
14766 The upper case @samp{W} and @samp{S} match characters that are
14767 @emph{not} word or symbol constituents. Unfortunately, this
14768 expression matches any character that is either not a word constituent
14769 or not a symbol constituent. This matches any character!
14770
14771 I then noticed that every word or symbol in my test region was
14772 followed by white space (blank space, tab, or newline). So I tried
14773 placing a pattern to match one or more blank spaces after the pattern
14774 for one or more word or symbol constituents. This failed, too. Words
14775 and symbols are often separated by whitespace, but in actual code
14776 parentheses may follow symbols and punctuation may follow words. So
14777 finally, I designed a pattern in which the word or symbol constituents
14778 are followed optionally by characters that are not white space and
14779 then followed optionally by white space.
14780
14781 @need 800
14782 Here is the full regular expression:
14783
14784 @smallexample
14785 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14786 @end smallexample
14787
14788 @node count-words-in-defun
14789 @section The @code{count-words-in-defun} Function
14790 @cindex Counting words in a @code{defun}
14791
14792 We have seen that there are several ways to write a
14793 @code{count-words-region} function. To write a
14794 @code{count-words-in-defun}, we need merely adapt one of these
14795 versions.
14796
14797 The version that uses a @code{while} loop is easy to understand, so I
14798 am going to adapt that. Because @code{count-words-in-defun} will be
14799 part of a more complex program, it need not be interactive and it need
14800 not display a message but just return the count. These considerations
14801 simplify the definition a little.
14802
14803 On the other hand, @code{count-words-in-defun} will be used within a
14804 buffer that contains function definitions. Consequently, it is
14805 reasonable to ask that the function determine whether it is called
14806 when point is within a function definition, and if it is, to return
14807 the count for that definition. This adds complexity to the
14808 definition, but saves us from needing to pass arguments to the
14809 function.
14810
14811 @need 1250
14812 These considerations lead us to prepare the following template:
14813
14814 @smallexample
14815 @group
14816 (defun count-words-in-defun ()
14817 "@var{documentation}@dots{}"
14818 (@var{set up}@dots{}
14819 (@var{while loop}@dots{})
14820 @var{return count})
14821 @end group
14822 @end smallexample
14823
14824 @noindent
14825 As usual, our job is to fill in the slots.
14826
14827 First, the set up.
14828
14829 We are presuming that this function will be called within a buffer
14830 containing function definitions. Point will either be within a
14831 function definition or not. For @code{count-words-in-defun} to work,
14832 point must move to the beginning of the definition, a counter must
14833 start at zero, and the counting loop must stop when point reaches the
14834 end of the definition.
14835
14836 The @code{beginning-of-defun} function searches backwards for an
14837 opening delimiter such as a @samp{(} at the beginning of a line, and
14838 moves point to that position, or else to the limit of the search. In
14839 practice, this means that @code{beginning-of-defun} moves point to the
14840 beginning of an enclosing or preceding function definition, or else to
14841 the beginning of the buffer. We can use @code{beginning-of-defun} to
14842 place point where we wish to start.
14843
14844 The @code{while} loop requires a counter to keep track of the words or
14845 symbols being counted. A @code{let} expression can be used to create
14846 a local variable for this purpose, and bind it to an initial value of zero.
14847
14848 The @code{end-of-defun} function works like @code{beginning-of-defun}
14849 except that it moves point to the end of the definition.
14850 @code{end-of-defun} can be used as part of an expression that
14851 determines the position of the end of the definition.
14852
14853 The set up for @code{count-words-in-defun} takes shape rapidly: first
14854 we move point to the beginning of the definition, then we create a
14855 local variable to hold the count, and finally, we record the position
14856 of the end of the definition so the @code{while} loop will know when to stop
14857 looping.
14858
14859 @need 1250
14860 The code looks like this:
14861
14862 @smallexample
14863 @group
14864 (beginning-of-defun)
14865 (let ((count 0)
14866 (end (save-excursion (end-of-defun) (point))))
14867 @end group
14868 @end smallexample
14869
14870 @noindent
14871 The code is simple. The only slight complication is likely to concern
14872 @code{end}: it is bound to the position of the end of the definition
14873 by a @code{save-excursion} expression that returns the value of point
14874 after @code{end-of-defun} temporarily moves it to the end of the
14875 definition.
14876
14877 The second part of the @code{count-words-in-defun}, after the set up,
14878 is the @code{while} loop.
14879
14880 The loop must contain an expression that jumps point forward word by
14881 word and symbol by symbol, and another expression that counts the
14882 jumps. The true-or-false-test for the @code{while} loop should test
14883 true so long as point should jump forward, and false when point is at
14884 the end of the definition. We have already redefined the regular
14885 expression for this, so the loop is straightforward:
14886
14887 @smallexample
14888 @group
14889 (while (and (< (point) end)
14890 (re-search-forward
14891 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t))
14892 (setq count (1+ count)))
14893 @end group
14894 @end smallexample
14895
14896 The third part of the function definition returns the count of words
14897 and symbols. This part is the last expression within the body of the
14898 @code{let} expression, and can be, very simply, the local variable
14899 @code{count}, which when evaluated returns the count.
14900
14901 @need 1250
14902 Put together, the @code{count-words-in-defun} definition looks like this:
14903
14904 @findex count-words-in-defun
14905 @smallexample
14906 @group
14907 (defun count-words-in-defun ()
14908 "Return the number of words and symbols in a defun."
14909 (beginning-of-defun)
14910 (let ((count 0)
14911 (end (save-excursion (end-of-defun) (point))))
14912 @end group
14913 @group
14914 (while
14915 (and (< (point) end)
14916 (re-search-forward
14917 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14918 end t))
14919 (setq count (1+ count)))
14920 count))
14921 @end group
14922 @end smallexample
14923
14924 How to test this? The function is not interactive, but it is easy to
14925 put a wrapper around the function to make it interactive; we can use
14926 almost the same code as for the recursive version of
14927 @code{@value{COUNT-WORDS}}:
14928
14929 @smallexample
14930 @group
14931 ;;; @r{Interactive version.}
14932 (defun count-words-defun ()
14933 "Number of words and symbols in a function definition."
14934 (interactive)
14935 (message
14936 "Counting words and symbols in function definition ... ")
14937 @end group
14938 @group
14939 (let ((count (count-words-in-defun)))
14940 (cond
14941 ((zerop count)
14942 (message
14943 "The definition does NOT have any words or symbols."))
14944 @end group
14945 @group
14946 ((= 1 count)
14947 (message
14948 "The definition has 1 word or symbol."))
14949 (t
14950 (message
14951 "The definition has %d words or symbols." count)))))
14952 @end group
14953 @end smallexample
14954
14955 @need 800
14956 @noindent
14957 Let's re-use @kbd{C-c =} as a convenient keybinding:
14958
14959 @smallexample
14960 (global-set-key "\C-c=" 'count-words-defun)
14961 @end smallexample
14962
14963 Now we can try out @code{count-words-defun}: install both
14964 @code{count-words-in-defun} and @code{count-words-defun}, and set the
14965 keybinding, and then place the cursor within the following definition:
14966
14967 @smallexample
14968 @group
14969 (defun multiply-by-seven (number)
14970 "Multiply NUMBER by seven."
14971 (* 7 number))
14972 @result{} 10
14973 @end group
14974 @end smallexample
14975
14976 @noindent
14977 Success! The definition has 10 words and symbols.
14978
14979 The next problem is to count the numbers of words and symbols in
14980 several definitions within a single file.
14981
14982 @node Several defuns
14983 @section Count Several @code{defuns} Within a File
14984
14985 A file such as @file{simple.el} may have a hundred or more function
14986 definitions within it. Our long term goal is to collect statistics on
14987 many files, but as a first step, our immediate goal is to collect
14988 statistics on one file.
14989
14990 The information will be a series of numbers, each number being the
14991 length of a function definition. We can store the numbers in a list.
14992
14993 We know that we will want to incorporate the information regarding one
14994 file with information about many other files; this means that the
14995 function for counting definition lengths within one file need only
14996 return the list of lengths. It need not and should not display any
14997 messages.
14998
14999 The word count commands contain one expression to jump point forward
15000 word by word and another expression to count the jumps. The function
15001 to return the lengths of definitions can be designed to work the same
15002 way, with one expression to jump point forward definition by
15003 definition and another expression to construct the lengths' list.
15004
15005 This statement of the problem makes it elementary to write the
15006 function definition. Clearly, we will start the count at the
15007 beginning of the file, so the first command will be @code{(goto-char
15008 (point-min))}. Next, we start the @code{while} loop; and the
15009 true-or-false test of the loop can be a regular expression search for
15010 the next function definition---so long as the search succeeds, point
15011 is moved forward and then the body of the loop is evaluated. The body
15012 needs an expression that constructs the lengths' list. @code{cons},
15013 the list construction command, can be used to create the list. That
15014 is almost all there is to it.
15015
15016 @need 800
15017 Here is what this fragment of code looks like:
15018
15019 @smallexample
15020 @group
15021 (goto-char (point-min))
15022 (while (re-search-forward "^(defun" nil t)
15023 (setq lengths-list
15024 (cons (count-words-in-defun) lengths-list)))
15025 @end group
15026 @end smallexample
15027
15028 What we have left out is the mechanism for finding the file that
15029 contains the function definitions.
15030
15031 In previous examples, we either used this, the Info file, or we
15032 switched back and forth to some other buffer, such as the
15033 @file{*scratch*} buffer.
15034
15035 Finding a file is a new process that we have not yet discussed.
15036
15037 @node Find a File
15038 @section Find a File
15039 @cindex Find a File
15040
15041 To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
15042 command. This command is almost, but not quite right for the lengths
15043 problem.
15044
15045 @need 1200
15046 Let's look at the source for @code{find-file}:
15047
15048 @smallexample
15049 @group
15050 (defun find-file (filename)
15051 "Edit file FILENAME.
15052 Switch to a buffer visiting file FILENAME,
15053 creating one if none already exists."
15054 (interactive "FFind file: ")
15055 (switch-to-buffer (find-file-noselect filename)))
15056 @end group
15057 @end smallexample
15058
15059 @noindent
15060 (The most recent version of the @code{find-file} function definition
15061 permits you to specify optional wildcards to visit multiple files; that
15062 makes the definition more complex and we will not discuss it here,
15063 since it is not relevant. You can see its source using either
15064 @kbd{M-.} (@code{find-tag}) or @kbd{C-h f} (@code{describe-function}).)
15065
15066 @ignore
15067 In Emacs 22
15068 (defun find-file (filename &optional wildcards)
15069 "Edit file FILENAME.
15070 Switch to a buffer visiting file FILENAME,
15071 creating one if none already exists.
15072 Interactively, the default if you just type RET is the current directory,
15073 but the visited file name is available through the minibuffer history:
15074 type M-n to pull it into the minibuffer.
15075
15076 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
15077 expand wildcards (if any) and visit multiple files. You can
15078 suppress wildcard expansion by setting `find-file-wildcards' to nil.
15079
15080 To visit a file without any kind of conversion and without
15081 automatically choosing a major mode, use \\[find-file-literally]."
15082 (interactive (find-file-read-args "Find file: " nil))
15083 (let ((value (find-file-noselect filename nil nil wildcards)))
15084 (if (listp value)
15085 (mapcar 'switch-to-buffer (nreverse value))
15086 (switch-to-buffer value))))
15087 @end ignore
15088
15089 The definition I am showing possesses short but complete documentation
15090 and an interactive specification that prompts you for a file name when
15091 you use the command interactively. The body of the definition
15092 contains two functions, @code{find-file-noselect} and
15093 @code{switch-to-buffer}.
15094
15095 According to its documentation as shown by @kbd{C-h f} (the
15096 @code{describe-function} command), the @code{find-file-noselect}
15097 function reads the named file into a buffer and returns the buffer.
15098 (Its most recent version includes an optional wildcards argument,
15099 too, as well as another to read a file literally and an other you
15100 suppress warning messages. These optional arguments are irrelevant.)
15101
15102 However, the @code{find-file-noselect} function does not select the
15103 buffer in which it puts the file. Emacs does not switch its attention
15104 (or yours if you are using @code{find-file-noselect}) to the selected
15105 buffer. That is what @code{switch-to-buffer} does: it switches the
15106 buffer to which Emacs attention is directed; and it switches the
15107 buffer displayed in the window to the new buffer. We have discussed
15108 buffer switching elsewhere. (@xref{Switching Buffers}.)
15109
15110 In this histogram project, we do not need to display each file on the
15111 screen as the program determines the length of each definition within
15112 it. Instead of employing @code{switch-to-buffer}, we can work with
15113 @code{set-buffer}, which redirects the attention of the computer
15114 program to a different buffer but does not redisplay it on the screen.
15115 So instead of calling on @code{find-file} to do the job, we must write
15116 our own expression.
15117
15118 The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
15119
15120 @node lengths-list-file
15121 @section @code{lengths-list-file} in Detail
15122
15123 The core of the @code{lengths-list-file} function is a @code{while}
15124 loop containing a function to move point forward `defun by defun' and
15125 a function to count the number of words and symbols in each defun.
15126 This core must be surrounded by functions that do various other tasks,
15127 including finding the file, and ensuring that point starts out at the
15128 beginning of the file. The function definition looks like this:
15129 @findex lengths-list-file
15130
15131 @smallexample
15132 @group
15133 (defun lengths-list-file (filename)
15134 "Return list of definitions' lengths within FILE.
15135 The returned list is a list of numbers.
15136 Each number is the number of words or
15137 symbols in one function definition."
15138 @end group
15139 @group
15140 (message "Working on `%s' ... " filename)
15141 (save-excursion
15142 (let ((buffer (find-file-noselect filename))
15143 (lengths-list))
15144 (set-buffer buffer)
15145 (setq buffer-read-only t)
15146 (widen)
15147 (goto-char (point-min))
15148 (while (re-search-forward "^(defun" nil t)
15149 (setq lengths-list
15150 (cons (count-words-in-defun) lengths-list)))
15151 (kill-buffer buffer)
15152 lengths-list)))
15153 @end group
15154 @end smallexample
15155
15156 @noindent
15157 The function is passed one argument, the name of the file on which it
15158 will work. It has four lines of documentation, but no interactive
15159 specification. Since people worry that a computer is broken if they
15160 don't see anything going on, the first line of the body is a
15161 message.
15162
15163 The next line contains a @code{save-excursion} that returns Emacs's
15164 attention to the current buffer when the function completes. This is
15165 useful in case you embed this function in another function that
15166 presumes point is restored to the original buffer.
15167
15168 In the varlist of the @code{let} expression, Emacs finds the file and
15169 binds the local variable @code{buffer} to the buffer containing the
15170 file. At the same time, Emacs creates @code{lengths-list} as a local
15171 variable.
15172
15173 Next, Emacs switches its attention to the buffer.
15174
15175 In the following line, Emacs makes the buffer read-only. Ideally,
15176 this line is not necessary. None of the functions for counting words
15177 and symbols in a function definition should change the buffer.
15178 Besides, the buffer is not going to be saved, even if it were changed.
15179 This line is entirely the consequence of great, perhaps excessive,
15180 caution. The reason for the caution is that this function and those
15181 it calls work on the sources for Emacs and it is inconvenient if they
15182 are inadvertently modified. It goes without saying that I did not
15183 realize a need for this line until an experiment went awry and started
15184 to modify my Emacs source files @dots{}
15185
15186 Next comes a call to widen the buffer if it is narrowed. This
15187 function is usually not needed---Emacs creates a fresh buffer if none
15188 already exists; but if a buffer visiting the file already exists Emacs
15189 returns that one. In this case, the buffer may be narrowed and must
15190 be widened. If we wanted to be fully `user-friendly', we would
15191 arrange to save the restriction and the location of point, but we
15192 won't.
15193
15194 The @code{(goto-char (point-min))} expression moves point to the
15195 beginning of the buffer.
15196
15197 Then comes a @code{while} loop in which the `work' of the function is
15198 carried out. In the loop, Emacs determines the length of each
15199 definition and constructs a lengths' list containing the information.
15200
15201 Emacs kills the buffer after working through it. This is to save
15202 space inside of Emacs. My version of GNU Emacs 19 contained over 300
15203 source files of interest; GNU Emacs 22 contains over a thousand source
15204 files. Another function will apply @code{lengths-list-file} to each
15205 of the files.
15206
15207 Finally, the last expression within the @code{let} expression is the
15208 @code{lengths-list} variable; its value is returned as the value of
15209 the whole function.
15210
15211 You can try this function by installing it in the usual fashion. Then
15212 place your cursor after the following expression and type @kbd{C-x
15213 C-e} (@code{eval-last-sexp}).
15214
15215 @c !!! 22.1.1 lisp sources location here
15216 @smallexample
15217 (lengths-list-file
15218 "/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el")
15219 @end smallexample
15220
15221 @noindent
15222 (You may need to change the pathname of the file; the one here is for
15223 GNU Emacs version 22.1.1. To change the expression, copy it to
15224 the @file{*scratch*} buffer and edit it.
15225
15226 @need 1200
15227 @noindent
15228 (Also, to see the full length of the list, rather than a truncated
15229 version, you may have to evaluate the following:
15230
15231 @smallexample
15232 (custom-set-variables '(eval-expression-print-length nil))
15233 @end smallexample
15234
15235 @noindent
15236 (@xref{defcustom, , Specifying Variables using @code{defcustom}}.
15237 Then evaluate the @code{lengths-list-file} expression.)
15238
15239 @need 1200
15240 The lengths' list for @file{debug.el} takes less than a second to
15241 produce and looks like this in GNU Emacs 22:
15242
15243 @smallexample
15244 (83 113 105 144 289 22 30 97 48 89 25 52 52 88 28 29 77 49 43 290 232 587)
15245 @end smallexample
15246
15247 @need 1500
15248 (Using my old machine, the version 19 lengths' list for @file{debug.el}
15249 took seven seconds to produce and looked like this:
15250
15251 @smallexample
15252 (75 41 80 62 20 45 44 68 45 12 34 235)
15253 @end smallexample
15254
15255 (The newer version of @file{debug.el} contains more defuns than the
15256 earlier one; and my new machine is much faster than the old one.)
15257
15258 Note that the length of the last definition in the file is first in
15259 the list.
15260
15261 @node Several files
15262 @section Count Words in @code{defuns} in Different Files
15263
15264 In the previous section, we created a function that returns a list of
15265 the lengths of each definition in a file. Now, we want to define a
15266 function to return a master list of the lengths of the definitions in
15267 a list of files.
15268
15269 Working on each of a list of files is a repetitious act, so we can use
15270 either a @code{while} loop or recursion.
15271
15272 @menu
15273 * lengths-list-many-files:: Return a list of the lengths of defuns.
15274 * append:: Attach one list to another.
15275 @end menu
15276
15277 @ifnottex
15278 @node lengths-list-many-files
15279 @unnumberedsubsec Determine the lengths of @code{defuns}
15280 @end ifnottex
15281
15282 The design using a @code{while} loop is routine. The argument passed
15283 the function is a list of files. As we saw earlier (@pxref{Loop
15284 Example}), you can write a @code{while} loop so that the body of the
15285 loop is evaluated if such a list contains elements, but to exit the
15286 loop if the list is empty. For this design to work, the body of the
15287 loop must contain an expression that shortens the list each time the
15288 body is evaluated, so that eventually the list is empty. The usual
15289 technique is to set the value of the list to the value of the @sc{cdr}
15290 of the list each time the body is evaluated.
15291
15292 @need 800
15293 The template looks like this:
15294
15295 @smallexample
15296 @group
15297 (while @var{test-whether-list-is-empty}
15298 @var{body}@dots{}
15299 @var{set-list-to-cdr-of-list})
15300 @end group
15301 @end smallexample
15302
15303 Also, we remember that a @code{while} loop returns @code{nil} (the
15304 result of evaluating the true-or-false-test), not the result of any
15305 evaluation within its body. (The evaluations within the body of the
15306 loop are done for their side effects.) However, the expression that
15307 sets the lengths' list is part of the body---and that is the value
15308 that we want returned by the function as a whole. To do this, we
15309 enclose the @code{while} loop within a @code{let} expression, and
15310 arrange that the last element of the @code{let} expression contains
15311 the value of the lengths' list. (@xref{Incrementing Example, , Loop
15312 Example with an Incrementing Counter}.)
15313
15314 @findex lengths-list-many-files
15315 @need 1250
15316 These considerations lead us directly to the function itself:
15317
15318 @smallexample
15319 @group
15320 ;;; @r{Use @code{while} loop.}
15321 (defun lengths-list-many-files (list-of-files)
15322 "Return list of lengths of defuns in LIST-OF-FILES."
15323 @end group
15324 @group
15325 (let (lengths-list)
15326
15327 ;;; @r{true-or-false-test}
15328 (while list-of-files
15329 (setq lengths-list
15330 (append
15331 lengths-list
15332
15333 ;;; @r{Generate a lengths' list.}
15334 (lengths-list-file
15335 (expand-file-name (car list-of-files)))))
15336 @end group
15337
15338 @group
15339 ;;; @r{Make files' list shorter.}
15340 (setq list-of-files (cdr list-of-files)))
15341
15342 ;;; @r{Return final value of lengths' list.}
15343 lengths-list))
15344 @end group
15345 @end smallexample
15346
15347 @code{expand-file-name} is a built-in function that converts a file
15348 name to the absolute, long, path name form. The function employs the
15349 name of the directory in which the function is called.
15350
15351 @c !!! 22.1.1 lisp sources location here
15352 @need 1500
15353 Thus, if @code{expand-file-name} is called on @code{debug.el} when
15354 Emacs is visiting the
15355 @file{/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/} directory,
15356
15357 @smallexample
15358 debug.el
15359 @end smallexample
15360
15361 @need 800
15362 @noindent
15363 becomes
15364
15365 @c !!! 22.1.1 lisp sources location here
15366 @smallexample
15367 /usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el
15368 @end smallexample
15369
15370 The only other new element of this function definition is the as yet
15371 unstudied function @code{append}, which merits a short section for
15372 itself.
15373
15374 @node append
15375 @subsection The @code{append} Function
15376
15377 @need 800
15378 The @code{append} function attaches one list to another. Thus,
15379
15380 @smallexample
15381 (append '(1 2 3 4) '(5 6 7 8))
15382 @end smallexample
15383
15384 @need 800
15385 @noindent
15386 produces the list
15387
15388 @smallexample
15389 (1 2 3 4 5 6 7 8)
15390 @end smallexample
15391
15392 This is exactly how we want to attach two lengths' lists produced by
15393 @code{lengths-list-file} to each other. The results contrast with
15394 @code{cons},
15395
15396 @smallexample
15397 (cons '(1 2 3 4) '(5 6 7 8))
15398 @end smallexample
15399
15400 @need 1250
15401 @noindent
15402 which constructs a new list in which the first argument to @code{cons}
15403 becomes the first element of the new list:
15404
15405 @smallexample
15406 ((1 2 3 4) 5 6 7 8)
15407 @end smallexample
15408
15409 @node Several files recursively
15410 @section Recursively Count Words in Different Files
15411
15412 Besides a @code{while} loop, you can work on each of a list of files
15413 with recursion. A recursive version of @code{lengths-list-many-files}
15414 is short and simple.
15415
15416 The recursive function has the usual parts: the `do-again-test', the
15417 `next-step-expression', and the recursive call. The `do-again-test'
15418 determines whether the function should call itself again, which it
15419 will do if the @code{list-of-files} contains any remaining elements;
15420 the `next-step-expression' resets the @code{list-of-files} to the
15421 @sc{cdr} of itself, so eventually the list will be empty; and the
15422 recursive call calls itself on the shorter list. The complete
15423 function is shorter than this description!
15424 @findex recursive-lengths-list-many-files
15425
15426 @smallexample
15427 @group
15428 (defun recursive-lengths-list-many-files (list-of-files)
15429 "Return list of lengths of each defun in LIST-OF-FILES."
15430 (if list-of-files ; @r{do-again-test}
15431 (append
15432 (lengths-list-file
15433 (expand-file-name (car list-of-files)))
15434 (recursive-lengths-list-many-files
15435 (cdr list-of-files)))))
15436 @end group
15437 @end smallexample
15438
15439 @noindent
15440 In a sentence, the function returns the lengths' list for the first of
15441 the @code{list-of-files} appended to the result of calling itself on
15442 the rest of the @code{list-of-files}.
15443
15444 Here is a test of @code{recursive-lengths-list-many-files}, along with
15445 the results of running @code{lengths-list-file} on each of the files
15446 individually.
15447
15448 Install @code{recursive-lengths-list-many-files} and
15449 @code{lengths-list-file}, if necessary, and then evaluate the
15450 following expressions. You may need to change the files' pathnames;
15451 those here work when this Info file and the Emacs sources are located
15452 in their customary places. To change the expressions, copy them to
15453 the @file{*scratch*} buffer, edit them, and then evaluate them.
15454
15455 The results are shown after the @samp{@result{}}. (These results are
15456 for files from Emacs version 22.1.1; files from other versions of
15457 Emacs may produce different results.)
15458
15459 @c !!! 22.1.1 lisp sources location here
15460 @smallexample
15461 @group
15462 (cd "/usr/local/share/emacs/22.1.1/")
15463
15464 (lengths-list-file "./lisp/macros.el")
15465 @result{} (283 263 480 90)
15466 @end group
15467
15468 @group
15469 (lengths-list-file "./lisp/mail/mailalias.el")
15470 @result{} (38 32 29 95 178 180 321 218 324)
15471 @end group
15472
15473 @group
15474 (lengths-list-file "./lisp/makesum.el")
15475 @result{} (85 181)
15476 @end group
15477
15478 @group
15479 (recursive-lengths-list-many-files
15480 '("./lisp/macros.el"
15481 "./lisp/mail/mailalias.el"
15482 "./lisp/makesum.el"))
15483 @result{} (283 263 480 90 38 32 29 95 178 180 321 218 324 85 181)
15484 @end group
15485 @end smallexample
15486
15487 The @code{recursive-lengths-list-many-files} function produces the
15488 output we want.
15489
15490 The next step is to prepare the data in the list for display in a graph.
15491
15492 @node Prepare the data
15493 @section Prepare the Data for Display in a Graph
15494
15495 The @code{recursive-lengths-list-many-files} function returns a list
15496 of numbers. Each number records the length of a function definition.
15497 What we need to do now is transform this data into a list of numbers
15498 suitable for generating a graph. The new list will tell how many
15499 functions definitions contain less than 10 words and
15500 symbols, how many contain between 10 and 19 words and symbols, how
15501 many contain between 20 and 29 words and symbols, and so on.
15502
15503 In brief, we need to go through the lengths' list produced by the
15504 @code{recursive-lengths-list-many-files} function and count the number
15505 of defuns within each range of lengths, and produce a list of those
15506 numbers.
15507
15508 @menu
15509 * Data for Display in Detail::
15510 * Sorting:: Sorting lists.
15511 * Files List:: Making a list of files.
15512 * Counting function definitions::
15513 @end menu
15514
15515 @ifnottex
15516 @node Data for Display in Detail
15517 @unnumberedsubsec The Data for Display in Detail
15518 @end ifnottex
15519
15520 Based on what we have done before, we can readily foresee that it
15521 should not be too hard to write a function that `@sc{cdr}s' down the
15522 lengths' list, looks at each element, determines which length range it
15523 is in, and increments a counter for that range.
15524
15525 However, before beginning to write such a function, we should consider
15526 the advantages of sorting the lengths' list first, so the numbers are
15527 ordered from smallest to largest. First, sorting will make it easier
15528 to count the numbers in each range, since two adjacent numbers will
15529 either be in the same length range or in adjacent ranges. Second, by
15530 inspecting a sorted list, we can discover the highest and lowest
15531 number, and thereby determine the largest and smallest length range
15532 that we will need.
15533
15534 @node Sorting
15535 @subsection Sorting Lists
15536 @findex sort
15537
15538 Emacs contains a function to sort lists, called (as you might guess)
15539 @code{sort}. The @code{sort} function takes two arguments, the list
15540 to be sorted, and a predicate that determines whether the first of
15541 two list elements is ``less'' than the second.
15542
15543 As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
15544 Type Object as an Argument}), a predicate is a function that
15545 determines whether some property is true or false. The @code{sort}
15546 function will reorder a list according to whatever property the
15547 predicate uses; this means that @code{sort} can be used to sort
15548 non-numeric lists by non-numeric criteria---it can, for example,
15549 alphabetize a list.
15550
15551 @need 1250
15552 The @code{<} function is used when sorting a numeric list. For example,
15553
15554 @smallexample
15555 (sort '(4 8 21 17 33 7 21 7) '<)
15556 @end smallexample
15557
15558 @need 800
15559 @noindent
15560 produces this:
15561
15562 @smallexample
15563 (4 7 7 8 17 21 21 33)
15564 @end smallexample
15565
15566 @noindent
15567 (Note that in this example, both the arguments are quoted so that the
15568 symbols are not evaluated before being passed to @code{sort} as
15569 arguments.)
15570
15571 Sorting the list returned by the
15572 @code{recursive-lengths-list-many-files} function is straightforward;
15573 it uses the @code{<} function:
15574
15575 @ignore
15576 2006 Oct 29
15577 In GNU Emacs 22, eval
15578 (progn
15579 (cd "/usr/local/share/emacs/22.0.50/")
15580 (sort
15581 (recursive-lengths-list-many-files
15582 '("./lisp/macros.el"
15583 "./lisp/mail/mailalias.el"
15584 "./lisp/makesum.el"))
15585 '<))
15586
15587 @end ignore
15588
15589 @smallexample
15590 @group
15591 (sort
15592 (recursive-lengths-list-many-files
15593 '("./lisp/macros.el"
15594 "./lisp/mailalias.el"
15595 "./lisp/makesum.el"))
15596 '<)
15597 @end group
15598 @end smallexample
15599
15600 @need 800
15601 @noindent
15602 which produces:
15603
15604 @smallexample
15605 (29 32 38 85 90 95 178 180 181 218 263 283 321 324 480)
15606 @end smallexample
15607
15608 @noindent
15609 (Note that in this example, the first argument to @code{sort} is not
15610 quoted, since the expression must be evaluated so as to produce the
15611 list that is passed to @code{sort}.)
15612
15613 @node Files List
15614 @subsection Making a List of Files
15615
15616 The @code{recursive-lengths-list-many-files} function requires a list
15617 of files as its argument. For our test examples, we constructed such
15618 a list by hand; but the Emacs Lisp source directory is too large for
15619 us to do for that. Instead, we will write a function to do the job
15620 for us. In this function, we will use both a @code{while} loop and a
15621 recursive call.
15622
15623 @findex directory-files
15624 We did not have to write a function like this for older versions of
15625 GNU Emacs, since they placed all the @samp{.el} files in one
15626 directory. Instead, we were able to use the @code{directory-files}
15627 function, which lists the names of files that match a specified
15628 pattern within a single directory.
15629
15630 However, recent versions of Emacs place Emacs Lisp files in
15631 sub-directories of the top level @file{lisp} directory. This
15632 re-arrangement eases navigation. For example, all the mail related
15633 files are in a @file{lisp} sub-directory called @file{mail}. But at
15634 the same time, this arrangement forces us to create a file listing
15635 function that descends into the sub-directories.
15636
15637 @findex files-in-below-directory
15638 We can create this function, called @code{files-in-below-directory},
15639 using familiar functions such as @code{car}, @code{nthcdr}, and
15640 @code{substring} in conjunction with an existing function called
15641 @code{directory-files-and-attributes}. This latter function not only
15642 lists all the filenames in a directory, including the names
15643 of sub-directories, but also their attributes.
15644
15645 To restate our goal: to create a function that will enable us
15646 to feed filenames to @code{recursive-lengths-list-many-files}
15647 as a list that looks like this (but with more elements):
15648
15649 @smallexample
15650 @group
15651 ("./lisp/macros.el"
15652 "./lisp/mail/rmail.el"
15653 "./lisp/makesum.el")
15654 @end group
15655 @end smallexample
15656
15657 The @code{directory-files-and-attributes} function returns a list of
15658 lists. Each of the lists within the main list consists of 13
15659 elements. The first element is a string that contains the name of the
15660 file -- which, in GNU/Linux, may be a `directory file', that is to
15661 say, a file with the special attributes of a directory. The second
15662 element of the list is @code{t} for a directory, a string
15663 for symbolic link (the string is the name linked to), or @code{nil}.
15664
15665 For example, the first @samp{.el} file in the @file{lisp/} directory
15666 is @file{abbrev.el}. Its name is
15667 @file{/usr/local/share/emacs/22.1.1/lisp/abbrev.el} and it is not a
15668 directory or a symbolic link.
15669
15670 @need 1000
15671 This is how @code{directory-files-and-attributes} lists that file and
15672 its attributes:
15673
15674 @smallexample
15675 @group
15676 ("abbrev.el"
15677 nil
15678 1
15679 1000
15680 100
15681 @end group
15682 @group
15683 (17733 259)
15684 (17491 28834)
15685 (17596 62124)
15686 13157
15687 "-rw-rw-r--"
15688 @end group
15689 @group
15690 nil
15691 2971624
15692 773)
15693 @end group
15694 @end smallexample
15695
15696 @need 1200
15697 On the other hand, @file{mail/} is a directory within the @file{lisp/}
15698 directory. The beginning of its listing looks like this:
15699
15700 @smallexample
15701 @group
15702 ("mail"
15703 t
15704 @dots{}
15705 )
15706 @end group
15707 @end smallexample
15708
15709 (To learn about the different attributes, look at the documentation of
15710 @code{file-attributes}. Bear in mind that the @code{file-attributes}
15711 function does not list the filename, so its first element is
15712 @code{directory-files-and-attributes}'s second element.)
15713
15714 We will want our new function, @code{files-in-below-directory}, to
15715 list the @samp{.el} files in the directory it is told to check, and in
15716 any directories below that directory.
15717
15718 This gives us a hint on how to construct
15719 @code{files-in-below-directory}: within a directory, the function
15720 should add @samp{.el} filenames to a list; and if, within a directory,
15721 the function comes upon a sub-directory, it should go into that
15722 sub-directory and repeat its actions.
15723
15724 However, we should note that every directory contains a name that
15725 refers to itself, called @file{.}, (``dot'') and a name that refers to
15726 its parent directory, called @file{..} (``double dot''). (In
15727 @file{/}, the root directory, @file{..} refers to itself, since
15728 @file{/} has no parent.) Clearly, we do not want our
15729 @code{files-in-below-directory} function to enter those directories,
15730 since they always lead us, directly or indirectly, to the current
15731 directory.
15732
15733 Consequently, our @code{files-in-below-directory} function must do
15734 several tasks:
15735
15736 @itemize @bullet
15737 @item
15738 Check to see whether it is looking at a filename that ends in
15739 @samp{.el}; and if so, add its name to a list.
15740
15741 @item
15742 Check to see whether it is looking at a filename that is the name of a
15743 directory; and if so,
15744
15745 @itemize @minus
15746 @item
15747 Check to see whether it is looking at @file{.} or @file{..}; and if
15748 so skip it.
15749
15750 @item
15751 Or else, go into that directory and repeat the process.
15752 @end itemize
15753 @end itemize
15754
15755 Let's write a function definition to do these tasks. We will use a
15756 @code{while} loop to move from one filename to another within a
15757 directory, checking what needs to be done; and we will use a recursive
15758 call to repeat the actions on each sub-directory. The recursive
15759 pattern is `accumulate'
15760 (@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
15761 using @code{append} as the combiner.
15762
15763 @ignore
15764 (directory-files "/usr/local/src/emacs/lisp/" t "\\.el$")
15765 (shell-command "find /usr/local/src/emacs/lisp/ -name '*.el'")
15766
15767 (directory-files "/usr/local/share/emacs/22.1.1/lisp/" t "\\.el$")
15768 (shell-command "find /usr/local/share/emacs/22.1.1/lisp/ -name '*.el'")
15769 @end ignore
15770
15771 @c /usr/local/share/emacs/22.1.1/lisp/
15772
15773 @need 800
15774 Here is the function:
15775
15776 @smallexample
15777 @group
15778 (defun files-in-below-directory (directory)
15779 "List the .el files in DIRECTORY and in its sub-directories."
15780 ;; Although the function will be used non-interactively,
15781 ;; it will be easier to test if we make it interactive.
15782 ;; The directory will have a name such as
15783 ;; "/usr/local/share/emacs/22.1.1/lisp/"
15784 (interactive "DDirectory name: ")
15785 @end group
15786 @group
15787 (let (el-files-list
15788 (current-directory-list
15789 (directory-files-and-attributes directory t)))
15790 ;; while we are in the current directory
15791 (while current-directory-list
15792 @end group
15793 @group
15794 (cond
15795 ;; check to see whether filename ends in `.el'
15796 ;; and if so, append its name to a list.
15797 ((equal ".el" (substring (car (car current-directory-list)) -3))
15798 (setq el-files-list
15799 (cons (car (car current-directory-list)) el-files-list)))
15800 @end group
15801 @group
15802 ;; check whether filename is that of a directory
15803 ((eq t (car (cdr (car current-directory-list))))
15804 ;; decide whether to skip or recurse
15805 (if
15806 (equal "."
15807 (substring (car (car current-directory-list)) -1))
15808 ;; then do nothing since filename is that of
15809 ;; current directory or parent, "." or ".."
15810 ()
15811 @end group
15812 @group
15813 ;; else descend into the directory and repeat the process
15814 (setq el-files-list
15815 (append
15816 (files-in-below-directory
15817 (car (car current-directory-list)))
15818 el-files-list)))))
15819 ;; move to the next filename in the list; this also
15820 ;; shortens the list so the while loop eventually comes to an end
15821 (setq current-directory-list (cdr current-directory-list)))
15822 ;; return the filenames
15823 el-files-list))
15824 @end group
15825 @end smallexample
15826
15827 @c (files-in-below-directory "/usr/local/src/emacs/lisp/")
15828 @c (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15829
15830 The @code{files-in-below-directory} @code{directory-files} function
15831 takes one argument, the name of a directory.
15832
15833 @need 1250
15834 Thus, on my system,
15835
15836 @c (length (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15837
15838 @c !!! 22.1.1 lisp sources location here
15839 @smallexample
15840 @group
15841 (length
15842 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/"))
15843 @end group
15844 @end smallexample
15845
15846 @noindent
15847 tells me that in and below my Lisp sources directory are 1031
15848 @samp{.el} files.
15849
15850 @code{files-in-below-directory} returns a list in reverse alphabetical
15851 order. An expression to sort the list in alphabetical order looks
15852 like this:
15853
15854 @smallexample
15855 @group
15856 (sort
15857 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15858 'string-lessp)
15859 @end group
15860 @end smallexample
15861
15862 @ignore
15863 (defun test ()
15864 "Test how long it takes to find lengths of all sorted elisp defuns."
15865 (insert "\n" (current-time-string) "\n")
15866 (sit-for 0)
15867 (sort
15868 (recursive-lengths-list-many-files
15869 (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15870 '<)
15871 (insert (format "%s" (current-time-string))))
15872 @end ignore
15873
15874 @node Counting function definitions
15875 @subsection Counting function definitions
15876
15877 Our immediate goal is to generate a list that tells us how many
15878 function definitions contain fewer than 10 words and symbols, how many
15879 contain between 10 and 19 words and symbols, how many contain between
15880 20 and 29 words and symbols, and so on.
15881
15882 With a sorted list of numbers, this is easy: count how many elements
15883 of the list are smaller than 10, then, after moving past the numbers
15884 just counted, count how many are smaller than 20, then, after moving
15885 past the numbers just counted, count how many are smaller than 30, and
15886 so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
15887 larger than the top of that range. We can call the list of such
15888 numbers the @code{top-of-ranges} list.
15889
15890 @need 1200
15891 If we wished, we could generate this list automatically, but it is
15892 simpler to write a list manually. Here it is:
15893 @vindex top-of-ranges
15894
15895 @smallexample
15896 @group
15897 (defvar top-of-ranges
15898 '(10 20 30 40 50
15899 60 70 80 90 100
15900 110 120 130 140 150
15901 160 170 180 190 200
15902 210 220 230 240 250
15903 260 270 280 290 300)
15904 "List specifying ranges for `defuns-per-range'.")
15905 @end group
15906 @end smallexample
15907
15908 To change the ranges, we edit this list.
15909
15910 Next, we need to write the function that creates the list of the
15911 number of definitions within each range. Clearly, this function must
15912 take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15913 as arguments.
15914
15915 The @code{defuns-per-range} function must do two things again and
15916 again: it must count the number of definitions within a range
15917 specified by the current top-of-range value; and it must shift to the
15918 next higher value in the @code{top-of-ranges} list after counting the
15919 number of definitions in the current range. Since each of these
15920 actions is repetitive, we can use @code{while} loops for the job.
15921 One loop counts the number of definitions in the range defined by the
15922 current top-of-range value, and the other loop selects each of the
15923 top-of-range values in turn.
15924
15925 Several entries of the @code{sorted-lengths} list are counted for each
15926 range; this means that the loop for the @code{sorted-lengths} list
15927 will be inside the loop for the @code{top-of-ranges} list, like a
15928 small gear inside a big gear.
15929
15930 The inner loop counts the number of definitions within the range. It
15931 is a simple counting loop of the type we have seen before.
15932 (@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15933 The true-or-false test of the loop tests whether the value from the
15934 @code{sorted-lengths} list is smaller than the current value of the
15935 top of the range. If it is, the function increments the counter and
15936 tests the next value from the @code{sorted-lengths} list.
15937
15938 @need 1250
15939 The inner loop looks like this:
15940
15941 @smallexample
15942 @group
15943 (while @var{length-element-smaller-than-top-of-range}
15944 (setq number-within-range (1+ number-within-range))
15945 (setq sorted-lengths (cdr sorted-lengths)))
15946 @end group
15947 @end smallexample
15948
15949 The outer loop must start with the lowest value of the
15950 @code{top-of-ranges} list, and then be set to each of the succeeding
15951 higher values in turn. This can be done with a loop like this:
15952
15953 @smallexample
15954 @group
15955 (while top-of-ranges
15956 @var{body-of-loop}@dots{}
15957 (setq top-of-ranges (cdr top-of-ranges)))
15958 @end group
15959 @end smallexample
15960
15961 @need 1200
15962 Put together, the two loops look like this:
15963
15964 @smallexample
15965 @group
15966 (while top-of-ranges
15967
15968 ;; @r{Count the number of elements within the current range.}
15969 (while @var{length-element-smaller-than-top-of-range}
15970 (setq number-within-range (1+ number-within-range))
15971 (setq sorted-lengths (cdr sorted-lengths)))
15972
15973 ;; @r{Move to next range.}
15974 (setq top-of-ranges (cdr top-of-ranges)))
15975 @end group
15976 @end smallexample
15977
15978 In addition, in each circuit of the outer loop, Emacs should record
15979 the number of definitions within that range (the value of
15980 @code{number-within-range}) in a list. We can use @code{cons} for
15981 this purpose. (@xref{cons, , @code{cons}}.)
15982
15983 The @code{cons} function works fine, except that the list it
15984 constructs will contain the number of definitions for the highest
15985 range at its beginning and the number of definitions for the lowest
15986 range at its end. This is because @code{cons} attaches new elements
15987 of the list to the beginning of the list, and since the two loops are
15988 working their way through the lengths' list from the lower end first,
15989 the @code{defuns-per-range-list} will end up largest number first.
15990 But we will want to print our graph with smallest values first and the
15991 larger later. The solution is to reverse the order of the
15992 @code{defuns-per-range-list}. We can do this using the
15993 @code{nreverse} function, which reverses the order of a list.
15994 @findex nreverse
15995
15996 @need 800
15997 For example,
15998
15999 @smallexample
16000 (nreverse '(1 2 3 4))
16001 @end smallexample
16002
16003 @need 800
16004 @noindent
16005 produces:
16006
16007 @smallexample
16008 (4 3 2 1)
16009 @end smallexample
16010
16011 Note that the @code{nreverse} function is ``destructive''---that is,
16012 it changes the list to which it is applied; this contrasts with the
16013 @code{car} and @code{cdr} functions, which are non-destructive. In
16014 this case, we do not want the original @code{defuns-per-range-list},
16015 so it does not matter that it is destroyed. (The @code{reverse}
16016 function provides a reversed copy of a list, leaving the original list
16017 as is.)
16018 @findex reverse
16019
16020 @need 1250
16021 Put all together, the @code{defuns-per-range} looks like this:
16022
16023 @smallexample
16024 @group
16025 (defun defuns-per-range (sorted-lengths top-of-ranges)
16026 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
16027 (let ((top-of-range (car top-of-ranges))
16028 (number-within-range 0)
16029 defuns-per-range-list)
16030 @end group
16031
16032 @group
16033 ;; @r{Outer loop.}
16034 (while top-of-ranges
16035 @end group
16036
16037 @group
16038 ;; @r{Inner loop.}
16039 (while (and
16040 ;; @r{Need number for numeric test.}
16041 (car sorted-lengths)
16042 (< (car sorted-lengths) top-of-range))
16043 @end group
16044
16045 @group
16046 ;; @r{Count number of definitions within current range.}
16047 (setq number-within-range (1+ number-within-range))
16048 (setq sorted-lengths (cdr sorted-lengths)))
16049
16050 ;; @r{Exit inner loop but remain within outer loop.}
16051 @end group
16052
16053 @group
16054 (setq defuns-per-range-list
16055 (cons number-within-range defuns-per-range-list))
16056 (setq number-within-range 0) ; @r{Reset count to zero.}
16057 @end group
16058
16059 @group
16060 ;; @r{Move to next range.}
16061 (setq top-of-ranges (cdr top-of-ranges))
16062 ;; @r{Specify next top of range value.}
16063 (setq top-of-range (car top-of-ranges)))
16064 @end group
16065
16066 @group
16067 ;; @r{Exit outer loop and count the number of defuns larger than}
16068 ;; @r{ the largest top-of-range value.}
16069 (setq defuns-per-range-list
16070 (cons
16071 (length sorted-lengths)
16072 defuns-per-range-list))
16073 @end group
16074
16075 @group
16076 ;; @r{Return a list of the number of definitions within each range,}
16077 ;; @r{ smallest to largest.}
16078 (nreverse defuns-per-range-list)))
16079 @end group
16080 @end smallexample
16081
16082 @need 1200
16083 @noindent
16084 The function is straightforward except for one subtle feature. The
16085 true-or-false test of the inner loop looks like this:
16086
16087 @smallexample
16088 @group
16089 (and (car sorted-lengths)
16090 (< (car sorted-lengths) top-of-range))
16091 @end group
16092 @end smallexample
16093
16094 @need 800
16095 @noindent
16096 instead of like this:
16097
16098 @smallexample
16099 (< (car sorted-lengths) top-of-range)
16100 @end smallexample
16101
16102 The purpose of the test is to determine whether the first item in the
16103 @code{sorted-lengths} list is less than the value of the top of the
16104 range.
16105
16106 The simple version of the test works fine unless the
16107 @code{sorted-lengths} list has a @code{nil} value. In that case, the
16108 @code{(car sorted-lengths)} expression function returns
16109 @code{nil}. The @code{<} function cannot compare a number to
16110 @code{nil}, which is an empty list, so Emacs signals an error and
16111 stops the function from attempting to continue to execute.
16112
16113 The @code{sorted-lengths} list always becomes @code{nil} when the
16114 counter reaches the end of the list. This means that any attempt to
16115 use the @code{defuns-per-range} function with the simple version of
16116 the test will fail.
16117
16118 We solve the problem by using the @code{(car sorted-lengths)}
16119 expression in conjunction with the @code{and} expression. The
16120 @code{(car sorted-lengths)} expression returns a non-@code{nil}
16121 value so long as the list has at least one number within it, but
16122 returns @code{nil} if the list is empty. The @code{and} expression
16123 first evaluates the @code{(car sorted-lengths)} expression, and
16124 if it is @code{nil}, returns false @emph{without} evaluating the
16125 @code{<} expression. But if the @code{(car sorted-lengths)}
16126 expression returns a non-@code{nil} value, the @code{and} expression
16127 evaluates the @code{<} expression, and returns that value as the value
16128 of the @code{and} expression.
16129
16130 @c colon in printed section title causes problem in Info cross reference
16131 This way, we avoid an error.
16132 @iftex
16133 @noindent
16134 (For information about @code{and}, see
16135 @ref{kill-new function, , The @code{kill-new} function}.)
16136 @end iftex
16137 @ifinfo
16138 @noindent
16139 (@xref{kill-new function, , The @code{kill-new} function}, for
16140 information about @code{and}.)
16141 @end ifinfo
16142
16143 Here is a short test of the @code{defuns-per-range} function. First,
16144 evaluate the expression that binds (a shortened)
16145 @code{top-of-ranges} list to the list of values, then evaluate the
16146 expression for binding the @code{sorted-lengths} list, and then
16147 evaluate the @code{defuns-per-range} function.
16148
16149 @smallexample
16150 @group
16151 ;; @r{(Shorter list than we will use later.)}
16152 (setq top-of-ranges
16153 '(110 120 130 140 150
16154 160 170 180 190 200))
16155
16156 (setq sorted-lengths
16157 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
16158
16159 (defuns-per-range sorted-lengths top-of-ranges)
16160 @end group
16161 @end smallexample
16162
16163 @need 800
16164 @noindent
16165 The list returned looks like this:
16166
16167 @smallexample
16168 (2 2 2 0 0 1 0 2 0 0 4)
16169 @end smallexample
16170
16171 @noindent
16172 Indeed, there are two elements of the @code{sorted-lengths} list
16173 smaller than 110, two elements between 110 and 119, two elements
16174 between 120 and 129, and so on. There are four elements with a value
16175 of 200 or larger.
16176
16177 @c The next step is to turn this numbers' list into a graph.
16178 @node Readying a Graph
16179 @chapter Readying a Graph
16180 @cindex Readying a graph
16181 @cindex Graph prototype
16182 @cindex Prototype graph
16183 @cindex Body of graph
16184
16185 Our goal is to construct a graph showing the numbers of function
16186 definitions of various lengths in the Emacs lisp sources.
16187
16188 As a practical matter, if you were creating a graph, you would
16189 probably use a program such as @code{gnuplot} to do the job.
16190 (@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
16191 however, we create one from scratch, and in the process we will
16192 re-acquaint ourselves with some of what we learned before and learn
16193 more.
16194
16195 In this chapter, we will first write a simple graph printing function.
16196 This first definition will be a @dfn{prototype}, a rapidly written
16197 function that enables us to reconnoiter this unknown graph-making
16198 territory. We will discover dragons, or find that they are myth.
16199 After scouting the terrain, we will feel more confident and enhance
16200 the function to label the axes automatically.
16201
16202 @menu
16203 * Columns of a graph::
16204 * graph-body-print:: How to print the body of a graph.
16205 * recursive-graph-body-print::
16206 * Printed Axes::
16207 * Line Graph Exercise::
16208 @end menu
16209
16210 @ifnottex
16211 @node Columns of a graph
16212 @unnumberedsec Printing the Columns of a Graph
16213 @end ifnottex
16214
16215 Since Emacs is designed to be flexible and work with all kinds of
16216 terminals, including character-only terminals, the graph will need to
16217 be made from one of the `typewriter' symbols. An asterisk will do; as
16218 we enhance the graph-printing function, we can make the choice of
16219 symbol a user option.
16220
16221 We can call this function @code{graph-body-print}; it will take a
16222 @code{numbers-list} as its only argument. At this stage, we will not
16223 label the graph, but only print its body.
16224
16225 The @code{graph-body-print} function inserts a vertical column of
16226 asterisks for each element in the @code{numbers-list}. The height of
16227 each line is determined by the value of that element of the
16228 @code{numbers-list}.
16229
16230 Inserting columns is a repetitive act; that means that this function can
16231 be written either with a @code{while} loop or recursively.
16232
16233 Our first challenge is to discover how to print a column of asterisks.
16234 Usually, in Emacs, we print characters onto a screen horizontally,
16235 line by line, by typing. We have two routes we can follow: write our
16236 own column-insertion function or discover whether one exists in Emacs.
16237
16238 To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
16239 command. This command is like the @kbd{C-h a} (@code{command-apropos})
16240 command, except that the latter finds only those functions that are
16241 commands. The @kbd{M-x apropos} command lists all symbols that match
16242 a regular expression, including functions that are not interactive.
16243 @findex apropos
16244
16245 What we want to look for is some command that prints or inserts
16246 columns. Very likely, the name of the function will contain either
16247 the word `print' or the word `insert' or the word `column'.
16248 Therefore, we can simply type @kbd{M-x apropos RET
16249 print\|insert\|column RET} and look at the result. On my system, this
16250 command once too takes quite some time, and then produced a list of 79
16251 functions and variables. Now it does not take much time at all and
16252 produces a list of 211 functions and variables. Scanning down the
16253 list, the only function that looks as if it might do the job is
16254 @code{insert-rectangle}.
16255
16256 @need 1200
16257 Indeed, this is the function we want; its documentation says:
16258
16259 @smallexample
16260 @group
16261 insert-rectangle:
16262 Insert text of RECTANGLE with upper left corner at point.
16263 RECTANGLE's first line is inserted at point,
16264 its second line is inserted at a point vertically under point, etc.
16265 RECTANGLE should be a list of strings.
16266 After this command, the mark is at the upper left corner
16267 and point is at the lower right corner.
16268 @end group
16269 @end smallexample
16270
16271 We can run a quick test, to make sure it does what we expect of it.
16272
16273 Here is the result of placing the cursor after the
16274 @code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
16275 (@code{eval-last-sexp}). The function inserts the strings
16276 @samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
16277 point. Also the function returns @code{nil}.
16278
16279 @smallexample
16280 @group
16281 (insert-rectangle '("first" "second" "third"))first
16282 second
16283 thirdnil
16284 @end group
16285 @end smallexample
16286
16287 @noindent
16288 Of course, we won't be inserting the text of the
16289 @code{insert-rectangle} expression itself into the buffer in which we
16290 are making the graph, but will call the function from our program. We
16291 shall, however, have to make sure that point is in the buffer at the
16292 place where the @code{insert-rectangle} function will insert its
16293 column of strings.
16294
16295 If you are reading this in Info, you can see how this works by
16296 switching to another buffer, such as the @file{*scratch*} buffer,
16297 placing point somewhere in the buffer, typing @kbd{M-:}, typing the
16298 @code{insert-rectangle} expression into the minibuffer at the prompt,
16299 and then typing @key{RET}. This causes Emacs to evaluate the
16300 expression in the minibuffer, but to use as the value of point the
16301 position of point in the @file{*scratch*} buffer. (@kbd{M-:} is the
16302 keybinding for @code{eval-expression}. Also, @code{nil} does not
16303 appear in the @file{*scratch*} buffer since the expression is
16304 evaluated in the minibuffer.)
16305
16306 We find when we do this that point ends up at the end of the last
16307 inserted line---that is to say, this function moves point as a
16308 side-effect. If we were to repeat the command, with point at this
16309 position, the next insertion would be below and to the right of the
16310 previous insertion. We don't want this! If we are going to make a
16311 bar graph, the columns need to be beside each other.
16312
16313 So we discover that each cycle of the column-inserting @code{while}
16314 loop must reposition point to the place we want it, and that place
16315 will be at the top, not the bottom, of the column. Moreover, we
16316 remember that when we print a graph, we do not expect all the columns
16317 to be the same height. This means that the top of each column may be
16318 at a different height from the previous one. We cannot simply
16319 reposition point to the same line each time, but moved over to the
16320 right---or perhaps we can@dots{}
16321
16322 We are planning to make the columns of the bar graph out of asterisks.
16323 The number of asterisks in the column is the number specified by the
16324 current element of the @code{numbers-list}. We need to construct a
16325 list of asterisks of the right length for each call to
16326 @code{insert-rectangle}. If this list consists solely of the requisite
16327 number of asterisks, then we will have position point the right number
16328 of lines above the base for the graph to print correctly. This could
16329 be difficult.
16330
16331 Alternatively, if we can figure out some way to pass
16332 @code{insert-rectangle} a list of the same length each time, then we
16333 can place point on the same line each time, but move it over one
16334 column to the right for each new column. If we do this, however, some
16335 of the entries in the list passed to @code{insert-rectangle} must be
16336 blanks rather than asterisks. For example, if the maximum height of
16337 the graph is 5, but the height of the column is 3, then
16338 @code{insert-rectangle} requires an argument that looks like this:
16339
16340 @smallexample
16341 (" " " " "*" "*" "*")
16342 @end smallexample
16343
16344 This last proposal is not so difficult, so long as we can determine
16345 the column height. There are two ways for us to specify the column
16346 height: we can arbitrarily state what it will be, which would work
16347 fine for graphs of that height; or we can search through the list of
16348 numbers and use the maximum height of the list as the maximum height
16349 of the graph. If the latter operation were difficult, then the former
16350 procedure would be easiest, but there is a function built into Emacs
16351 that determines the maximum of its arguments. We can use that
16352 function. The function is called @code{max} and it returns the
16353 largest of all its arguments, which must be numbers. Thus, for
16354 example,
16355
16356 @smallexample
16357 (max 3 4 6 5 7 3)
16358 @end smallexample
16359
16360 @noindent
16361 returns 7. (A corresponding function called @code{min} returns the
16362 smallest of all its arguments.)
16363 @findex max
16364 @findex min
16365
16366 However, we cannot simply call @code{max} on the @code{numbers-list};
16367 the @code{max} function expects numbers as its argument, not a list of
16368 numbers. Thus, the following expression,
16369
16370 @smallexample
16371 (max '(3 4 6 5 7 3))
16372 @end smallexample
16373
16374 @need 800
16375 @noindent
16376 produces the following error message;
16377
16378 @smallexample
16379 Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
16380 @end smallexample
16381
16382 @findex apply
16383 We need a function that passes a list of arguments to a function.
16384 This function is @code{apply}. This function `applies' its first
16385 argument (a function) to its remaining arguments, the last of which
16386 may be a list.
16387
16388 @need 1250
16389 For example,
16390
16391 @smallexample
16392 (apply 'max 3 4 7 3 '(4 8 5))
16393 @end smallexample
16394
16395 @noindent
16396 returns 8.
16397
16398 (Incidentally, I don't know how you would learn of this function
16399 without a book such as this. It is possible to discover other
16400 functions, like @code{search-forward} or @code{insert-rectangle}, by
16401 guessing at a part of their names and then using @code{apropos}. Even
16402 though its base in metaphor is clear---`apply' its first argument to
16403 the rest---I doubt a novice would come up with that particular word
16404 when using @code{apropos} or other aid. Of course, I could be wrong;
16405 after all, the function was first named by someone who had to invent
16406 it.)
16407
16408 The second and subsequent arguments to @code{apply} are optional, so
16409 we can use @code{apply} to call a function and pass the elements of a
16410 list to it, like this, which also returns 8:
16411
16412 @smallexample
16413 (apply 'max '(4 8 5))
16414 @end smallexample
16415
16416 This latter way is how we will use @code{apply}. The
16417 @code{recursive-lengths-list-many-files} function returns a numbers'
16418 list to which we can apply @code{max} (we could also apply @code{max} to
16419 the sorted numbers' list; it does not matter whether the list is
16420 sorted or not.)
16421
16422 @need 800
16423 Hence, the operation for finding the maximum height of the graph is this:
16424
16425 @smallexample
16426 (setq max-graph-height (apply 'max numbers-list))
16427 @end smallexample
16428
16429 Now we can return to the question of how to create a list of strings
16430 for a column of the graph. Told the maximum height of the graph
16431 and the number of asterisks that should appear in the column, the
16432 function should return a list of strings for the
16433 @code{insert-rectangle} command to insert.
16434
16435 Each column is made up of asterisks or blanks. Since the function is
16436 passed the value of the height of the column and the number of
16437 asterisks in the column, the number of blanks can be found by
16438 subtracting the number of asterisks from the height of the column.
16439 Given the number of blanks and the number of asterisks, two
16440 @code{while} loops can be used to construct the list:
16441
16442 @smallexample
16443 @group
16444 ;;; @r{First version.}
16445 (defun column-of-graph (max-graph-height actual-height)
16446 "Return list of strings that is one column of a graph."
16447 (let ((insert-list nil)
16448 (number-of-top-blanks
16449 (- max-graph-height actual-height)))
16450 @end group
16451
16452 @group
16453 ;; @r{Fill in asterisks.}
16454 (while (> actual-height 0)
16455 (setq insert-list (cons "*" insert-list))
16456 (setq actual-height (1- actual-height)))
16457 @end group
16458
16459 @group
16460 ;; @r{Fill in blanks.}
16461 (while (> number-of-top-blanks 0)
16462 (setq insert-list (cons " " insert-list))
16463 (setq number-of-top-blanks
16464 (1- number-of-top-blanks)))
16465 @end group
16466
16467 @group
16468 ;; @r{Return whole list.}
16469 insert-list))
16470 @end group
16471 @end smallexample
16472
16473 If you install this function and then evaluate the following
16474 expression you will see that it returns the list as desired:
16475
16476 @smallexample
16477 (column-of-graph 5 3)
16478 @end smallexample
16479
16480 @need 800
16481 @noindent
16482 returns
16483
16484 @smallexample
16485 (" " " " "*" "*" "*")
16486 @end smallexample
16487
16488 As written, @code{column-of-graph} contains a major flaw: the symbols
16489 used for the blank and for the marked entries in the column are
16490 `hard-coded' as a space and asterisk. This is fine for a prototype,
16491 but you, or another user, may wish to use other symbols. For example,
16492 in testing the graph function, you many want to use a period in place
16493 of the space, to make sure the point is being repositioned properly
16494 each time the @code{insert-rectangle} function is called; or you might
16495 want to substitute a @samp{+} sign or other symbol for the asterisk.
16496 You might even want to make a graph-column that is more than one
16497 display column wide. The program should be more flexible. The way to
16498 do that is to replace the blank and the asterisk with two variables
16499 that we can call @code{graph-blank} and @code{graph-symbol} and define
16500 those variables separately.
16501
16502 Also, the documentation is not well written. These considerations
16503 lead us to the second version of the function:
16504
16505 @smallexample
16506 @group
16507 (defvar graph-symbol "*"
16508 "String used as symbol in graph, usually an asterisk.")
16509 @end group
16510
16511 @group
16512 (defvar graph-blank " "
16513 "String used as blank in graph, usually a blank space.
16514 graph-blank must be the same number of columns wide
16515 as graph-symbol.")
16516 @end group
16517 @end smallexample
16518
16519 @noindent
16520 (For an explanation of @code{defvar}, see
16521 @ref{defvar, , Initializing a Variable with @code{defvar}}.)
16522
16523 @smallexample
16524 @group
16525 ;;; @r{Second version.}
16526 (defun column-of-graph (max-graph-height actual-height)
16527 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
16528
16529 @end group
16530 @group
16531 The graph-symbols are contiguous entries at the end
16532 of the list.
16533 The list will be inserted as one column of a graph.
16534 The strings are either graph-blank or graph-symbol."
16535 @end group
16536
16537 @group
16538 (let ((insert-list nil)
16539 (number-of-top-blanks
16540 (- max-graph-height actual-height)))
16541 @end group
16542
16543 @group
16544 ;; @r{Fill in @code{graph-symbols}.}
16545 (while (> actual-height 0)
16546 (setq insert-list (cons graph-symbol insert-list))
16547 (setq actual-height (1- actual-height)))
16548 @end group
16549
16550 @group
16551 ;; @r{Fill in @code{graph-blanks}.}
16552 (while (> number-of-top-blanks 0)
16553 (setq insert-list (cons graph-blank insert-list))
16554 (setq number-of-top-blanks
16555 (1- number-of-top-blanks)))
16556
16557 ;; @r{Return whole list.}
16558 insert-list))
16559 @end group
16560 @end smallexample
16561
16562 If we wished, we could rewrite @code{column-of-graph} a third time to
16563 provide optionally for a line graph as well as for a bar graph. This
16564 would not be hard to do. One way to think of a line graph is that it
16565 is no more than a bar graph in which the part of each bar that is
16566 below the top is blank. To construct a column for a line graph, the
16567 function first constructs a list of blanks that is one shorter than
16568 the value, then it uses @code{cons} to attach a graph symbol to the
16569 list; then it uses @code{cons} again to attach the `top blanks' to
16570 the list.
16571
16572 It is easy to see how to write such a function, but since we don't
16573 need it, we will not do it. But the job could be done, and if it were
16574 done, it would be done with @code{column-of-graph}. Even more
16575 important, it is worth noting that few changes would have to be made
16576 anywhere else. The enhancement, if we ever wish to make it, is
16577 simple.
16578
16579 Now, finally, we come to our first actual graph printing function.
16580 This prints the body of a graph, not the labels for the vertical and
16581 horizontal axes, so we can call this @code{graph-body-print}.
16582
16583 @node graph-body-print
16584 @section The @code{graph-body-print} Function
16585 @findex graph-body-print
16586
16587 After our preparation in the preceding section, the
16588 @code{graph-body-print} function is straightforward. The function
16589 will print column after column of asterisks and blanks, using the
16590 elements of a numbers' list to specify the number of asterisks in each
16591 column. This is a repetitive act, which means we can use a
16592 decrementing @code{while} loop or recursive function for the job. In
16593 this section, we will write the definition using a @code{while} loop.
16594
16595 The @code{column-of-graph} function requires the height of the graph
16596 as an argument, so we should determine and record that as a local variable.
16597
16598 This leads us to the following template for the @code{while} loop
16599 version of this function:
16600
16601 @smallexample
16602 @group
16603 (defun graph-body-print (numbers-list)
16604 "@var{documentation}@dots{}"
16605 (let ((height @dots{}
16606 @dots{}))
16607 @end group
16608
16609 @group
16610 (while numbers-list
16611 @var{insert-columns-and-reposition-point}
16612 (setq numbers-list (cdr numbers-list)))))
16613 @end group
16614 @end smallexample
16615
16616 @noindent
16617 We need to fill in the slots of the template.
16618
16619 Clearly, we can use the @code{(apply 'max numbers-list)} expression to
16620 determine the height of the graph.
16621
16622 The @code{while} loop will cycle through the @code{numbers-list} one
16623 element at a time. As it is shortened by the @code{(setq numbers-list
16624 (cdr numbers-list))} expression, the @sc{car} of each instance of the
16625 list is the value of the argument for @code{column-of-graph}.
16626
16627 At each cycle of the @code{while} loop, the @code{insert-rectangle}
16628 function inserts the list returned by @code{column-of-graph}. Since
16629 the @code{insert-rectangle} function moves point to the lower right of
16630 the inserted rectangle, we need to save the location of point at the
16631 time the rectangle is inserted, move back to that position after the
16632 rectangle is inserted, and then move horizontally to the next place
16633 from which @code{insert-rectangle} is called.
16634
16635 If the inserted columns are one character wide, as they will be if
16636 single blanks and asterisks are used, the repositioning command is
16637 simply @code{(forward-char 1)}; however, the width of a column may be
16638 greater than one. This means that the repositioning command should be
16639 written @code{(forward-char symbol-width)}. The @code{symbol-width}
16640 itself is the length of a @code{graph-blank} and can be found using
16641 the expression @code{(length graph-blank)}. The best place to bind
16642 the @code{symbol-width} variable to the value of the width of graph
16643 column is in the varlist of the @code{let} expression.
16644
16645 @need 1250
16646 These considerations lead to the following function definition:
16647
16648 @smallexample
16649 @group
16650 (defun graph-body-print (numbers-list)
16651 "Print a bar graph of the NUMBERS-LIST.
16652 The numbers-list consists of the Y-axis values."
16653
16654 (let ((height (apply 'max numbers-list))
16655 (symbol-width (length graph-blank))
16656 from-position)
16657 @end group
16658
16659 @group
16660 (while numbers-list
16661 (setq from-position (point))
16662 (insert-rectangle
16663 (column-of-graph height (car numbers-list)))
16664 (goto-char from-position)
16665 (forward-char symbol-width)
16666 @end group
16667 @group
16668 ;; @r{Draw graph column by column.}
16669 (sit-for 0)
16670 (setq numbers-list (cdr numbers-list)))
16671 @end group
16672 @group
16673 ;; @r{Place point for X axis labels.}
16674 (forward-line height)
16675 (insert "\n")
16676 ))
16677 @end group
16678 @end smallexample
16679
16680 @noindent
16681 The one unexpected expression in this function is the
16682 @w{@code{(sit-for 0)}} expression in the @code{while} loop. This
16683 expression makes the graph printing operation more interesting to
16684 watch than it would be otherwise. The expression causes Emacs to
16685 `sit' or do nothing for a zero length of time and then redraw the
16686 screen. Placed here, it causes Emacs to redraw the screen column by
16687 column. Without it, Emacs would not redraw the screen until the
16688 function exits.
16689
16690 We can test @code{graph-body-print} with a short list of numbers.
16691
16692 @enumerate
16693 @item
16694 Install @code{graph-symbol}, @code{graph-blank},
16695 @code{column-of-graph}, which are in
16696 @iftex
16697 @ref{Readying a Graph, , Readying a Graph},
16698 @end iftex
16699 @ifinfo
16700 @ref{Columns of a graph},
16701 @end ifinfo
16702 and @code{graph-body-print}.
16703
16704 @need 800
16705 @item
16706 Copy the following expression:
16707
16708 @smallexample
16709 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
16710 @end smallexample
16711
16712 @item
16713 Switch to the @file{*scratch*} buffer and place the cursor where you
16714 want the graph to start.
16715
16716 @item
16717 Type @kbd{M-:} (@code{eval-expression}).
16718
16719 @item
16720 Yank the @code{graph-body-print} expression into the minibuffer
16721 with @kbd{C-y} (@code{yank)}.
16722
16723 @item
16724 Press @key{RET} to evaluate the @code{graph-body-print} expression.
16725 @end enumerate
16726
16727 @need 800
16728 Emacs will print a graph like this:
16729
16730 @smallexample
16731 @group
16732 *
16733 * **
16734 * ****
16735 *** ****
16736 ********* *
16737 ************
16738 *************
16739 @end group
16740 @end smallexample
16741
16742 @node recursive-graph-body-print
16743 @section The @code{recursive-graph-body-print} Function
16744 @findex recursive-graph-body-print
16745
16746 The @code{graph-body-print} function may also be written recursively.
16747 The recursive solution is divided into two parts: an outside `wrapper'
16748 that uses a @code{let} expression to determine the values of several
16749 variables that need only be found once, such as the maximum height of
16750 the graph, and an inside function that is called recursively to print
16751 the graph.
16752
16753 @need 1250
16754 The `wrapper' is uncomplicated:
16755
16756 @smallexample
16757 @group
16758 (defun recursive-graph-body-print (numbers-list)
16759 "Print a bar graph of the NUMBERS-LIST.
16760 The numbers-list consists of the Y-axis values."
16761 (let ((height (apply 'max numbers-list))
16762 (symbol-width (length graph-blank))
16763 from-position)
16764 (recursive-graph-body-print-internal
16765 numbers-list
16766 height
16767 symbol-width)))
16768 @end group
16769 @end smallexample
16770
16771 The recursive function is a little more difficult. It has four parts:
16772 the `do-again-test', the printing code, the recursive call, and the
16773 `next-step-expression'. The `do-again-test' is a @code{when}
16774 expression that determines whether the @code{numbers-list} contains
16775 any remaining elements; if it does, the function prints one column of
16776 the graph using the printing code and calls itself again. The
16777 function calls itself again according to the value produced by the
16778 `next-step-expression' which causes the call to act on a shorter
16779 version of the @code{numbers-list}.
16780
16781 @smallexample
16782 @group
16783 (defun recursive-graph-body-print-internal
16784 (numbers-list height symbol-width)
16785 "Print a bar graph.
16786 Used within recursive-graph-body-print function."
16787 @end group
16788
16789 @group
16790 (when numbers-list
16791 (setq from-position (point))
16792 (insert-rectangle
16793 (column-of-graph height (car numbers-list)))
16794 @end group
16795 @group
16796 (goto-char from-position)
16797 (forward-char symbol-width)
16798 (sit-for 0) ; @r{Draw graph column by column.}
16799 (recursive-graph-body-print-internal
16800 (cdr numbers-list) height symbol-width)))
16801 @end group
16802 @end smallexample
16803
16804 @need 1250
16805 After installation, this expression can be tested; here is a sample:
16806
16807 @smallexample
16808 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
16809 @end smallexample
16810
16811 @need 800
16812 Here is what @code{recursive-graph-body-print} produces:
16813
16814 @smallexample
16815 @group
16816 *
16817 ** *
16818 **** *
16819 **** ***
16820 * *********
16821 ************
16822 *************
16823 @end group
16824 @end smallexample
16825
16826 Either of these two functions, @code{graph-body-print} or
16827 @code{recursive-graph-body-print}, create the body of a graph.
16828
16829 @node Printed Axes
16830 @section Need for Printed Axes
16831
16832 A graph needs printed axes, so you can orient yourself. For a do-once
16833 project, it may be reasonable to draw the axes by hand using Emacs's
16834 Picture mode; but a graph drawing function may be used more than once.
16835
16836 For this reason, I have written enhancements to the basic
16837 @code{print-graph-body} function that automatically print labels for
16838 the horizontal and vertical axes. Since the label printing functions
16839 do not contain much new material, I have placed their description in
16840 an appendix. @xref{Full Graph, , A Graph with Labeled Axes}.
16841
16842 @node Line Graph Exercise
16843 @section Exercise
16844
16845 Write a line graph version of the graph printing functions.
16846
16847 @node Emacs Initialization
16848 @chapter Your @file{.emacs} File
16849 @cindex @file{.emacs} file
16850 @cindex Customizing your @file{.emacs} file
16851 @cindex Initialization file
16852
16853 ``You don't have to like Emacs to like it'' -- this seemingly
16854 paradoxical statement is the secret of GNU Emacs. The plain, `out of
16855 the box' Emacs is a generic tool. Most people who use it, customize
16856 it to suit themselves.
16857
16858 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
16859 expressions in Emacs Lisp you can change or extend Emacs.
16860
16861 @menu
16862 * Default Configuration::
16863 * Site-wide Init:: You can write site-wide init files.
16864 * defcustom:: Emacs will write code for you.
16865 * Beginning a .emacs File:: How to write a @code{.emacs file}.
16866 * Text and Auto-fill:: Automatically wrap lines.
16867 * Mail Aliases:: Use abbreviations for email addresses.
16868 * Indent Tabs Mode:: Don't use tabs with @TeX{}
16869 * Keybindings:: Create some personal keybindings.
16870 * Keymaps:: More about key binding.
16871 * Loading Files:: Load (i.e., evaluate) files automatically.
16872 * Autoload:: Make functions available.
16873 * Simple Extension:: Define a function; bind it to a key.
16874 * X11 Colors:: Colors in X.
16875 * Miscellaneous::
16876 * Mode Line:: How to customize your mode line.
16877 @end menu
16878
16879 @ifnottex
16880 @node Default Configuration
16881 @unnumberedsec Emacs's Default Configuration
16882 @end ifnottex
16883
16884 There are those who appreciate Emacs's default configuration. After
16885 all, Emacs starts you in C mode when you edit a C file, starts you in
16886 Fortran mode when you edit a Fortran file, and starts you in
16887 Fundamental mode when you edit an unadorned file. This all makes
16888 sense, if you do not know who is going to use Emacs. Who knows what a
16889 person hopes to do with an unadorned file? Fundamental mode is the
16890 right default for such a file, just as C mode is the right default for
16891 editing C code. (Enough programming languages have syntaxes
16892 that enable them to share or nearly share features, so C mode is
16893 now provided by CC mode, the `C Collection'.)
16894
16895 But when you do know who is going to use Emacs---you,
16896 yourself---then it makes sense to customize Emacs.
16897
16898 For example, I seldom want Fundamental mode when I edit an
16899 otherwise undistinguished file; I want Text mode. This is why I
16900 customize Emacs: so it suits me.
16901
16902 You can customize and extend Emacs by writing or adapting a
16903 @file{~/.emacs} file. This is your personal initialization file; its
16904 contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16905 may also add @file{.el} to @file{~/.emacs} and call it a
16906 @file{~/.emacs.el} file. In the past, you were forbidden to type the
16907 extra keystrokes that the name @file{~/.emacs.el} requires, but now
16908 you may. The new format is consistent with the Emacs Lisp file
16909 naming conventions; the old format saves typing.}
16910
16911 A @file{~/.emacs} file contains Emacs Lisp code. You can write this
16912 code yourself; or you can use Emacs's @code{customize} feature to write
16913 the code for you. You can combine your own expressions and
16914 auto-written Customize expressions in your @file{.emacs} file.
16915
16916 (I myself prefer to write my own expressions, except for those,
16917 particularly fonts, that I find easier to manipulate using the
16918 @code{customize} command. I combine the two methods.)
16919
16920 Most of this chapter is about writing expressions yourself. It
16921 describes a simple @file{.emacs} file; for more information, see
16922 @ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16923 @ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16924 Manual}.
16925
16926 @node Site-wide Init
16927 @section Site-wide Initialization Files
16928
16929 @cindex @file{default.el} init file
16930 @cindex @file{site-init.el} init file
16931 @cindex @file{site-load.el} init file
16932 In addition to your personal initialization file, Emacs automatically
16933 loads various site-wide initialization files, if they exist. These
16934 have the same form as your @file{.emacs} file, but are loaded by
16935 everyone.
16936
16937 Two site-wide initialization files, @file{site-load.el} and
16938 @file{site-init.el}, are loaded into Emacs and then `dumped' if a
16939 `dumped' version of Emacs is created, as is most common. (Dumped
16940 copies of Emacs load more quickly. However, once a file is loaded and
16941 dumped, a change to it does not lead to a change in Emacs unless you
16942 load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16943 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16944 @file{INSTALL} file.)
16945
16946 Three other site-wide initialization files are loaded automatically
16947 each time you start Emacs, if they exist. These are
16948 @file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16949 file, and @file{default.el}, and the terminal type file, which are both
16950 loaded @emph{after} your @file{.emacs} file.
16951
16952 Settings and definitions in your @file{.emacs} file will overwrite
16953 conflicting settings and definitions in a @file{site-start.el} file,
16954 if it exists; but the settings and definitions in a @file{default.el}
16955 or terminal type file will overwrite those in your @file{.emacs} file.
16956 (You can prevent interference from a terminal type file by setting
16957 @code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16958 Simple Extension}.)
16959
16960 @c Rewritten to avoid overfull hbox.
16961 The @file{INSTALL} file that comes in the distribution contains
16962 descriptions of the @file{site-init.el} and @file{site-load.el} files.
16963
16964 The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16965 control loading. These files are in the @file{lisp} directory of the
16966 Emacs distribution and are worth perusing.
16967
16968 The @file{loaddefs.el} file contains a good many suggestions as to
16969 what to put into your own @file{.emacs} file, or into a site-wide
16970 initialization file.
16971
16972 @node defcustom
16973 @section Specifying Variables using @code{defcustom}
16974 @findex defcustom
16975
16976 You can specify variables using @code{defcustom} so that you and
16977 others can then use Emacs's @code{customize} feature to set their
16978 values. (You cannot use @code{customize} to write function
16979 definitions; but you can write @code{defuns} in your @file{.emacs}
16980 file. Indeed, you can write any Lisp expression in your @file{.emacs}
16981 file.)
16982
16983 The @code{customize} feature depends on the @code{defcustom} special
16984 form. Although you can use @code{defvar} or @code{setq} for variables
16985 that users set, the @code{defcustom} special form is designed for the
16986 job.
16987
16988 You can use your knowledge of @code{defvar} for writing the
16989 first three arguments for @code{defcustom}. The first argument to
16990 @code{defcustom} is the name of the variable. The second argument is
16991 the variable's initial value, if any; and this value is set only if
16992 the value has not already been set. The third argument is the
16993 documentation.
16994
16995 The fourth and subsequent arguments to @code{defcustom} specify types
16996 and options; these are not featured in @code{defvar}. (These
16997 arguments are optional.)
16998
16999 Each of these arguments consists of a keyword followed by a value.
17000 Each keyword starts with the colon character @samp{:}.
17001
17002 @need 1250
17003 For example, the customizable user option variable
17004 @code{text-mode-hook} looks like this:
17005
17006 @smallexample
17007 @group
17008 (defcustom text-mode-hook nil
17009 "Normal hook run when entering Text mode and many related modes."
17010 :type 'hook
17011 :options '(turn-on-auto-fill flyspell-mode)
17012 :group 'data)
17013 @end group
17014 @end smallexample
17015
17016 @noindent
17017 The name of the variable is @code{text-mode-hook}; it has no default
17018 value; and its documentation string tells you what it does.
17019
17020 The @code{:type} keyword tells Emacs the kind of data to which
17021 @code{text-mode-hook} should be set and how to display the value in a
17022 Customization buffer.
17023
17024 The @code{:options} keyword specifies a suggested list of values for
17025 the variable. Usually, @code{:options} applies to a hook.
17026 The list is only a suggestion; it is not exclusive; a person who sets
17027 the variable may set it to other values; the list shown following the
17028 @code{:options} keyword is intended to offer convenient choices to a
17029 user.
17030
17031 Finally, the @code{:group} keyword tells the Emacs Customization
17032 command in which group the variable is located. This tells where to
17033 find it.
17034
17035 The @code{defcustom} function recognizes more than a dozen keywords.
17036 For more information, see @ref{Customization, , Writing Customization
17037 Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
17038
17039 Consider @code{text-mode-hook} as an example.
17040
17041 There are two ways to customize this variable. You can use the
17042 customization command or write the appropriate expressions yourself.
17043
17044 @need 800
17045 Using the customization command, you can type:
17046
17047 @smallexample
17048 M-x customize
17049 @end smallexample
17050
17051 @noindent
17052 and find that the group for editing files of data is called `data'.
17053 Enter that group. Text Mode Hook is the first member. You can click
17054 on its various options, such as @code{turn-on-auto-fill}, to set the
17055 values. After you click on the button to
17056
17057 @smallexample
17058 Save for Future Sessions
17059 @end smallexample
17060
17061 @noindent
17062 Emacs will write an expression into your @file{.emacs} file.
17063 It will look like this:
17064
17065 @smallexample
17066 @group
17067 (custom-set-variables
17068 ;; custom-set-variables was added by Custom.
17069 ;; If you edit it by hand, you could mess it up, so be careful.
17070 ;; Your init file should contain only one such instance.
17071 ;; If there is more than one, they won't work right.
17072 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
17073 @end group
17074 @end smallexample
17075
17076 @noindent
17077 (The @code{text-mode-hook-identify} function tells
17078 @code{toggle-text-mode-auto-fill} which buffers are in Text mode.
17079 It comes on automatically.)
17080
17081 The @code{custom-set-variables} function works somewhat differently
17082 than a @code{setq}. While I have never learned the differences, I
17083 modify the @code{custom-set-variables} expressions in my @file{.emacs}
17084 file by hand: I make the changes in what appears to me to be a
17085 reasonable manner and have not had any problems. Others prefer to use
17086 the Customization command and let Emacs do the work for them.
17087
17088 Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
17089 This function sets the various font faces. Over time, I have set a
17090 considerable number of faces. Some of the time, I re-set them using
17091 @code{customize}; other times, I simply edit the
17092 @code{custom-set-faces} expression in my @file{.emacs} file itself.
17093
17094 The second way to customize your @code{text-mode-hook} is to set it
17095 yourself in your @file{.emacs} file using code that has nothing to do
17096 with the @code{custom-set-@dots{}} functions.
17097
17098 @need 800
17099 When you do this, and later use @code{customize}, you will see a
17100 message that says
17101
17102 @smallexample
17103 CHANGED outside Customize; operating on it here may be unreliable.
17104 @end smallexample
17105
17106 @need 800
17107 This message is only a warning. If you click on the button to
17108
17109 @smallexample
17110 Save for Future Sessions
17111 @end smallexample
17112
17113 @noindent
17114 Emacs will write a @code{custom-set-@dots{}} expression near the end
17115 of your @file{.emacs} file that will be evaluated after your
17116 hand-written expression. It will, therefore, overrule your
17117 hand-written expression. No harm will be done. When you do this,
17118 however, be careful to remember which expression is active; if you
17119 forget, you may confuse yourself.
17120
17121 So long as you remember where the values are set, you will have no
17122 trouble. In any event, the values are always set in your
17123 initialization file, which is usually called @file{.emacs}.
17124
17125 I myself use @code{customize} for hardly anything. Mostly, I write
17126 expressions myself.
17127
17128 @findex defsubst
17129 @findex defconst
17130 Incidentally, to be more complete concerning defines: @code{defsubst}
17131 defines an inline function. The syntax is just like that of
17132 @code{defun}. @code{defconst} defines a symbol as a constant. The
17133 intent is that neither programs nor users should ever change a value
17134 set by @code{defconst}. (You can change it; the value set is a
17135 variable; but please do not.)
17136
17137 @node Beginning a .emacs File
17138 @section Beginning a @file{.emacs} File
17139 @cindex @file{.emacs} file, beginning of
17140
17141 When you start Emacs, it loads your @file{.emacs} file unless you tell
17142 it not to by specifying @samp{-q} on the command line. (The
17143 @code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
17144
17145 A @file{.emacs} file contains Lisp expressions. Often, these are no
17146 more than expressions to set values; sometimes they are function
17147 definitions.
17148
17149 @xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
17150 Manual}, for a short description of initialization files.
17151
17152 This chapter goes over some of the same ground, but is a walk among
17153 extracts from a complete, long-used @file{.emacs} file---my own.
17154
17155 The first part of the file consists of comments: reminders to myself.
17156 By now, of course, I remember these things, but when I started, I did
17157 not.
17158
17159 @need 1200
17160 @smallexample
17161 @group
17162 ;;;; Bob's .emacs file
17163 ; Robert J. Chassell
17164 ; 26 September 1985
17165 @end group
17166 @end smallexample
17167
17168 @noindent
17169 Look at that date! I started this file a long time ago. I have been
17170 adding to it ever since.
17171
17172 @smallexample
17173 @group
17174 ; Each section in this file is introduced by a
17175 ; line beginning with four semicolons; and each
17176 ; entry is introduced by a line beginning with
17177 ; three semicolons.
17178 @end group
17179 @end smallexample
17180
17181 @noindent
17182 This describes the usual conventions for comments in Emacs Lisp.
17183 Everything on a line that follows a semicolon is a comment. Two,
17184 three, and four semicolons are used as subsection and section markers.
17185 (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference Manual}, for
17186 more about comments.)
17187
17188 @smallexample
17189 @group
17190 ;;;; The Help Key
17191 ; Control-h is the help key;
17192 ; after typing control-h, type a letter to
17193 ; indicate the subject about which you want help.
17194 ; For an explanation of the help facility,
17195 ; type control-h two times in a row.
17196 @end group
17197 @end smallexample
17198
17199 @noindent
17200 Just remember: type @kbd{C-h} two times for help.
17201
17202 @smallexample
17203 @group
17204 ; To find out about any mode, type control-h m
17205 ; while in that mode. For example, to find out
17206 ; about mail mode, enter mail mode and then type
17207 ; control-h m.
17208 @end group
17209 @end smallexample
17210
17211 @noindent
17212 `Mode help', as I call this, is very helpful. Usually, it tells you
17213 all you need to know.
17214
17215 Of course, you don't need to include comments like these in your
17216 @file{.emacs} file. I included them in mine because I kept forgetting
17217 about Mode help or the conventions for comments---but I was able to
17218 remember to look here to remind myself.
17219
17220 @node Text and Auto-fill
17221 @section Text and Auto Fill Mode
17222
17223 Now we come to the part that `turns on' Text mode and
17224 Auto Fill mode.
17225
17226 @smallexample
17227 @group
17228 ;;; Text mode and Auto Fill mode
17229 ;; The next two lines put Emacs into Text mode
17230 ;; and Auto Fill mode, and are for writers who
17231 ;; want to start writing prose rather than code.
17232 (setq-default major-mode 'text-mode)
17233 (add-hook 'text-mode-hook 'turn-on-auto-fill)
17234 @end group
17235 @end smallexample
17236
17237 Here is the first part of this @file{.emacs} file that does something
17238 besides remind a forgetful human!
17239
17240 The first of the two lines in parentheses tells Emacs to turn on Text
17241 mode when you find a file, @emph{unless} that file should go into some
17242 other mode, such as C mode.
17243
17244 @cindex Per-buffer, local variables list
17245 @cindex Local variables list, per-buffer,
17246 @cindex Automatic mode selection
17247 @cindex Mode selection, automatic
17248 When Emacs reads a file, it looks at the extension to the file name,
17249 if any. (The extension is the part that comes after a @samp{.}.) If
17250 the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
17251 on C mode. Also, Emacs looks at first nonblank line of the file; if
17252 the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
17253 possesses a list of extensions and specifications that it uses
17254 automatically. In addition, Emacs looks near the last page for a
17255 per-buffer, ``local variables list'', if any.
17256
17257 @ifinfo
17258 @xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
17259 Emacs Manual}.
17260
17261 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17262 Manual}.
17263 @end ifinfo
17264 @iftex
17265 See sections ``How Major Modes are Chosen'' and ``Local Variables in
17266 Files'' in @cite{The GNU Emacs Manual}.
17267 @end iftex
17268
17269 Now, back to the @file{.emacs} file.
17270
17271 @need 800
17272 Here is the line again; how does it work?
17273
17274 @cindex Text Mode turned on
17275 @smallexample
17276 (setq major-mode 'text-mode)
17277 @end smallexample
17278
17279 @noindent
17280 This line is a short, but complete Emacs Lisp expression.
17281
17282 We are already familiar with @code{setq}. It sets the following variable,
17283 @code{major-mode}, to the subsequent value, which is @code{text-mode}.
17284 The single quote mark before @code{text-mode} tells Emacs to deal directly
17285 with the @code{text-mode} symbol, not with whatever it might stand for.
17286 @xref{set & setq, , Setting the Value of a Variable},
17287 for a reminder of how @code{setq} works.
17288 The main point is that there is no difference between the procedure you
17289 use to set a value in your @file{.emacs} file and the procedure you use
17290 anywhere else in Emacs.
17291
17292 @need 800
17293 Here is the next line:
17294
17295 @cindex Auto Fill mode turned on
17296 @findex add-hook
17297 @smallexample
17298 (add-hook 'text-mode-hook 'turn-on-auto-fill)
17299 @end smallexample
17300
17301 @noindent
17302 In this line, the @code{add-hook} command adds
17303 @code{turn-on-auto-fill} to the variable.
17304
17305 @code{turn-on-auto-fill} is the name of a program, that, you guessed
17306 it!, turns on Auto Fill mode.
17307
17308 Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
17309 onto Text mode. So every time Emacs turns on Text mode, Emacs also
17310 turns on Auto Fill mode.
17311
17312 In brief, the first line causes Emacs to enter Text mode when you edit a
17313 file, unless the file name extension, a first non-blank line, or local
17314 variables to tell Emacs otherwise.
17315
17316 Text mode among other actions, sets the syntax table to work
17317 conveniently for writers. In Text mode, Emacs considers an apostrophe
17318 as part of a word like a letter; but Emacs does not consider a period
17319 or a space as part of a word. Thus, @kbd{M-f} moves you over
17320 @samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
17321 the @samp{t} of @samp{it's}.
17322
17323 The second line causes Emacs to turn on Auto Fill mode when it turns
17324 on Text mode. In Auto Fill mode, Emacs automatically breaks a line
17325 that is too wide and brings the excessively wide part of the line down
17326 to the next line. Emacs breaks lines between words, not within them.
17327
17328 When Auto Fill mode is turned off, lines continue to the right as you
17329 type them. Depending on how you set the value of
17330 @code{truncate-lines}, the words you type either disappear off the
17331 right side of the screen, or else are shown, in a rather ugly and
17332 unreadable manner, as a continuation line on the screen.
17333
17334 @need 1250
17335 In addition, in this part of my @file{.emacs} file, I tell the Emacs
17336 fill commands to insert two spaces after a colon:
17337
17338 @smallexample
17339 (setq colon-double-space t)
17340 @end smallexample
17341
17342 @node Mail Aliases
17343 @section Mail Aliases
17344
17345 Here is a @code{setq} that `turns on' mail aliases, along with more
17346 reminders.
17347
17348 @smallexample
17349 @group
17350 ;;; Mail mode
17351 ; To enter mail mode, type `C-x m'
17352 ; To enter RMAIL (for reading mail),
17353 ; type `M-x rmail'
17354 (setq mail-aliases t)
17355 @end group
17356 @end smallexample
17357
17358 @cindex Mail aliases
17359 @noindent
17360 This @code{setq} command sets the value of the variable
17361 @code{mail-aliases} to @code{t}. Since @code{t} means true, the line
17362 says, in effect, ``Yes, use mail aliases.''
17363
17364 Mail aliases are convenient short names for long email addresses or
17365 for lists of email addresses. The file where you keep your `aliases'
17366 is @file{~/.mailrc}. You write an alias like this:
17367
17368 @smallexample
17369 alias geo george@@foobar.wiz.edu
17370 @end smallexample
17371
17372 @noindent
17373 When you write a message to George, address it to @samp{geo}; the
17374 mailer will automatically expand @samp{geo} to the full address.
17375
17376 @node Indent Tabs Mode
17377 @section Indent Tabs Mode
17378 @cindex Tabs, preventing
17379 @findex indent-tabs-mode
17380
17381 By default, Emacs inserts tabs in place of multiple spaces when it
17382 formats a region. (For example, you might indent many lines of text
17383 all at once with the @code{indent-region} command.) Tabs look fine on
17384 a terminal or with ordinary printing, but they produce badly indented
17385 output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
17386
17387 @need 1250
17388 The following turns off Indent Tabs mode:
17389
17390 @smallexample
17391 @group
17392 ;;; Prevent Extraneous Tabs
17393 (setq-default indent-tabs-mode nil)
17394 @end group
17395 @end smallexample
17396
17397 Note that this line uses @code{setq-default} rather than the
17398 @code{setq} command that we have seen before. The @code{setq-default}
17399 command sets values only in buffers that do not have their own local
17400 values for the variable.
17401
17402 @ifinfo
17403 @xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
17404
17405 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17406 Manual}.
17407 @end ifinfo
17408 @iftex
17409 See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
17410 Files'' in @cite{The GNU Emacs Manual}.
17411 @end iftex
17412
17413 @need 1700
17414 @node Keybindings
17415 @section Some Keybindings
17416
17417 Now for some personal keybindings:
17418
17419 @smallexample
17420 @group
17421 ;;; Compare windows
17422 (global-set-key "\C-cw" 'compare-windows)
17423 @end group
17424 @end smallexample
17425
17426 @findex compare-windows
17427 @code{compare-windows} is a nifty command that compares the text in
17428 your current window with text in the next window. It makes the
17429 comparison by starting at point in each window, moving over text in
17430 each window as far as they match. I use this command all the time.
17431
17432 This also shows how to set a key globally, for all modes.
17433
17434 @cindex Setting a key globally
17435 @cindex Global set key
17436 @cindex Key setting globally
17437 @findex global-set-key
17438 The command is @code{global-set-key}. It is followed by the
17439 keybinding. In a @file{.emacs} file, the keybinding is written as
17440 shown: @code{\C-c} stands for `control-c', which means `press the
17441 control key and the @key{c} key at the same time'. The @code{w} means
17442 `press the @key{w} key'. The keybinding is surrounded by double
17443 quotation marks. In documentation, you would write this as
17444 @w{@kbd{C-c w}}. (If you were binding a @key{META} key, such as
17445 @kbd{M-c}, rather than a @key{CTRL} key, you would write
17446 @w{@code{\M-c}} in your @file{.emacs} file. @xref{Init Rebinding, ,
17447 Rebinding Keys in Your Init File, emacs, The GNU Emacs Manual}, for
17448 details.)
17449
17450 The command invoked by the keys is @code{compare-windows}. Note that
17451 @code{compare-windows} is preceded by a single quote; otherwise, Emacs
17452 would first try to evaluate the symbol to determine its value.
17453
17454 These three things, the double quotation marks, the backslash before
17455 the @samp{C}, and the single quote mark are necessary parts of
17456 keybinding that I tend to forget. Fortunately, I have come to
17457 remember that I should look at my existing @file{.emacs} file, and
17458 adapt what is there.
17459
17460 As for the keybinding itself: @kbd{C-c w}. This combines the prefix
17461 key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
17462 set of keys, @kbd{C-c} followed by a single character, is strictly
17463 reserved for individuals' own use. (I call these `own' keys, since
17464 these are for my own use.) You should always be able to create such a
17465 keybinding for your own use without stomping on someone else's
17466 keybinding. If you ever write an extension to Emacs, please avoid
17467 taking any of these keys for public use. Create a key like @kbd{C-c
17468 C-w} instead. Otherwise, we will run out of `own' keys.
17469
17470 @need 1250
17471 Here is another keybinding, with a comment:
17472
17473 @smallexample
17474 @group
17475 ;;; Keybinding for `occur'
17476 ; I use occur a lot, so let's bind it to a key:
17477 (global-set-key "\C-co" 'occur)
17478 @end group
17479 @end smallexample
17480
17481 @findex occur
17482 The @code{occur} command shows all the lines in the current buffer
17483 that contain a match for a regular expression. Matching lines are
17484 shown in a buffer called @file{*Occur*}. That buffer serves as a menu
17485 to jump to occurrences.
17486
17487 @findex global-unset-key
17488 @cindex Unbinding key
17489 @cindex Key unbinding
17490 @need 1250
17491 Here is how to unbind a key, so it does not
17492 work:
17493
17494 @smallexample
17495 @group
17496 ;;; Unbind `C-x f'
17497 (global-unset-key "\C-xf")
17498 @end group
17499 @end smallexample
17500
17501 There is a reason for this unbinding: I found I inadvertently typed
17502 @w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
17503 file, as I intended, I accidentally set the width for filled text,
17504 almost always to a width I did not want. Since I hardly ever reset my
17505 default width, I simply unbound the key.
17506
17507 @findex list-buffers, @r{rebound}
17508 @findex buffer-menu, @r{bound to key}
17509 @need 1250
17510 The following rebinds an existing key:
17511
17512 @smallexample
17513 @group
17514 ;;; Rebind `C-x C-b' for `buffer-menu'
17515 (global-set-key "\C-x\C-b" 'buffer-menu)
17516 @end group
17517 @end smallexample
17518
17519 By default, @kbd{C-x C-b} runs the
17520 @code{list-buffers} command. This command lists
17521 your buffers in @emph{another} window. Since I
17522 almost always want to do something in that
17523 window, I prefer the @code{buffer-menu}
17524 command, which not only lists the buffers,
17525 but moves point into that window.
17526
17527 @node Keymaps
17528 @section Keymaps
17529 @cindex Keymaps
17530 @cindex Rebinding keys
17531
17532 Emacs uses @dfn{keymaps} to record which keys call which commands.
17533 When you use @code{global-set-key} to set the keybinding for a single
17534 command in all parts of Emacs, you are specifying the keybinding in
17535 @code{current-global-map}.
17536
17537 Specific modes, such as C mode or Text mode, have their own keymaps;
17538 the mode-specific keymaps override the global map that is shared by
17539 all buffers.
17540
17541 The @code{global-set-key} function binds, or rebinds, the global
17542 keymap. For example, the following binds the key @kbd{C-x C-b} to the
17543 function @code{buffer-menu}:
17544
17545 @smallexample
17546 (global-set-key "\C-x\C-b" 'buffer-menu)
17547 @end smallexample
17548
17549 Mode-specific keymaps are bound using the @code{define-key} function,
17550 which takes a specific keymap as an argument, as well as the key and
17551 the command. For example, my @file{.emacs} file contains the
17552 following expression to bind the @code{texinfo-insert-@@group} command
17553 to @kbd{C-c C-c g}:
17554
17555 @smallexample
17556 @group
17557 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
17558 @end group
17559 @end smallexample
17560
17561 @noindent
17562 The @code{texinfo-insert-@@group} function itself is a little extension
17563 to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
17564 use this command all the time and prefer to type the three strokes
17565 @kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
17566 (@samp{@@group} and its matching @samp{@@end group} are commands that
17567 keep all enclosed text together on one page; many multi-line examples
17568 in this book are surrounded by @samp{@@group @dots{} @@end group}.)
17569
17570 @need 1250
17571 Here is the @code{texinfo-insert-@@group} function definition:
17572
17573 @smallexample
17574 @group
17575 (defun texinfo-insert-@@group ()
17576 "Insert the string @@group in a Texinfo buffer."
17577 (interactive)
17578 (beginning-of-line)
17579 (insert "@@group\n"))
17580 @end group
17581 @end smallexample
17582
17583 (Of course, I could have used Abbrev mode to save typing, rather than
17584 write a function to insert a word; but I prefer key strokes consistent
17585 with other Texinfo mode key bindings.)
17586
17587 You will see numerous @code{define-key} expressions in
17588 @file{loaddefs.el} as well as in the various mode libraries, such as
17589 @file{cc-mode.el} and @file{lisp-mode.el}.
17590
17591 @xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
17592 Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
17593 Reference Manual}, for more information about keymaps.
17594
17595 @node Loading Files
17596 @section Loading Files
17597 @cindex Loading files
17598 @c findex load
17599
17600 Many people in the GNU Emacs community have written extensions to
17601 Emacs. As time goes by, these extensions are often included in new
17602 releases. For example, the Calendar and Diary packages are now part
17603 of the standard GNU Emacs, as is Calc.
17604
17605 You can use a @code{load} command to evaluate a complete file and
17606 thereby install all the functions and variables in the file into Emacs.
17607 For example:
17608
17609 @c (auto-compression-mode t)
17610
17611 @smallexample
17612 (load "~/emacs/slowsplit")
17613 @end smallexample
17614
17615 This evaluates, i.e.@: loads, the @file{slowsplit.el} file or if it
17616 exists, the faster, byte compiled @file{slowsplit.elc} file from the
17617 @file{emacs} sub-directory of your home directory. The file contains
17618 the function @code{split-window-quietly}, which John Robinson wrote in
17619 1989.
17620
17621 The @code{split-window-quietly} function splits a window with the
17622 minimum of redisplay. I installed it in 1989 because it worked well
17623 with the slow 1200 baud terminals I was then using. Nowadays, I only
17624 occasionally come across such a slow connection, but I continue to use
17625 the function because I like the way it leaves the bottom half of a
17626 buffer in the lower of the new windows and the top half in the upper
17627 window.
17628
17629 @need 1250
17630 To replace the key binding for the default
17631 @code{split-window-vertically}, you must also unset that key and bind
17632 the keys to @code{split-window-quietly}, like this:
17633
17634 @smallexample
17635 @group
17636 (global-unset-key "\C-x2")
17637 (global-set-key "\C-x2" 'split-window-quietly)
17638 @end group
17639 @end smallexample
17640
17641 @vindex load-path
17642 If you load many extensions, as I do, then instead of specifying the
17643 exact location of the extension file, as shown above, you can specify
17644 that directory as part of Emacs's @code{load-path}. Then, when Emacs
17645 loads a file, it will search that directory as well as its default
17646 list of directories. (The default list is specified in @file{paths.h}
17647 when Emacs is built.)
17648
17649 @need 1250
17650 The following command adds your @file{~/emacs} directory to the
17651 existing load path:
17652
17653 @smallexample
17654 @group
17655 ;;; Emacs Load Path
17656 (setq load-path (cons "~/emacs" load-path))
17657 @end group
17658 @end smallexample
17659
17660 Incidentally, @code{load-library} is an interactive interface to the
17661 @code{load} function. The complete function looks like this:
17662
17663 @findex load-library
17664 @smallexample
17665 @group
17666 (defun load-library (library)
17667 "Load the library named LIBRARY.
17668 This is an interface to the function `load'."
17669 (interactive
17670 (list (completing-read "Load library: "
17671 (apply-partially 'locate-file-completion-table
17672 load-path
17673 (get-load-suffixes)))))
17674 (load library))
17675 @end group
17676 @end smallexample
17677
17678 The name of the function, @code{load-library}, comes from the use of
17679 `library' as a conventional synonym for `file'. The source for the
17680 @code{load-library} command is in the @file{files.el} library.
17681
17682 Another interactive command that does a slightly different job is
17683 @code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
17684 Emacs, emacs, The GNU Emacs Manual}, for information on the
17685 distinction between @code{load-library} and this command.
17686
17687 @node Autoload
17688 @section Autoloading
17689 @findex autoload
17690
17691 Instead of installing a function by loading the file that contains it,
17692 or by evaluating the function definition, you can make the function
17693 available but not actually install it until it is first called. This
17694 is called @dfn{autoloading}.
17695
17696 When you execute an autoloaded function, Emacs automatically evaluates
17697 the file that contains the definition, and then calls the function.
17698
17699 Emacs starts quicker with autoloaded functions, since their libraries
17700 are not loaded right away; but you need to wait a moment when you
17701 first use such a function, while its containing file is evaluated.
17702
17703 Rarely used functions are frequently autoloaded. The
17704 @file{loaddefs.el} library contains hundreds of autoloaded functions,
17705 from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
17706 come to use a `rare' function frequently. When you do, you should
17707 load that function's file with a @code{load} expression in your
17708 @file{.emacs} file.
17709
17710 In my @file{.emacs} file, I load 14 libraries that contain functions
17711 that would otherwise be autoloaded. (Actually, it would have been
17712 better to include these files in my `dumped' Emacs, but I forgot.
17713 @xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17714 Reference Manual}, and the @file{INSTALL} file for more about
17715 dumping.)
17716
17717 You may also want to include autoloaded expressions in your @file{.emacs}
17718 file. @code{autoload} is a built-in function that takes up to five
17719 arguments, the final three of which are optional. The first argument
17720 is the name of the function to be autoloaded; the second is the name
17721 of the file to be loaded. The third argument is documentation for the
17722 function, and the fourth tells whether the function can be called
17723 interactively. The fifth argument tells what type of
17724 object---@code{autoload} can handle a keymap or macro as well as a
17725 function (the default is a function).
17726
17727 @need 800
17728 Here is a typical example:
17729
17730 @smallexample
17731 @group
17732 (autoload 'html-helper-mode
17733 "html-helper-mode" "Edit HTML documents" t)
17734 @end group
17735 @end smallexample
17736
17737 @noindent
17738 (@code{html-helper-mode} is an older alternative to @code{html-mode},
17739 which is a standard part of the distribution.)
17740
17741 @noindent
17742 This expression autoloads the @code{html-helper-mode} function. It
17743 takes it from the @file{html-helper-mode.el} file (or from the byte
17744 compiled version @file{html-helper-mode.elc}, if that exists.) The
17745 file must be located in a directory specified by @code{load-path}.
17746 The documentation says that this is a mode to help you edit documents
17747 written in the HyperText Markup Language. You can call this mode
17748 interactively by typing @kbd{M-x html-helper-mode}. (You need to
17749 duplicate the function's regular documentation in the autoload
17750 expression because the regular function is not yet loaded, so its
17751 documentation is not available.)
17752
17753 @xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
17754 Manual}, for more information.
17755
17756 @node Simple Extension
17757 @section A Simple Extension: @code{line-to-top-of-window}
17758 @findex line-to-top-of-window
17759 @cindex Simple extension in @file{.emacs} file
17760
17761 Here is a simple extension to Emacs that moves the line point is on to
17762 the top of the window. I use this all the time, to make text easier
17763 to read.
17764
17765 You can put the following code into a separate file and then load it
17766 from your @file{.emacs} file, or you can include it within your
17767 @file{.emacs} file.
17768
17769 @need 1250
17770 Here is the definition:
17771
17772 @smallexample
17773 @group
17774 ;;; Line to top of window;
17775 ;;; replace three keystroke sequence C-u 0 C-l
17776 (defun line-to-top-of-window ()
17777 "Move the line point is on to top of window."
17778 (interactive)
17779 (recenter 0))
17780 @end group
17781 @end smallexample
17782
17783 @need 1250
17784 Now for the keybinding.
17785
17786 Nowadays, function keys as well as mouse button events and
17787 non-@sc{ascii} characters are written within square brackets, without
17788 quotation marks. (In Emacs version 18 and before, you had to write
17789 different function key bindings for each different make of terminal.)
17790
17791 I bind @code{line-to-top-of-window} to my @key{F6} function key like
17792 this:
17793
17794 @smallexample
17795 (global-set-key [f6] 'line-to-top-of-window)
17796 @end smallexample
17797
17798 For more information, see @ref{Init Rebinding, , Rebinding Keys in
17799 Your Init File, emacs, The GNU Emacs Manual}.
17800
17801 @cindex Conditional 'twixt two versions of Emacs
17802 @cindex Version of Emacs, choosing
17803 @cindex Emacs version, choosing
17804 If you run two versions of GNU Emacs, such as versions 22 and 23, and
17805 use one @file{.emacs} file, you can select which code to evaluate with
17806 the following conditional:
17807
17808 @smallexample
17809 @group
17810 (cond
17811 ((= 22 emacs-major-version)
17812 ;; evaluate version 22 code
17813 ( @dots{} ))
17814 ((= 23 emacs-major-version)
17815 ;; evaluate version 23 code
17816 ( @dots{} )))
17817 @end group
17818 @end smallexample
17819
17820 For example, recent versions blink
17821 their cursors by default. I hate such blinking, as well as other
17822 features, so I placed the following in my @file{.emacs}
17823 file@footnote{When I start instances of Emacs that do not load my
17824 @file{.emacs} file or any site file, I also turn off blinking:
17825
17826 @smallexample
17827 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
17828
17829 @exdent Or nowadays, using an even more sophisticated set of options,
17830
17831 emacs -Q - D
17832 @end smallexample
17833 }:
17834
17835 @smallexample
17836 @group
17837 (when (>= emacs-major-version 21)
17838 (blink-cursor-mode 0)
17839 ;; Insert newline when you press `C-n' (next-line)
17840 ;; at the end of the buffer
17841 (setq next-line-add-newlines t)
17842 @end group
17843 @group
17844 ;; Turn on image viewing
17845 (auto-image-file-mode t)
17846 @end group
17847 @group
17848 ;; Turn on menu bar (this bar has text)
17849 ;; (Use numeric argument to turn on)
17850 (menu-bar-mode 1)
17851 @end group
17852 @group
17853 ;; Turn off tool bar (this bar has icons)
17854 ;; (Use numeric argument to turn on)
17855 (tool-bar-mode nil)
17856 @end group
17857 @group
17858 ;; Turn off tooltip mode for tool bar
17859 ;; (This mode causes icon explanations to pop up)
17860 ;; (Use numeric argument to turn on)
17861 (tooltip-mode nil)
17862 ;; If tooltips turned on, make tips appear promptly
17863 (setq tooltip-delay 0.1) ; default is 0.7 second
17864 )
17865 @end group
17866 @end smallexample
17867
17868 @node X11 Colors
17869 @section X11 Colors
17870
17871 You can specify colors when you use Emacs with the MIT X Windowing
17872 system.
17873
17874 I dislike the default colors and specify my own.
17875
17876 @need 1250
17877 Here are the expressions in my @file{.emacs}
17878 file that set values:
17879
17880 @smallexample
17881 @group
17882 ;; Set cursor color
17883 (set-cursor-color "white")
17884
17885 ;; Set mouse color
17886 (set-mouse-color "white")
17887
17888 ;; Set foreground and background
17889 (set-foreground-color "white")
17890 (set-background-color "darkblue")
17891 @end group
17892
17893 @group
17894 ;;; Set highlighting colors for isearch and drag
17895 (set-face-foreground 'highlight "white")
17896 (set-face-background 'highlight "blue")
17897 @end group
17898
17899 @group
17900 (set-face-foreground 'region "cyan")
17901 (set-face-background 'region "blue")
17902 @end group
17903
17904 @group
17905 (set-face-foreground 'secondary-selection "skyblue")
17906 (set-face-background 'secondary-selection "darkblue")
17907 @end group
17908
17909 @group
17910 ;; Set calendar highlighting colors
17911 (setq calendar-load-hook
17912 '(lambda ()
17913 (set-face-foreground 'diary-face "skyblue")
17914 (set-face-background 'holiday-face "slate blue")
17915 (set-face-foreground 'holiday-face "white")))
17916 @end group
17917 @end smallexample
17918
17919 The various shades of blue soothe my eye and prevent me from seeing
17920 the screen flicker.
17921
17922 Alternatively, I could have set my specifications in various X
17923 initialization files. For example, I could set the foreground,
17924 background, cursor, and pointer (i.e., mouse) colors in my
17925 @file{~/.Xresources} file like this:
17926
17927 @smallexample
17928 @group
17929 Emacs*foreground: white
17930 Emacs*background: darkblue
17931 Emacs*cursorColor: white
17932 Emacs*pointerColor: white
17933 @end group
17934 @end smallexample
17935
17936 In any event, since it is not part of Emacs, I set the root color of
17937 my X window in my @file{~/.xinitrc} file, like this@footnote{I also
17938 run more modern window managers, such as Enlightenment, Gnome, or KDE;
17939 in those cases, I often specify an image rather than a plain color.}:
17940
17941 @smallexample
17942 xsetroot -solid Navy -fg white &
17943 @end smallexample
17944
17945 @need 1700
17946 @node Miscellaneous
17947 @section Miscellaneous Settings for a @file{.emacs} File
17948
17949 @need 1250
17950 Here are a few miscellaneous settings:
17951 @sp 1
17952
17953 @itemize @minus
17954 @item
17955 Set the shape and color of the mouse cursor:
17956
17957 @smallexample
17958 @group
17959 ; Cursor shapes are defined in
17960 ; `/usr/include/X11/cursorfont.h';
17961 ; for example, the `target' cursor is number 128;
17962 ; the `top_left_arrow' cursor is number 132.
17963 @end group
17964
17965 @group
17966 (let ((mpointer (x-get-resource "*mpointer"
17967 "*emacs*mpointer")))
17968 ;; If you have not set your mouse pointer
17969 ;; then set it, otherwise leave as is:
17970 (if (eq mpointer nil)
17971 (setq mpointer "132")) ; top_left_arrow
17972 @end group
17973 @group
17974 (setq x-pointer-shape (string-to-int mpointer))
17975 (set-mouse-color "white"))
17976 @end group
17977 @end smallexample
17978
17979 @item
17980 Or you can set the values of a variety of features in an alist, like
17981 this:
17982
17983 @smallexample
17984 @group
17985 (setq-default
17986 default-frame-alist
17987 '((cursor-color . "white")
17988 (mouse-color . "white")
17989 (foreground-color . "white")
17990 (background-color . "DodgerBlue4")
17991 ;; (cursor-type . bar)
17992 (cursor-type . box)
17993 @end group
17994 @group
17995 (tool-bar-lines . 0)
17996 (menu-bar-lines . 1)
17997 (width . 80)
17998 (height . 58)
17999 (font .
18000 "-Misc-Fixed-Medium-R-Normal--20-200-75-75-C-100-ISO8859-1")
18001 ))
18002 @end group
18003 @end smallexample
18004
18005 @item
18006 Convert @kbd{@key{CTRL}-h} into @key{DEL} and @key{DEL}
18007 into @kbd{@key{CTRL}-h}.@*
18008 (Some older keyboards needed this, although I have not seen the
18009 problem recently.)
18010
18011 @smallexample
18012 @group
18013 ;; Translate `C-h' to <DEL>.
18014 ; (keyboard-translate ?\C-h ?\C-?)
18015
18016 ;; Translate <DEL> to `C-h'.
18017 (keyboard-translate ?\C-? ?\C-h)
18018 @end group
18019 @end smallexample
18020
18021 @item Turn off a blinking cursor!
18022
18023 @smallexample
18024 @group
18025 (if (fboundp 'blink-cursor-mode)
18026 (blink-cursor-mode -1))
18027 @end group
18028 @end smallexample
18029
18030 @noindent
18031 or start GNU Emacs with the command @code{emacs -nbc}.
18032
18033 @need 1250
18034 @item When using `grep'@*
18035 @samp{-i}@w{ } Ignore case distinctions@*
18036 @samp{-n}@w{ } Prefix each line of output with line number@*
18037 @samp{-H}@w{ } Print the filename for each match.@*
18038 @samp{-e}@w{ } Protect patterns beginning with a hyphen character, @samp{-}
18039
18040 @smallexample
18041 (setq grep-command "grep -i -nH -e ")
18042 @end smallexample
18043
18044 @ignore
18045 @c Evidently, no longer needed in GNU Emacs 22
18046
18047 item Automatically uncompress compressed files when visiting them
18048
18049 smallexample
18050 (load "uncompress")
18051 end smallexample
18052
18053 @end ignore
18054
18055 @item Find an existing buffer, even if it has a different name@*
18056 This avoids problems with symbolic links.
18057
18058 @smallexample
18059 (setq find-file-existing-other-name t)
18060 @end smallexample
18061
18062 @item Set your language environment and default input method
18063
18064 @smallexample
18065 @group
18066 (set-language-environment "latin-1")
18067 ;; Remember you can enable or disable multilingual text input
18068 ;; with the @code{toggle-input-method'} (@kbd{C-\}) command
18069 (setq default-input-method "latin-1-prefix")
18070 @end group
18071 @end smallexample
18072
18073 If you want to write with Chinese `GB' characters, set this instead:
18074
18075 @smallexample
18076 @group
18077 (set-language-environment "Chinese-GB")
18078 (setq default-input-method "chinese-tonepy")
18079 @end group
18080 @end smallexample
18081 @end itemize
18082
18083 @subsubheading Fixing Unpleasant Key Bindings
18084 @cindex Key bindings, fixing
18085 @cindex Bindings, key, fixing unpleasant
18086
18087 Some systems bind keys unpleasantly. Sometimes, for example, the
18088 @key{CTRL} key appears in an awkward spot rather than at the far left
18089 of the home row.
18090
18091 Usually, when people fix these sorts of keybindings, they do not
18092 change their @file{~/.emacs} file. Instead, they bind the proper keys
18093 on their consoles with the @code{loadkeys} or @code{install-keymap}
18094 commands in their boot script and then include @code{xmodmap} commands
18095 in their @file{.xinitrc} or @file{.Xsession} file for X Windows.
18096
18097 @need 1250
18098 @noindent
18099 For a boot script:
18100
18101 @smallexample
18102 @group
18103 loadkeys /usr/share/keymaps/i386/qwerty/emacs2.kmap.gz
18104 @exdent or
18105 install-keymap emacs2
18106 @end group
18107 @end smallexample
18108
18109 @need 1250
18110 @noindent
18111 For a @file{.xinitrc} or @file{.Xsession} file when the @key{Caps
18112 Lock} key is at the far left of the home row:
18113
18114 @smallexample
18115 @group
18116 # Bind the key labeled `Caps Lock' to `Control'
18117 # (Such a broken user interface suggests that keyboard manufacturers
18118 # think that computers are typewriters from 1885.)
18119
18120 xmodmap -e "clear Lock"
18121 xmodmap -e "add Control = Caps_Lock"
18122 @end group
18123 @end smallexample
18124
18125 @need 1250
18126 @noindent
18127 In a @file{.xinitrc} or @file{.Xsession} file, to convert an @key{ALT}
18128 key to a @key{META} key:
18129
18130 @smallexample
18131 @group
18132 # Some ill designed keyboards have a key labeled ALT and no Meta
18133 xmodmap -e "keysym Alt_L = Meta_L Alt_L"
18134 @end group
18135 @end smallexample
18136
18137 @need 1700
18138 @node Mode Line
18139 @section A Modified Mode Line
18140 @vindex mode-line-format
18141 @cindex Mode line format
18142
18143 Finally, a feature I really like: a modified mode line.
18144
18145 When I work over a network, I forget which machine I am using. Also,
18146 I tend to I lose track of where I am, and which line point is on.
18147
18148 So I reset my mode line to look like this:
18149
18150 @smallexample
18151 -:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
18152 @end smallexample
18153
18154 I am visiting a file called @file{foo.texi}, on my machine
18155 @file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
18156 Texinfo mode, and am at the top of the buffer.
18157
18158 @need 1200
18159 My @file{.emacs} file has a section that looks like this:
18160
18161 @smallexample
18162 @group
18163 ;; Set a Mode Line that tells me which machine, which directory,
18164 ;; and which line I am on, plus the other customary information.
18165 (setq-default mode-line-format
18166 (quote
18167 (#("-" 0 1
18168 (help-echo
18169 "mouse-1: select window, mouse-2: delete others ..."))
18170 mode-line-mule-info
18171 mode-line-modified
18172 mode-line-frame-identification
18173 " "
18174 @end group
18175 @group
18176 mode-line-buffer-identification
18177 " "
18178 (:eval (substring
18179 (system-name) 0 (string-match "\\..+" (system-name))))
18180 ":"
18181 default-directory
18182 #(" " 0 1
18183 (help-echo
18184 "mouse-1: select window, mouse-2: delete others ..."))
18185 (line-number-mode " Line %l ")
18186 global-mode-string
18187 @end group
18188 @group
18189 #(" %[(" 0 6
18190 (help-echo
18191 "mouse-1: select window, mouse-2: delete others ..."))
18192 (:eval (mode-line-mode-name))
18193 mode-line-process
18194 minor-mode-alist
18195 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
18196 ")%] "
18197 (-3 . "%P")
18198 ;; "-%-"
18199 )))
18200 @end group
18201 @end smallexample
18202
18203 @noindent
18204 Here, I redefine the default mode line. Most of the parts are from
18205 the original; but I make a few changes. I set the @emph{default} mode
18206 line format so as to permit various modes, such as Info, to override
18207 it.
18208
18209 Many elements in the list are self-explanatory:
18210 @code{mode-line-modified} is a variable that tells whether the buffer
18211 has been modified, @code{mode-name} tells the name of the mode, and so
18212 on. However, the format looks complicated because of two features we
18213 have not discussed.
18214
18215 @cindex Properties, in mode line example
18216 The first string in the mode line is a dash or hyphen, @samp{-}. In
18217 the old days, it would have been specified simply as @code{"-"}. But
18218 nowadays, Emacs can add properties to a string, such as highlighting
18219 or, as in this case, a help feature. If you place your mouse cursor
18220 over the hyphen, some help information appears (By default, you must
18221 wait seven-tenths of a second before the information appears. You can
18222 change that timing by changing the value of @code{tooltip-delay}.)
18223
18224 @need 1000
18225 The new string format has a special syntax:
18226
18227 @smallexample
18228 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
18229 @end smallexample
18230
18231 @noindent
18232 The @code{#(} begins a list. The first element of the list is the
18233 string itself, just one @samp{-}. The second and third
18234 elements specify the range over which the fourth element applies. A
18235 range starts @emph{after} a character, so a zero means the range
18236 starts just before the first character; a 1 means that the range ends
18237 just after the first character. The third element is the property for
18238 the range. It consists of a property list, a
18239 property name, in this case, @samp{help-echo}, followed by a value, in this
18240 case, a string. The second, third, and fourth elements of this new
18241 string format can be repeated.
18242
18243 @xref{Text Properties, , Text Properties, elisp, The GNU Emacs Lisp
18244 Reference Manual}, and see @ref{Mode Line Format, , Mode Line Format,
18245 elisp, The GNU Emacs Lisp Reference Manual}, for more information.
18246
18247 @code{mode-line-buffer-identification}
18248 displays the current buffer name. It is a list
18249 beginning @code{(#("%12b" 0 4 @dots{}}.
18250 The @code{#(} begins the list.
18251
18252 The @samp{"%12b"} displays the current buffer name, using the
18253 @code{buffer-name} function with which we are familiar; the `12'
18254 specifies the maximum number of characters that will be displayed.
18255 When a name has fewer characters, whitespace is added to fill out to
18256 this number. (Buffer names can and often should be longer than 12
18257 characters; this length works well in a typical 80 column wide
18258 window.)
18259
18260 @code{:eval} says to evaluate the following form and use the result as
18261 a string to display. In this case, the expression displays the first
18262 component of the full system name. The end of the first component is
18263 a @samp{.} (`period'), so I use the @code{string-match} function to
18264 tell me the length of the first component. The substring from the
18265 zeroth character to that length is the name of the machine.
18266
18267 @need 1250
18268 This is the expression:
18269
18270 @smallexample
18271 @group
18272 (:eval (substring
18273 (system-name) 0 (string-match "\\..+" (system-name))))
18274 @end group
18275 @end smallexample
18276
18277 @samp{%[} and @samp{%]} cause a pair of square brackets
18278 to appear for each recursive editing level. @samp{%n} says `Narrow'
18279 when narrowing is in effect. @samp{%P} tells you the percentage of
18280 the buffer that is above the bottom of the window, or `Top', `Bottom',
18281 or `All'. (A lower case @samp{p} tell you the percentage above the
18282 @emph{top} of the window.) @samp{%-} inserts enough dashes to fill
18283 out the line.
18284
18285 Remember, ``You don't have to like Emacs to like it'' --- your own
18286 Emacs can have different colors, different commands, and different
18287 keys than a default Emacs.
18288
18289 On the other hand, if you want to bring up a plain `out of the box'
18290 Emacs, with no customization, type:
18291
18292 @smallexample
18293 emacs -q
18294 @end smallexample
18295
18296 @noindent
18297 This will start an Emacs that does @emph{not} load your
18298 @file{~/.emacs} initialization file. A plain, default Emacs. Nothing
18299 more.
18300
18301 @node Debugging
18302 @chapter Debugging
18303 @cindex debugging
18304
18305 GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
18306 first is built into the internals of Emacs and is always with you;
18307 the second requires that you instrument a function before you can use it.
18308
18309 Both debuggers are described extensively in @ref{Debugging, ,
18310 Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
18311 In this chapter, I will walk through a short example of each.
18312
18313 @menu
18314 * debug:: How to use the built-in debugger.
18315 * debug-on-entry:: Start debugging when you call a function.
18316 * debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
18317 * edebug:: How to use Edebug, a source level debugger.
18318 * Debugging Exercises::
18319 @end menu
18320
18321 @node debug
18322 @section @code{debug}
18323 @findex debug
18324
18325 Suppose you have written a function definition that is intended to
18326 return the sum of the numbers 1 through a given number. (This is the
18327 @code{triangle} function discussed earlier. @xref{Decrementing
18328 Example, , Example with Decrementing Counter}, for a discussion.)
18329 @c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
18330
18331 However, your function definition has a bug. You have mistyped
18332 @samp{1=} for @samp{1-}. Here is the broken definition:
18333
18334 @findex triangle-bugged
18335 @smallexample
18336 @group
18337 (defun triangle-bugged (number)
18338 "Return sum of numbers 1 through NUMBER inclusive."
18339 (let ((total 0))
18340 (while (> number 0)
18341 (setq total (+ total number))
18342 (setq number (1= number))) ; @r{Error here.}
18343 total))
18344 @end group
18345 @end smallexample
18346
18347 If you are reading this in Info, you can evaluate this definition in
18348 the normal fashion. You will see @code{triangle-bugged} appear in the
18349 echo area.
18350
18351 @need 1250
18352 Now evaluate the @code{triangle-bugged} function with an
18353 argument of 4:
18354
18355 @smallexample
18356 (triangle-bugged 4)
18357 @end smallexample
18358
18359 @noindent
18360 In a recent GNU Emacs, you will create and enter a @file{*Backtrace*}
18361 buffer that says:
18362
18363 @noindent
18364 @smallexample
18365 @group
18366 ---------- Buffer: *Backtrace* ----------
18367 Debugger entered--Lisp error: (void-function 1=)
18368 (1= number)
18369 (setq number (1= number))
18370 (while (> number 0) (setq total (+ total number))
18371 (setq number (1= number)))
18372 (let ((total 0)) (while (> number 0) (setq total ...)
18373 (setq number ...)) total)
18374 triangle-bugged(4)
18375 @end group
18376 @group
18377 eval((triangle-bugged 4))
18378 eval-last-sexp-1(nil)
18379 eval-last-sexp(nil)
18380 call-interactively(eval-last-sexp)
18381 ---------- Buffer: *Backtrace* ----------
18382 @end group
18383 @end smallexample
18384
18385 @noindent
18386 (I have reformatted this example slightly; the debugger does not fold
18387 long lines. As usual, you can quit the debugger by typing @kbd{q} in
18388 the @file{*Backtrace*} buffer.)
18389
18390 In practice, for a bug as simple as this, the `Lisp error' line will
18391 tell you what you need to know to correct the definition. The
18392 function @code{1=} is `void'.
18393
18394 @ignore
18395 @need 800
18396 In GNU Emacs 20 and before, you will see:
18397
18398 @smallexample
18399 Symbol's function definition is void:@: 1=
18400 @end smallexample
18401
18402 @noindent
18403 which has the same meaning as the @file{*Backtrace*} buffer line in
18404 version 21.
18405 @end ignore
18406
18407 However, suppose you are not quite certain what is going on?
18408 You can read the complete backtrace.
18409
18410 In this case, you need to run a recent GNU Emacs, which automatically
18411 starts the debugger that puts you in the @file{*Backtrace*} buffer; or
18412 else, you need to start the debugger manually as described below.
18413
18414 Read the @file{*Backtrace*} buffer from the bottom up; it tells you
18415 what Emacs did that led to the error. Emacs made an interactive call
18416 to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
18417 of the @code{triangle-bugged} expression. Each line above tells you
18418 what the Lisp interpreter evaluated next.
18419
18420 @need 1250
18421 The third line from the top of the buffer is
18422
18423 @smallexample
18424 (setq number (1= number))
18425 @end smallexample
18426
18427 @noindent
18428 Emacs tried to evaluate this expression; in order to do so, it tried
18429 to evaluate the inner expression shown on the second line from the
18430 top:
18431
18432 @smallexample
18433 (1= number)
18434 @end smallexample
18435
18436 @need 1250
18437 @noindent
18438 This is where the error occurred; as the top line says:
18439
18440 @smallexample
18441 Debugger entered--Lisp error: (void-function 1=)
18442 @end smallexample
18443
18444 @noindent
18445 You can correct the mistake, re-evaluate the function definition, and
18446 then run your test again.
18447
18448 @node debug-on-entry
18449 @section @code{debug-on-entry}
18450 @findex debug-on-entry
18451
18452 A recent GNU Emacs starts the debugger automatically when your
18453 function has an error.
18454
18455 @ignore
18456 GNU Emacs version 20 and before did not; it simply
18457 presented you with an error message. You had to start the debugger
18458 manually.
18459 @end ignore
18460
18461 Incidentally, you can start the debugger manually for all versions of
18462 Emacs; the advantage is that the debugger runs even if you do not have
18463 a bug in your code. Sometimes your code will be free of bugs!
18464
18465 You can enter the debugger when you call the function by calling
18466 @code{debug-on-entry}.
18467
18468 @need 1250
18469 @noindent
18470 Type:
18471
18472 @smallexample
18473 M-x debug-on-entry RET triangle-bugged RET
18474 @end smallexample
18475
18476 @need 1250
18477 @noindent
18478 Now, evaluate the following:
18479
18480 @smallexample
18481 (triangle-bugged 5)
18482 @end smallexample
18483
18484 @noindent
18485 All versions of Emacs will create a @file{*Backtrace*} buffer and tell
18486 you that it is beginning to evaluate the @code{triangle-bugged}
18487 function:
18488
18489 @smallexample
18490 @group
18491 ---------- Buffer: *Backtrace* ----------
18492 Debugger entered--entering a function:
18493 * triangle-bugged(5)
18494 eval((triangle-bugged 5))
18495 @end group
18496 @group
18497 eval-last-sexp-1(nil)
18498 eval-last-sexp(nil)
18499 call-interactively(eval-last-sexp)
18500 ---------- Buffer: *Backtrace* ----------
18501 @end group
18502 @end smallexample
18503
18504 In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
18505 the first expression in @code{triangle-bugged}; the buffer will look
18506 like this:
18507
18508 @smallexample
18509 @group
18510 ---------- Buffer: *Backtrace* ----------
18511 Debugger entered--beginning evaluation of function call form:
18512 * (let ((total 0)) (while (> number 0) (setq total ...)
18513 (setq number ...)) total)
18514 * triangle-bugged(5)
18515 eval((triangle-bugged 5))
18516 @end group
18517 @group
18518 eval-last-sexp-1(nil)
18519 eval-last-sexp(nil)
18520 call-interactively(eval-last-sexp)
18521 ---------- Buffer: *Backtrace* ----------
18522 @end group
18523 @end smallexample
18524
18525 @noindent
18526 Now, type @kbd{d} again, eight times, slowly. Each time you type
18527 @kbd{d}, Emacs will evaluate another expression in the function
18528 definition.
18529
18530 @need 1750
18531 Eventually, the buffer will look like this:
18532
18533 @smallexample
18534 @group
18535 ---------- Buffer: *Backtrace* ----------
18536 Debugger entered--beginning evaluation of function call form:
18537 * (setq number (1= number))
18538 * (while (> number 0) (setq total (+ total number))
18539 (setq number (1= number)))
18540 @group
18541 @end group
18542 * (let ((total 0)) (while (> number 0) (setq total ...)
18543 (setq number ...)) total)
18544 * triangle-bugged(5)
18545 eval((triangle-bugged 5))
18546 @group
18547 @end group
18548 eval-last-sexp-1(nil)
18549 eval-last-sexp(nil)
18550 call-interactively(eval-last-sexp)
18551 ---------- Buffer: *Backtrace* ----------
18552 @end group
18553 @end smallexample
18554
18555 @need 1500
18556 @noindent
18557 Finally, after you type @kbd{d} two more times, Emacs will reach the
18558 error, and the top two lines of the @file{*Backtrace*} buffer will look
18559 like this:
18560
18561 @smallexample
18562 @group
18563 ---------- Buffer: *Backtrace* ----------
18564 Debugger entered--Lisp error: (void-function 1=)
18565 * (1= number)
18566 @dots{}
18567 ---------- Buffer: *Backtrace* ----------
18568 @end group
18569 @end smallexample
18570
18571 By typing @kbd{d}, you were able to step through the function.
18572
18573 You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
18574 quits the trace, but does not cancel @code{debug-on-entry}.
18575
18576 @findex cancel-debug-on-entry
18577 To cancel the effect of @code{debug-on-entry}, call
18578 @code{cancel-debug-on-entry} and the name of the function, like this:
18579
18580 @smallexample
18581 M-x cancel-debug-on-entry RET triangle-bugged RET
18582 @end smallexample
18583
18584 @noindent
18585 (If you are reading this in Info, cancel @code{debug-on-entry} now.)
18586
18587 @node debug-on-quit
18588 @section @code{debug-on-quit} and @code{(debug)}
18589
18590 In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
18591 there are two other ways to start @code{debug}.
18592
18593 @findex debug-on-quit
18594 You can start @code{debug} whenever you type @kbd{C-g}
18595 (@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
18596 @code{t}. This is useful for debugging infinite loops.
18597
18598 @need 1500
18599 @cindex @code{(debug)} in code
18600 Or, you can insert a line that says @code{(debug)} into your code
18601 where you want the debugger to start, like this:
18602
18603 @smallexample
18604 @group
18605 (defun triangle-bugged (number)
18606 "Return sum of numbers 1 through NUMBER inclusive."
18607 (let ((total 0))
18608 (while (> number 0)
18609 (setq total (+ total number))
18610 (debug) ; @r{Start debugger.}
18611 (setq number (1= number))) ; @r{Error here.}
18612 total))
18613 @end group
18614 @end smallexample
18615
18616 The @code{debug} function is described in detail in @ref{Debugger, ,
18617 The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
18618
18619 @node edebug
18620 @section The @code{edebug} Source Level Debugger
18621 @cindex Source level debugger
18622 @findex edebug
18623
18624 Edebug is a source level debugger. Edebug normally displays the
18625 source of the code you are debugging, with an arrow at the left that
18626 shows which line you are currently executing.
18627
18628 You can walk through the execution of a function, line by line, or run
18629 quickly until reaching a @dfn{breakpoint} where execution stops.
18630
18631 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18632 Lisp Reference Manual}.
18633
18634 @need 1250
18635 Here is a bugged function definition for @code{triangle-recursively}.
18636 @xref{Recursive triangle function, , Recursion in place of a counter},
18637 for a review of it.
18638
18639 @smallexample
18640 @group
18641 (defun triangle-recursively-bugged (number)
18642 "Return sum of numbers 1 through NUMBER inclusive.
18643 Uses recursion."
18644 (if (= number 1)
18645 1
18646 (+ number
18647 (triangle-recursively-bugged
18648 (1= number))))) ; @r{Error here.}
18649 @end group
18650 @end smallexample
18651
18652 @noindent
18653 Normally, you would install this definition by positioning your cursor
18654 after the function's closing parenthesis and typing @kbd{C-x C-e}
18655 (@code{eval-last-sexp}) or else by positioning your cursor within the
18656 definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
18657 the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
18658 Interaction mode.)
18659
18660 @need 1500
18661 However, to prepare this function definition for Edebug, you must
18662 first @dfn{instrument} the code using a different command. You can do
18663 this by positioning your cursor within or just after the definition
18664 and typing
18665
18666 @smallexample
18667 M-x edebug-defun RET
18668 @end smallexample
18669
18670 @noindent
18671 This will cause Emacs to load Edebug automatically if it is not
18672 already loaded, and properly instrument the function.
18673
18674 After instrumenting the function, place your cursor after the
18675 following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
18676
18677 @smallexample
18678 (triangle-recursively-bugged 3)
18679 @end smallexample
18680
18681 @noindent
18682 You will be jumped back to the source for
18683 @code{triangle-recursively-bugged} and the cursor positioned at the
18684 beginning of the @code{if} line of the function. Also, you will see
18685 an arrowhead at the left hand side of that line. The arrowhead marks
18686 the line where the function is executing. (In the following examples,
18687 we show the arrowhead with @samp{=>}; in a windowing system, you may
18688 see the arrowhead as a solid triangle in the window `fringe'.)
18689
18690 @smallexample
18691 =>@point{}(if (= number 1)
18692 @end smallexample
18693
18694 @noindent
18695 @iftex
18696 In the example, the location of point is displayed with a star,
18697 @samp{@point{}} (in Info, it is displayed as @samp{-!-}).
18698 @end iftex
18699 @ifnottex
18700 In the example, the location of point is displayed as @samp{@point{}}
18701 (in a printed book, it is displayed with a five pointed star).
18702 @end ifnottex
18703
18704 If you now press @key{SPC}, point will move to the next expression to
18705 be executed; the line will look like this:
18706
18707 @smallexample
18708 =>(if @point{}(= number 1)
18709 @end smallexample
18710
18711 @noindent
18712 As you continue to press @key{SPC}, point will move from expression to
18713 expression. At the same time, whenever an expression returns a value,
18714 that value will be displayed in the echo area. For example, after you
18715 move point past @code{number}, you will see the following:
18716
18717 @smallexample
18718 Result: 3 (#o3, #x3, ?\C-c)
18719 @end smallexample
18720
18721 @noindent
18722 This means the value of @code{number} is 3, which is octal three,
18723 hexadecimal three, and @sc{ascii} `control-c' (the third letter of the
18724 alphabet, in case you need to know this information).
18725
18726 You can continue moving through the code until you reach the line with
18727 the error. Before evaluation, that line looks like this:
18728
18729 @smallexample
18730 => @point{}(1= number))))) ; @r{Error here.}
18731 @end smallexample
18732
18733 @need 1250
18734 @noindent
18735 When you press @key{SPC} once again, you will produce an error message
18736 that says:
18737
18738 @smallexample
18739 Symbol's function definition is void:@: 1=
18740 @end smallexample
18741
18742 @noindent
18743 This is the bug.
18744
18745 Press @kbd{q} to quit Edebug.
18746
18747 To remove instrumentation from a function definition, simply
18748 re-evaluate it with a command that does not instrument it.
18749 For example, you could place your cursor after the definition's
18750 closing parenthesis and type @kbd{C-x C-e}.
18751
18752 Edebug does a great deal more than walk with you through a function.
18753 You can set it so it races through on its own, stopping only at an
18754 error or at specified stopping points; you can cause it to display the
18755 changing values of various expressions; you can find out how many
18756 times a function is called, and more.
18757
18758 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18759 Lisp Reference Manual}.
18760
18761 @need 1500
18762 @node Debugging Exercises
18763 @section Debugging Exercises
18764
18765 @itemize @bullet
18766 @item
18767 Install the @code{@value{COUNT-WORDS}} function and then cause it to
18768 enter the built-in debugger when you call it. Run the command on a
18769 region containing two words. You will need to press @kbd{d} a
18770 remarkable number of times. On your system, is a `hook' called after
18771 the command finishes? (For information on hooks, see @ref{Command
18772 Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
18773 Manual}.)
18774
18775 @item
18776 Copy @code{@value{COUNT-WORDS}} into the @file{*scratch*} buffer,
18777 instrument the function for Edebug, and walk through its execution.
18778 The function does not need to have a bug, although you can introduce
18779 one if you wish. If the function lacks a bug, the walk-through
18780 completes without problems.
18781
18782 @item
18783 While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
18784 (The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.@:
18785 @kbd{@key{CTRL}-x} followed by an upper case @kbd{X}; use this prefix
18786 for commands made outside of the Edebug debugging buffer.)
18787
18788 @item
18789 In the Edebug debugging buffer, use the @kbd{p}
18790 (@code{edebug-bounce-point}) command to see where in the region the
18791 @code{@value{COUNT-WORDS}} is working.
18792
18793 @item
18794 Move point to some spot further down the function and then type the
18795 @kbd{h} (@code{edebug-goto-here}) command to jump to that location.
18796
18797 @item
18798 Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
18799 walk through the function on its own; use an upper case @kbd{T} for
18800 @code{edebug-Trace-fast-mode}.
18801
18802 @item
18803 Set a breakpoint, then run Edebug in Trace mode until it reaches the
18804 stopping point.
18805 @end itemize
18806
18807 @node Conclusion
18808 @chapter Conclusion
18809
18810 We have now reached the end of this Introduction. You have now
18811 learned enough about programming in Emacs Lisp to set values, to write
18812 simple @file{.emacs} files for yourself and your friends, and write
18813 simple customizations and extensions to Emacs.
18814
18815 This is a place to stop. Or, if you wish, you can now go onward, and
18816 teach yourself.
18817
18818 You have learned some of the basic nuts and bolts of programming. But
18819 only some. There are a great many more brackets and hinges that are
18820 easy to use that we have not touched.
18821
18822 A path you can follow right now lies among the sources to GNU Emacs
18823 and in
18824 @ifnotinfo
18825 @cite{The GNU Emacs Lisp Reference Manual}.
18826 @end ifnotinfo
18827 @ifinfo
18828 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
18829 Emacs Lisp Reference Manual}.
18830 @end ifinfo
18831
18832 The Emacs Lisp sources are an adventure. When you read the sources and
18833 come across a function or expression that is unfamiliar, you need to
18834 figure out or find out what it does.
18835
18836 Go to the Reference Manual. It is a thorough, complete, and fairly
18837 easy-to-read description of Emacs Lisp. It is written not only for
18838 experts, but for people who know what you know. (The @cite{Reference
18839 Manual} comes with the standard GNU Emacs distribution. Like this
18840 introduction, it comes as a Texinfo source file, so you can read it
18841 on-line and as a typeset, printed book.)
18842
18843 Go to the other on-line help that is part of GNU Emacs: the on-line
18844 documentation for all functions and variables, and @code{find-tag},
18845 the program that takes you to sources.
18846
18847 Here is an example of how I explore the sources. Because of its name,
18848 @file{simple.el} is the file I looked at first, a long time ago. As
18849 it happens some of the functions in @file{simple.el} are complicated,
18850 or at least look complicated at first sight. The @code{open-line}
18851 function, for example, looks complicated.
18852
18853 You may want to walk through this function slowly, as we did with the
18854 @code{forward-sentence} function. (@xref{forward-sentence, The
18855 @code{forward-sentence} function}.) Or you may want to skip that
18856 function and look at another, such as @code{split-line}. You don't
18857 need to read all the functions. According to
18858 @code{count-words-in-defun}, the @code{split-line} function contains
18859 102 words and symbols.
18860
18861 Even though it is short, @code{split-line} contains expressions
18862 we have not studied: @code{skip-chars-forward}, @code{indent-to},
18863 @code{current-column} and @code{insert-and-inherit}.
18864
18865 Consider the @code{skip-chars-forward} function. (It is part of the
18866 function definition for @code{back-to-indentation}, which is shown in
18867 @ref{Review, , Review}.)
18868
18869 In GNU Emacs, you can find out more about @code{skip-chars-forward} by
18870 typing @kbd{C-h f} (@code{describe-function}) and the name of the
18871 function. This gives you the function documentation.
18872
18873 You may be able to guess what is done by a well named function such as
18874 @code{indent-to}; or you can look it up, too. Incidentally, the
18875 @code{describe-function} function itself is in @file{help.el}; it is
18876 one of those long, but decipherable functions. You can look up
18877 @code{describe-function} using the @kbd{C-h f} command!
18878
18879 In this instance, since the code is Lisp, the @file{*Help*} buffer
18880 contains the name of the library containing the function's source.
18881 You can put point over the name of the library and press the RET key,
18882 which in this situation is bound to @code{help-follow}, and be taken
18883 directly to the source, in the same way as @kbd{M-.}
18884 (@code{find-tag}).
18885
18886 The definition for @code{describe-function} illustrates how to
18887 customize the @code{interactive} expression without using the standard
18888 character codes; and it shows how to create a temporary buffer.
18889
18890 (The @code{indent-to} function is written in C rather than Emacs Lisp;
18891 it is a `built-in' function. @code{help-follow} takes you to its
18892 source as does @code{find-tag}, when properly set up.)
18893
18894 You can look at a function's source using @code{find-tag}, which is
18895 bound to @kbd{M-.} Finally, you can find out what the Reference
18896 Manual has to say by visiting the manual in Info, and typing @kbd{i}
18897 (@code{Info-index}) and the name of the function, or by looking up the
18898 function in the index to a printed copy of the manual.
18899
18900 Similarly, you can find out what is meant by
18901 @code{insert-and-inherit}.
18902
18903 Other interesting source files include @file{paragraphs.el},
18904 @file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
18905 file includes short, easily understood functions as well as longer
18906 ones. The @file{loaddefs.el} file contains the many standard
18907 autoloads and many keymaps. I have never looked at it all; only at
18908 parts. @file{loadup.el} is the file that loads the standard parts of
18909 Emacs; it tells you a great deal about how Emacs is built.
18910 (@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
18911 Reference Manual}, for more about building.)
18912
18913 As I said, you have learned some nuts and bolts; however, and very
18914 importantly, we have hardly touched major aspects of programming; I
18915 have said nothing about how to sort information, except to use the
18916 predefined @code{sort} function; I have said nothing about how to store
18917 information, except to use variables and lists; I have said nothing
18918 about how to write programs that write programs. These are topics for
18919 another, and different kind of book, a different kind of learning.
18920
18921 What you have done is learn enough for much practical work with GNU
18922 Emacs. What you have done is get started. This is the end of a
18923 beginning.
18924
18925 @c ================ Appendix ================
18926
18927 @node the-the
18928 @appendix The @code{the-the} Function
18929 @findex the-the
18930 @cindex Duplicated words function
18931 @cindex Words, duplicated
18932
18933 Sometimes when you you write text, you duplicate words---as with ``you
18934 you'' near the beginning of this sentence. I find that most
18935 frequently, I duplicate ``the''; hence, I call the function for
18936 detecting duplicated words, @code{the-the}.
18937
18938 @need 1250
18939 As a first step, you could use the following regular expression to
18940 search for duplicates:
18941
18942 @smallexample
18943 \\(\\w+[ \t\n]+\\)\\1
18944 @end smallexample
18945
18946 @noindent
18947 This regexp matches one or more word-constituent characters followed
18948 by one or more spaces, tabs, or newlines. However, it does not detect
18949 duplicated words on different lines, since the ending of the first
18950 word, the end of the line, is different from the ending of the second
18951 word, a space. (For more information about regular expressions, see
18952 @ref{Regexp Search, , Regular Expression Searches}, as well as
18953 @ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
18954 Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
18955 The GNU Emacs Lisp Reference Manual}.)
18956
18957 You might try searching just for duplicated word-constituent
18958 characters but that does not work since the pattern detects doubles
18959 such as the two occurrences of `th' in `with the'.
18960
18961 Another possible regexp searches for word-constituent characters
18962 followed by non-word-constituent characters, reduplicated. Here,
18963 @w{@samp{\\w+}} matches one or more word-constituent characters and
18964 @w{@samp{\\W*}} matches zero or more non-word-constituent characters.
18965
18966 @smallexample
18967 \\(\\(\\w+\\)\\W*\\)\\1
18968 @end smallexample
18969
18970 @noindent
18971 Again, not useful.
18972
18973 Here is the pattern that I use. It is not perfect, but good enough.
18974 @w{@samp{\\b}} matches the empty string, provided it is at the beginning
18975 or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
18976 any characters that are @emph{not} an @@-sign, space, newline, or tab.
18977
18978 @smallexample
18979 \\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
18980 @end smallexample
18981
18982 One can write more complicated expressions, but I found that this
18983 expression is good enough, so I use it.
18984
18985 Here is the @code{the-the} function, as I include it in my
18986 @file{.emacs} file, along with a handy global key binding:
18987
18988 @smallexample
18989 @group
18990 (defun the-the ()
18991 "Search forward for for a duplicated word."
18992 (interactive)
18993 (message "Searching for for duplicated words ...")
18994 (push-mark)
18995 @end group
18996 @group
18997 ;; This regexp is not perfect
18998 ;; but is fairly good over all:
18999 (if (re-search-forward
19000 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
19001 (message "Found duplicated word.")
19002 (message "End of buffer")))
19003 @end group
19004
19005 @group
19006 ;; Bind `the-the' to C-c \
19007 (global-set-key "\C-c\\" 'the-the)
19008 @end group
19009 @end smallexample
19010
19011 @sp 1
19012 Here is test text:
19013
19014 @smallexample
19015 @group
19016 one two two three four five
19017 five six seven
19018 @end group
19019 @end smallexample
19020
19021 You can substitute the other regular expressions shown above in the
19022 function definition and try each of them on this list.
19023
19024 @node Kill Ring
19025 @appendix Handling the Kill Ring
19026 @cindex Kill ring handling
19027 @cindex Handling the kill ring
19028 @cindex Ring, making a list like a
19029
19030 The kill ring is a list that is transformed into a ring by the
19031 workings of the @code{current-kill} function. The @code{yank} and
19032 @code{yank-pop} commands use the @code{current-kill} function.
19033
19034 This appendix describes the @code{current-kill} function as well as
19035 both the @code{yank} and the @code{yank-pop} commands, but first,
19036 consider the workings of the kill ring.
19037
19038 @menu
19039 * What the Kill Ring Does::
19040 * current-kill::
19041 * yank:: Paste a copy of a clipped element.
19042 * yank-pop:: Insert element pointed to.
19043 * ring file::
19044 @end menu
19045
19046 @ifnottex
19047 @node What the Kill Ring Does
19048 @unnumberedsec What the Kill Ring Does
19049 @end ifnottex
19050
19051 @need 1250
19052 The kill ring has a default maximum length of sixty items; this number
19053 is too large for an explanation. Instead, set it to four. Please
19054 evaluate the following:
19055
19056 @smallexample
19057 @group
19058 (setq old-kill-ring-max kill-ring-max)
19059 (setq kill-ring-max 4)
19060 @end group
19061 @end smallexample
19062
19063 @noindent
19064 Then, please copy each line of the following indented example into the
19065 kill ring. You may kill each line with @kbd{C-k} or mark it and copy
19066 it with @kbd{M-w}.
19067
19068 @noindent
19069 (In a read-only buffer, such as the @file{*info*} buffer, the kill
19070 command, @kbd{C-k} (@code{kill-line}), will not remove the text,
19071 merely copy it to the kill ring. However, your machine may beep at
19072 you. Alternatively, for silence, you may copy the region of each line
19073 with the @kbd{M-w} (@code{kill-ring-save}) command. You must mark
19074 each line for this command to succeed, but it does not matter at which
19075 end you put point or mark.)
19076
19077 @need 1250
19078 @noindent
19079 Please invoke the calls in order, so that five elements attempt to
19080 fill the kill ring:
19081
19082 @smallexample
19083 @group
19084 first some text
19085 second piece of text
19086 third line
19087 fourth line of text
19088 fifth bit of text
19089 @end group
19090 @end smallexample
19091
19092 @need 1250
19093 @noindent
19094 Then find the value of @code{kill-ring} by evaluating
19095
19096 @smallexample
19097 kill-ring
19098 @end smallexample
19099
19100 @need 800
19101 @noindent
19102 It is:
19103
19104 @smallexample
19105 @group
19106 ("fifth bit of text" "fourth line of text"
19107 "third line" "second piece of text")
19108 @end group
19109 @end smallexample
19110
19111 @noindent
19112 The first element, @samp{first some text}, was dropped.
19113
19114 @need 1250
19115 To return to the old value for the length of the kill ring, evaluate:
19116
19117 @smallexample
19118 (setq kill-ring-max old-kill-ring-max)
19119 @end smallexample
19120
19121 @node current-kill
19122 @appendixsec The @code{current-kill} Function
19123 @findex current-kill
19124
19125 The @code{current-kill} function changes the element in the kill ring
19126 to which @code{kill-ring-yank-pointer} points. (Also, the
19127 @code{kill-new} function sets @code{kill-ring-yank-pointer} to point
19128 to the latest element of the kill ring. The @code{kill-new}
19129 function is used directly or indirectly by @code{kill-append},
19130 @code{copy-region-as-kill}, @code{kill-ring-save}, @code{kill-line},
19131 and @code{kill-region}.)
19132
19133 @menu
19134 * Code for current-kill::
19135 * Understanding current-kill::
19136 @end menu
19137
19138 @ifnottex
19139 @node Code for current-kill
19140 @unnumberedsubsec The code for @code{current-kill}
19141 @end ifnottex
19142
19143
19144 @need 1500
19145 The @code{current-kill} function is used by @code{yank} and by
19146 @code{yank-pop}. Here is the code for @code{current-kill}:
19147
19148 @smallexample
19149 @group
19150 (defun current-kill (n &optional do-not-move)
19151 "Rotate the yanking point by N places, and then return that kill.
19152 If N is zero, `interprogram-paste-function' is set, and calling it
19153 returns a string, then that string is added to the front of the
19154 kill ring and returned as the latest kill.
19155 @end group
19156 @group
19157 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
19158 yanking point; just return the Nth kill forward."
19159 (let ((interprogram-paste (and (= n 0)
19160 interprogram-paste-function
19161 (funcall interprogram-paste-function))))
19162 @end group
19163 @group
19164 (if interprogram-paste
19165 (progn
19166 ;; Disable the interprogram cut function when we add the new
19167 ;; text to the kill ring, so Emacs doesn't try to own the
19168 ;; selection, with identical text.
19169 (let ((interprogram-cut-function nil))
19170 (kill-new interprogram-paste))
19171 interprogram-paste)
19172 @end group
19173 @group
19174 (or kill-ring (error "Kill ring is empty"))
19175 (let ((ARGth-kill-element
19176 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19177 (length kill-ring))
19178 kill-ring)))
19179 (or do-not-move
19180 (setq kill-ring-yank-pointer ARGth-kill-element))
19181 (car ARGth-kill-element)))))
19182 @end group
19183 @end smallexample
19184
19185 Remember also that the @code{kill-new} function sets
19186 @code{kill-ring-yank-pointer} to the latest element of the kill
19187 ring, which means that all the functions that call it set the value
19188 indirectly: @code{kill-append}, @code{copy-region-as-kill},
19189 @code{kill-ring-save}, @code{kill-line}, and @code{kill-region}.
19190
19191 @need 1500
19192 Here is the line in @code{kill-new}, which is explained in
19193 @ref{kill-new function, , The @code{kill-new} function}.
19194
19195 @smallexample
19196 (setq kill-ring-yank-pointer kill-ring)
19197 @end smallexample
19198
19199 @ifnottex
19200 @node Understanding current-kill
19201 @unnumberedsubsec @code{current-kill} in Outline
19202 @end ifnottex
19203
19204 The @code{current-kill} function looks complex, but as usual, it can
19205 be understood by taking it apart piece by piece. First look at it in
19206 skeletal form:
19207
19208 @smallexample
19209 @group
19210 (defun current-kill (n &optional do-not-move)
19211 "Rotate the yanking point by N places, and then return that kill."
19212 (let @var{varlist}
19213 @var{body}@dots{})
19214 @end group
19215 @end smallexample
19216
19217 This function takes two arguments, one of which is optional. It has a
19218 documentation string. It is @emph{not} interactive.
19219
19220 @menu
19221 * Body of current-kill::
19222 * Digression concerning error:: How to mislead humans, but not computers.
19223 * Determining the Element::
19224 @end menu
19225
19226 @ifnottex
19227 @node Body of current-kill
19228 @unnumberedsubsubsec The Body of @code{current-kill}
19229 @end ifnottex
19230
19231 The body of the function definition is a @code{let} expression, which
19232 itself has a body as well as a @var{varlist}.
19233
19234 The @code{let} expression declares a variable that will be only usable
19235 within the bounds of this function. This variable is called
19236 @code{interprogram-paste} and is for copying to another program. It
19237 is not for copying within this instance of GNU Emacs. Most window
19238 systems provide a facility for interprogram pasting. Sadly, that
19239 facility usually provides only for the last element. Most windowing
19240 systems have not adopted a ring of many possibilities, even though
19241 Emacs has provided it for decades.
19242
19243 The @code{if} expression has two parts, one if there exists
19244 @code{interprogram-paste} and one if not.
19245
19246 @need 2000
19247 Let us consider the `if not' or else-part of the @code{current-kill}
19248 function. (The then-part uses the @code{kill-new} function, which
19249 we have already described. @xref{kill-new function, , The
19250 @code{kill-new} function}.)
19251
19252 @smallexample
19253 @group
19254 (or kill-ring (error "Kill ring is empty"))
19255 (let ((ARGth-kill-element
19256 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19257 (length kill-ring))
19258 kill-ring)))
19259 (or do-not-move
19260 (setq kill-ring-yank-pointer ARGth-kill-element))
19261 (car ARGth-kill-element))
19262 @end group
19263 @end smallexample
19264
19265 @noindent
19266 The code first checks whether the kill ring has content; otherwise it
19267 signals an error.
19268
19269 @need 1000
19270 Note that the @code{or} expression is very similar to testing length
19271 with an @code{if}:
19272
19273 @findex zerop
19274 @findex error
19275 @smallexample
19276 @group
19277 (if (zerop (length kill-ring)) ; @r{if-part}
19278 (error "Kill ring is empty")) ; @r{then-part}
19279 ;; No else-part
19280 @end group
19281 @end smallexample
19282
19283 @noindent
19284 If there is not anything in the kill ring, its length must be zero and
19285 an error message sent to the user: @samp{Kill ring is empty}. The
19286 @code{current-kill} function uses an @code{or} expression which is
19287 simpler. But an @code{if} expression reminds us what goes on.
19288
19289 This @code{if} expression uses the function @code{zerop} which returns
19290 true if the value it is testing is zero. When @code{zerop} tests
19291 true, the then-part of the @code{if} is evaluated. The then-part is a
19292 list starting with the function @code{error}, which is a function that
19293 is similar to the @code{message} function
19294 (@pxref{message, , The @code{message} Function}) in that
19295 it prints a one-line message in the echo area. However, in addition
19296 to printing a message, @code{error} also stops evaluation of the
19297 function within which it is embedded. This means that the rest of the
19298 function will not be evaluated if the length of the kill ring is zero.
19299
19300 Then the @code{current-kill} function selects the element to return.
19301 The selection depends on the number of places that @code{current-kill}
19302 rotates and on where @code{kill-ring-yank-pointer} points.
19303
19304 Next, either the optional @code{do-not-move} argument is true or the
19305 current value of @code{kill-ring-yank-pointer} is set to point to the
19306 list. Finally, another expression returns the first element of the
19307 list even if the @code{do-not-move} argument is true.
19308
19309 @ifnottex
19310 @node Digression concerning error
19311 @unnumberedsubsubsec Digression about the word `error'
19312 @end ifnottex
19313
19314 In my opinion, it is slightly misleading, at least to humans, to use
19315 the term `error' as the name of the @code{error} function. A better
19316 term would be `cancel'. Strictly speaking, of course, you cannot
19317 point to, much less rotate a pointer to a list that has no length, so
19318 from the point of view of the computer, the word `error' is correct.
19319 But a human expects to attempt this sort of thing, if only to find out
19320 whether the kill ring is full or empty. This is an act of
19321 exploration.
19322
19323 From the human point of view, the act of exploration and discovery is
19324 not necessarily an error, and therefore should not be labeled as one,
19325 even in the bowels of a computer. As it is, the code in Emacs implies
19326 that a human who is acting virtuously, by exploring his or her
19327 environment, is making an error. This is bad. Even though the computer
19328 takes the same steps as it does when there is an `error', a term such as
19329 `cancel' would have a clearer connotation.
19330
19331 @ifnottex
19332 @node Determining the Element
19333 @unnumberedsubsubsec Determining the Element
19334 @end ifnottex
19335
19336 Among other actions, the else-part of the @code{if} expression sets
19337 the value of @code{kill-ring-yank-pointer} to
19338 @code{ARGth-kill-element} when the kill ring has something in it and
19339 the value of @code{do-not-move} is @code{nil}.
19340
19341 @need 800
19342 The code looks like this:
19343
19344 @smallexample
19345 @group
19346 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19347 (length kill-ring))
19348 kill-ring)))
19349 @end group
19350 @end smallexample
19351
19352 This needs some examination. Unless it is not supposed to move the
19353 pointer, the @code{current-kill} function changes where
19354 @code{kill-ring-yank-pointer} points.
19355 That is what the
19356 @w{@code{(setq kill-ring-yank-pointer ARGth-kill-element))}}
19357 expression does. Also, clearly, @code{ARGth-kill-element} is being
19358 set to be equal to some @sc{cdr} of the kill ring, using the
19359 @code{nthcdr} function that is described in an earlier section.
19360 (@xref{copy-region-as-kill}.) How does it do this?
19361
19362 As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
19363 works by repeatedly taking the @sc{cdr} of a list---it takes the
19364 @sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
19365
19366 @need 800
19367 The two following expressions produce the same result:
19368
19369 @smallexample
19370 @group
19371 (setq kill-ring-yank-pointer (cdr kill-ring))
19372
19373 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
19374 @end group
19375 @end smallexample
19376
19377 However, the @code{nthcdr} expression is more complicated. It uses
19378 the @code{mod} function to determine which @sc{cdr} to select.
19379
19380 (You will remember to look at inner functions first; indeed, we will
19381 have to go inside the @code{mod}.)
19382
19383 The @code{mod} function returns the value of its first argument modulo
19384 the second; that is to say, it returns the remainder after dividing
19385 the first argument by the second. The value returned has the same
19386 sign as the second argument.
19387
19388 @need 800
19389 Thus,
19390
19391 @smallexample
19392 @group
19393 (mod 12 4)
19394 @result{} 0 ;; @r{because there is no remainder}
19395 (mod 13 4)
19396 @result{} 1
19397 @end group
19398 @end smallexample
19399
19400 @need 1250
19401 In this case, the first argument is often smaller than the second.
19402 That is fine.
19403
19404 @smallexample
19405 @group
19406 (mod 0 4)
19407 @result{} 0
19408 (mod 1 4)
19409 @result{} 1
19410 @end group
19411 @end smallexample
19412
19413 We can guess what the @code{-} function does. It is like @code{+} but
19414 subtracts instead of adds; the @code{-} function subtracts its second
19415 argument from its first. Also, we already know what the @code{length}
19416 function does (@pxref{length}). It returns the length of a list.
19417
19418 And @code{n} is the name of the required argument to the
19419 @code{current-kill} function.
19420
19421 @need 1250
19422 So when the first argument to @code{nthcdr} is zero, the @code{nthcdr}
19423 expression returns the whole list, as you can see by evaluating the
19424 following:
19425
19426 @smallexample
19427 @group
19428 ;; kill-ring-yank-pointer @r{and} kill-ring @r{have a length of four}
19429 ;; @r{and} (mod (- 0 4) 4) @result{} 0
19430 (nthcdr (mod (- 0 4) 4)
19431 '("fourth line of text"
19432 "third line"
19433 "second piece of text"
19434 "first some text"))
19435 @end group
19436 @end smallexample
19437
19438 @need 1250
19439 When the first argument to the @code{current-kill} function is one,
19440 the @code{nthcdr} expression returns the list without its first
19441 element.
19442
19443 @smallexample
19444 @group
19445 (nthcdr (mod (- 1 4) 4)
19446 '("fourth line of text"
19447 "third line"
19448 "second piece of text"
19449 "first some text"))
19450 @end group
19451 @end smallexample
19452
19453 @cindex @samp{global variable} defined
19454 @cindex @samp{variable, global}, defined
19455 Incidentally, both @code{kill-ring} and @code{kill-ring-yank-pointer}
19456 are @dfn{global variables}. That means that any expression in Emacs
19457 Lisp can access them. They are not like the local variables set by
19458 @code{let} or like the symbols in an argument list.
19459 Local variables can only be accessed
19460 within the @code{let} that defines them or the function that specifies
19461 them in an argument list (and within expressions called by them).
19462
19463 @ignore
19464 @c texi2dvi fails when the name of the section is within ifnottex ...
19465 (@xref{Prevent confusion, , @code{let} Prevents Confusion}, and
19466 @ref{defun, , The @code{defun} Special Form}.)
19467 @end ignore
19468
19469 @node yank
19470 @appendixsec @code{yank}
19471 @findex yank
19472
19473 After learning about @code{current-kill}, the code for the
19474 @code{yank} function is almost easy.
19475
19476 The @code{yank} function does not use the
19477 @code{kill-ring-yank-pointer} variable directly. It calls
19478 @code{insert-for-yank} which calls @code{current-kill} which sets the
19479 @code{kill-ring-yank-pointer} variable.
19480
19481 @need 1250
19482 The code looks like this:
19483
19484 @c in GNU Emacs 22
19485 @smallexample
19486 @group
19487 (defun yank (&optional arg)
19488 "Reinsert (\"paste\") the last stretch of killed text.
19489 More precisely, reinsert the stretch of killed text most recently
19490 killed OR yanked. Put point at end, and set mark at beginning.
19491 With just \\[universal-argument] as argument, same but put point at
19492 beginning (and mark at end). With argument N, reinsert the Nth most
19493 recently killed stretch of killed text.
19494
19495 When this command inserts killed text into the buffer, it honors
19496 `yank-excluded-properties' and `yank-handler' as described in the
19497 doc string for `insert-for-yank-1', which see.
19498
19499 See also the command \\[yank-pop]."
19500 @end group
19501 @group
19502 (interactive "*P")
19503 (setq yank-window-start (window-start))
19504 ;; If we don't get all the way thru, make last-command indicate that
19505 ;; for the following command.
19506 (setq this-command t)
19507 (push-mark (point))
19508 @end group
19509 @group
19510 (insert-for-yank (current-kill (cond
19511 ((listp arg) 0)
19512 ((eq arg '-) -2)
19513 (t (1- arg)))))
19514 (if (consp arg)
19515 ;; This is like exchange-point-and-mark,
19516 ;; but doesn't activate the mark.
19517 ;; It is cleaner to avoid activation, even though the command
19518 ;; loop would deactivate the mark because we inserted text.
19519 (goto-char (prog1 (mark t)
19520 (set-marker (mark-marker) (point) (current-buffer)))))
19521 @end group
19522 @group
19523 ;; If we do get all the way thru, make this-command indicate that.
19524 (if (eq this-command t)
19525 (setq this-command 'yank))
19526 nil)
19527 @end group
19528 @end smallexample
19529
19530 The key expression is @code{insert-for-yank}, which inserts the string
19531 returned by @code{current-kill}, but removes some text properties from
19532 it.
19533
19534 However, before getting to that expression, the function sets the value
19535 of @code{yank-window-start} to the position returned by the
19536 @code{(window-start)} expression, the position at which the display
19537 currently starts. The @code{yank} function also sets
19538 @code{this-command} and pushes the mark.
19539
19540 After it yanks the appropriate element, if the optional argument is a
19541 @sc{cons} rather than a number or nothing, it puts point at beginning
19542 of the yanked text and mark at its end.
19543
19544 (The @code{prog1} function is like @code{progn} but returns the value
19545 of its first argument rather than the value of its last argument. Its
19546 first argument is forced to return the buffer's mark as an integer.
19547 You can see the documentation for these functions by placing point
19548 over them in this buffer and then typing @kbd{C-h f}
19549 (@code{describe-function}) followed by a @kbd{RET}; the default is the
19550 function.)
19551
19552 The last part of the function tells what to do when it succeeds.
19553
19554 @node yank-pop
19555 @appendixsec @code{yank-pop}
19556 @findex yank-pop
19557
19558 After understanding @code{yank} and @code{current-kill}, you know how
19559 to approach the @code{yank-pop} function. Leaving out the
19560 documentation to save space, it looks like this:
19561
19562 @c GNU Emacs 22
19563 @smallexample
19564 @group
19565 (defun yank-pop (&optional arg)
19566 "@dots{}"
19567 (interactive "*p")
19568 (if (not (eq last-command 'yank))
19569 (error "Previous command was not a yank"))
19570 @end group
19571 @group
19572 (setq this-command 'yank)
19573 (unless arg (setq arg 1))
19574 (let ((inhibit-read-only t)
19575 (before (< (point) (mark t))))
19576 @end group
19577 @group
19578 (if before
19579 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
19580 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
19581 (setq yank-undo-function nil)
19582 @end group
19583 @group
19584 (set-marker (mark-marker) (point) (current-buffer))
19585 (insert-for-yank (current-kill arg))
19586 ;; Set the window start back where it was in the yank command,
19587 ;; if possible.
19588 (set-window-start (selected-window) yank-window-start t)
19589 @end group
19590 @group
19591 (if before
19592 ;; This is like exchange-point-and-mark,
19593 ;; but doesn't activate the mark.
19594 ;; It is cleaner to avoid activation, even though the command
19595 ;; loop would deactivate the mark because we inserted text.
19596 (goto-char (prog1 (mark t)
19597 (set-marker (mark-marker)
19598 (point)
19599 (current-buffer))))))
19600 nil)
19601 @end group
19602 @end smallexample
19603
19604 The function is interactive with a small @samp{p} so the prefix
19605 argument is processed and passed to the function. The command can
19606 only be used after a previous yank; otherwise an error message is
19607 sent. This check uses the variable @code{last-command} which is set
19608 by @code{yank} and is discussed elsewhere.
19609 (@xref{copy-region-as-kill}.)
19610
19611 The @code{let} clause sets the variable @code{before} to true or false
19612 depending whether point is before or after mark and then the region
19613 between point and mark is deleted. This is the region that was just
19614 inserted by the previous yank and it is this text that will be
19615 replaced.
19616
19617 @code{funcall} calls its first argument as a function, passing
19618 remaining arguments to it. The first argument is whatever the
19619 @code{or} expression returns. The two remaining arguments are the
19620 positions of point and mark set by the preceding @code{yank} command.
19621
19622 There is more, but that is the hardest part.
19623
19624 @node ring file
19625 @appendixsec The @file{ring.el} File
19626 @cindex @file{ring.el} file
19627
19628 Interestingly, GNU Emacs posses a file called @file{ring.el} that
19629 provides many of the features we just discussed. But functions such
19630 as @code{kill-ring-yank-pointer} do not use this library, possibly
19631 because they were written earlier.
19632
19633 @node Full Graph
19634 @appendix A Graph with Labeled Axes
19635
19636 Printed axes help you understand a graph. They convey scale. In an
19637 earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
19638 wrote the code to print the body of a graph. Here we write the code
19639 for printing and labeling vertical and horizontal axes, along with the
19640 body itself.
19641
19642 @menu
19643 * Labeled Example::
19644 * print-graph Varlist:: @code{let} expression in @code{print-graph}.
19645 * print-Y-axis:: Print a label for the vertical axis.
19646 * print-X-axis:: Print a horizontal label.
19647 * Print Whole Graph:: The function to print a complete graph.
19648 @end menu
19649
19650 @ifnottex
19651 @node Labeled Example
19652 @unnumberedsec Labeled Example Graph
19653 @end ifnottex
19654
19655 Since insertions fill a buffer to the right and below point, the new
19656 graph printing function should first print the Y or vertical axis,
19657 then the body of the graph, and finally the X or horizontal axis.
19658 This sequence lays out for us the contents of the function:
19659
19660 @enumerate
19661 @item
19662 Set up code.
19663
19664 @item
19665 Print Y axis.
19666
19667 @item
19668 Print body of graph.
19669
19670 @item
19671 Print X axis.
19672 @end enumerate
19673
19674 @need 800
19675 Here is an example of how a finished graph should look:
19676
19677 @smallexample
19678 @group
19679 10 -
19680 *
19681 * *
19682 * **
19683 * ***
19684 5 - * *******
19685 * *** *******
19686 *************
19687 ***************
19688 1 - ****************
19689 | | | |
19690 1 5 10 15
19691 @end group
19692 @end smallexample
19693
19694 @noindent
19695 In this graph, both the vertical and the horizontal axes are labeled
19696 with numbers. However, in some graphs, the horizontal axis is time
19697 and would be better labeled with months, like this:
19698
19699 @smallexample
19700 @group
19701 5 - *
19702 * ** *
19703 *******
19704 ********** **
19705 1 - **************
19706 | ^ |
19707 Jan June Jan
19708 @end group
19709 @end smallexample
19710
19711 Indeed, with a little thought, we can easily come up with a variety of
19712 vertical and horizontal labeling schemes. Our task could become
19713 complicated. But complications breed confusion. Rather than permit
19714 this, it is better choose a simple labeling scheme for our first
19715 effort, and to modify or replace it later.
19716
19717 @need 1200
19718 These considerations suggest the following outline for the
19719 @code{print-graph} function:
19720
19721 @smallexample
19722 @group
19723 (defun print-graph (numbers-list)
19724 "@var{documentation}@dots{}"
19725 (let ((height @dots{}
19726 @dots{}))
19727 @end group
19728 @group
19729 (print-Y-axis height @dots{} )
19730 (graph-body-print numbers-list)
19731 (print-X-axis @dots{} )))
19732 @end group
19733 @end smallexample
19734
19735 We can work on each part of the @code{print-graph} function definition
19736 in turn.
19737
19738 @node print-graph Varlist
19739 @appendixsec The @code{print-graph} Varlist
19740 @cindex @code{print-graph} varlist
19741
19742 In writing the @code{print-graph} function, the first task is to write
19743 the varlist in the @code{let} expression. (We will leave aside for the
19744 moment any thoughts about making the function interactive or about the
19745 contents of its documentation string.)
19746
19747 The varlist should set several values. Clearly, the top of the label
19748 for the vertical axis must be at least the height of the graph, which
19749 means that we must obtain this information here. Note that the
19750 @code{print-graph-body} function also requires this information. There
19751 is no reason to calculate the height of the graph in two different
19752 places, so we should change @code{print-graph-body} from the way we
19753 defined it earlier to take advantage of the calculation.
19754
19755 Similarly, both the function for printing the X axis labels and the
19756 @code{print-graph-body} function need to learn the value of the width of
19757 each symbol. We can perform the calculation here and change the
19758 definition for @code{print-graph-body} from the way we defined it in the
19759 previous chapter.
19760
19761 The length of the label for the horizontal axis must be at least as long
19762 as the graph. However, this information is used only in the function
19763 that prints the horizontal axis, so it does not need to be calculated here.
19764
19765 These thoughts lead us directly to the following form for the varlist
19766 in the @code{let} for @code{print-graph}:
19767
19768 @smallexample
19769 @group
19770 (let ((height (apply 'max numbers-list)) ; @r{First version.}
19771 (symbol-width (length graph-blank)))
19772 @end group
19773 @end smallexample
19774
19775 @noindent
19776 As we shall see, this expression is not quite right.
19777
19778 @need 2000
19779 @node print-Y-axis
19780 @appendixsec The @code{print-Y-axis} Function
19781 @cindex Axis, print vertical
19782 @cindex Y axis printing
19783 @cindex Vertical axis printing
19784 @cindex Print vertical axis
19785
19786 The job of the @code{print-Y-axis} function is to print a label for
19787 the vertical axis that looks like this:
19788
19789 @smallexample
19790 @group
19791 10 -
19792
19793
19794
19795
19796 5 -
19797
19798
19799
19800 1 -
19801 @end group
19802 @end smallexample
19803
19804 @noindent
19805 The function should be passed the height of the graph, and then should
19806 construct and insert the appropriate numbers and marks.
19807
19808 @menu
19809 * print-Y-axis in Detail::
19810 * Height of label:: What height for the Y axis?
19811 * Compute a Remainder:: How to compute the remainder of a division.
19812 * Y Axis Element:: Construct a line for the Y axis.
19813 * Y-axis-column:: Generate a list of Y axis labels.
19814 * print-Y-axis Penultimate:: A not quite final version.
19815 @end menu
19816
19817 @ifnottex
19818 @node print-Y-axis in Detail
19819 @unnumberedsubsec The @code{print-Y-axis} Function in Detail
19820 @end ifnottex
19821
19822 It is easy enough to see in the figure what the Y axis label should
19823 look like; but to say in words, and then to write a function
19824 definition to do the job is another matter. It is not quite true to
19825 say that we want a number and a tic every five lines: there are only
19826 three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
19827 but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
19828 and 9). It is better to say that we want a number and a tic mark on
19829 the base line (number 1) and then that we want a number and a tic on
19830 the fifth line from the bottom and on every line that is a multiple of
19831 five.
19832
19833 @ifnottex
19834 @node Height of label
19835 @unnumberedsubsec What height should the label be?
19836 @end ifnottex
19837
19838 The next issue is what height the label should be? Suppose the maximum
19839 height of tallest column of the graph is seven. Should the highest
19840 label on the Y axis be @samp{5 -}, and should the graph stick up above
19841 the label? Or should the highest label be @samp{7 -}, and mark the peak
19842 of the graph? Or should the highest label be @code{10 -}, which is a
19843 multiple of five, and be higher than the topmost value of the graph?
19844
19845 The latter form is preferred. Most graphs are drawn within rectangles
19846 whose sides are an integral number of steps long---5, 10, 15, and so
19847 on for a step distance of five. But as soon as we decide to use a
19848 step height for the vertical axis, we discover that the simple
19849 expression in the varlist for computing the height is wrong. The
19850 expression is @code{(apply 'max numbers-list)}. This returns the
19851 precise height, not the maximum height plus whatever is necessary to
19852 round up to the nearest multiple of five. A more complex expression
19853 is required.
19854
19855 As usual in cases like this, a complex problem becomes simpler if it is
19856 divided into several smaller problems.
19857
19858 First, consider the case when the highest value of the graph is an
19859 integral multiple of five---when it is 5, 10, 15, or some higher
19860 multiple of five. We can use this value as the Y axis height.
19861
19862 A fairly simply way to determine whether a number is a multiple of
19863 five is to divide it by five and see if the division results in a
19864 remainder. If there is no remainder, the number is a multiple of
19865 five. Thus, seven divided by five has a remainder of two, and seven
19866 is not an integral multiple of five. Put in slightly different
19867 language, more reminiscent of the classroom, five goes into seven
19868 once, with a remainder of two. However, five goes into ten twice,
19869 with no remainder: ten is an integral multiple of five.
19870
19871 @node Compute a Remainder
19872 @appendixsubsec Side Trip: Compute a Remainder
19873
19874 @findex % @r{(remainder function)}
19875 @cindex Remainder function, @code{%}
19876 In Lisp, the function for computing a remainder is @code{%}. The
19877 function returns the remainder of its first argument divided by its
19878 second argument. As it happens, @code{%} is a function in Emacs Lisp
19879 that you cannot discover using @code{apropos}: you find nothing if you
19880 type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
19881 learn of the existence of @code{%} is to read about it in a book such
19882 as this or in the Emacs Lisp sources.
19883
19884 You can try the @code{%} function by evaluating the following two
19885 expressions:
19886
19887 @smallexample
19888 @group
19889 (% 7 5)
19890
19891 (% 10 5)
19892 @end group
19893 @end smallexample
19894
19895 @noindent
19896 The first expression returns 2 and the second expression returns 0.
19897
19898 To test whether the returned value is zero or some other number, we
19899 can use the @code{zerop} function. This function returns @code{t} if
19900 its argument, which must be a number, is zero.
19901
19902 @smallexample
19903 @group
19904 (zerop (% 7 5))
19905 @result{} nil
19906
19907 (zerop (% 10 5))
19908 @result{} t
19909 @end group
19910 @end smallexample
19911
19912 Thus, the following expression will return @code{t} if the height
19913 of the graph is evenly divisible by five:
19914
19915 @smallexample
19916 (zerop (% height 5))
19917 @end smallexample
19918
19919 @noindent
19920 (The value of @code{height}, of course, can be found from @code{(apply
19921 'max numbers-list)}.)
19922
19923 On the other hand, if the value of @code{height} is not a multiple of
19924 five, we want to reset the value to the next higher multiple of five.
19925 This is straightforward arithmetic using functions with which we are
19926 already familiar. First, we divide the value of @code{height} by five
19927 to determine how many times five goes into the number. Thus, five
19928 goes into twelve twice. If we add one to this quotient and multiply by
19929 five, we will obtain the value of the next multiple of five that is
19930 larger than the height. Five goes into twelve twice. Add one to two,
19931 and multiply by five; the result is fifteen, which is the next multiple
19932 of five that is higher than twelve. The Lisp expression for this is:
19933
19934 @smallexample
19935 (* (1+ (/ height 5)) 5)
19936 @end smallexample
19937
19938 @noindent
19939 For example, if you evaluate the following, the result is 15:
19940
19941 @smallexample
19942 (* (1+ (/ 12 5)) 5)
19943 @end smallexample
19944
19945 All through this discussion, we have been using `five' as the value
19946 for spacing labels on the Y axis; but we may want to use some other
19947 value. For generality, we should replace `five' with a variable to
19948 which we can assign a value. The best name I can think of for this
19949 variable is @code{Y-axis-label-spacing}.
19950
19951 @need 1250
19952 Using this term, and an @code{if} expression, we produce the
19953 following:
19954
19955 @smallexample
19956 @group
19957 (if (zerop (% height Y-axis-label-spacing))
19958 height
19959 ;; @r{else}
19960 (* (1+ (/ height Y-axis-label-spacing))
19961 Y-axis-label-spacing))
19962 @end group
19963 @end smallexample
19964
19965 @noindent
19966 This expression returns the value of @code{height} itself if the height
19967 is an even multiple of the value of the @code{Y-axis-label-spacing} or
19968 else it computes and returns a value of @code{height} that is equal to
19969 the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19970
19971 We can now include this expression in the @code{let} expression of the
19972 @code{print-graph} function (after first setting the value of
19973 @code{Y-axis-label-spacing}):
19974 @vindex Y-axis-label-spacing
19975
19976 @smallexample
19977 @group
19978 (defvar Y-axis-label-spacing 5
19979 "Number of lines from one Y axis label to next.")
19980 @end group
19981
19982 @group
19983 @dots{}
19984 (let* ((height (apply 'max numbers-list))
19985 (height-of-top-line
19986 (if (zerop (% height Y-axis-label-spacing))
19987 height
19988 @end group
19989 @group
19990 ;; @r{else}
19991 (* (1+ (/ height Y-axis-label-spacing))
19992 Y-axis-label-spacing)))
19993 (symbol-width (length graph-blank))))
19994 @dots{}
19995 @end group
19996 @end smallexample
19997
19998 @noindent
19999 (Note use of the @code{let*} function: the initial value of height is
20000 computed once by the @code{(apply 'max numbers-list)} expression and
20001 then the resulting value of @code{height} is used to compute its
20002 final value. @xref{fwd-para let, , The @code{let*} expression}, for
20003 more about @code{let*}.)
20004
20005 @node Y Axis Element
20006 @appendixsubsec Construct a Y Axis Element
20007
20008 When we print the vertical axis, we want to insert strings such as
20009 @w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
20010 Moreover, we want the numbers and dashes to line up, so shorter
20011 numbers must be padded with leading spaces. If some of the strings
20012 use two digit numbers, the strings with single digit numbers must
20013 include a leading blank space before the number.
20014
20015 @findex number-to-string
20016 To figure out the length of the number, the @code{length} function is
20017 used. But the @code{length} function works only with a string, not with
20018 a number. So the number has to be converted from being a number to
20019 being a string. This is done with the @code{number-to-string} function.
20020 For example,
20021
20022 @smallexample
20023 @group
20024 (length (number-to-string 35))
20025 @result{} 2
20026
20027 (length (number-to-string 100))
20028 @result{} 3
20029 @end group
20030 @end smallexample
20031
20032 @noindent
20033 (@code{number-to-string} is also called @code{int-to-string}; you will
20034 see this alternative name in various sources.)
20035
20036 In addition, in each label, each number is followed by a string such
20037 as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
20038 This variable is defined with @code{defvar}:
20039
20040 @vindex Y-axis-tic
20041 @smallexample
20042 @group
20043 (defvar Y-axis-tic " - "
20044 "String that follows number in a Y axis label.")
20045 @end group
20046 @end smallexample
20047
20048 The length of the Y label is the sum of the length of the Y axis tic
20049 mark and the length of the number of the top of the graph.
20050
20051 @smallexample
20052 (length (concat (number-to-string height) Y-axis-tic)))
20053 @end smallexample
20054
20055 This value will be calculated by the @code{print-graph} function in
20056 its varlist as @code{full-Y-label-width} and passed on. (Note that we
20057 did not think to include this in the varlist when we first proposed it.)
20058
20059 To make a complete vertical axis label, a tic mark is concatenated
20060 with a number; and the two together may be preceded by one or more
20061 spaces depending on how long the number is. The label consists of
20062 three parts: the (optional) leading spaces, the number, and the tic
20063 mark. The function is passed the value of the number for the specific
20064 row, and the value of the width of the top line, which is calculated
20065 (just once) by @code{print-graph}.
20066
20067 @smallexample
20068 @group
20069 (defun Y-axis-element (number full-Y-label-width)
20070 "Construct a NUMBERed label element.
20071 A numbered element looks like this ` 5 - ',
20072 and is padded as needed so all line up with
20073 the element for the largest number."
20074 @end group
20075 @group
20076 (let* ((leading-spaces
20077 (- full-Y-label-width
20078 (length
20079 (concat (number-to-string number)
20080 Y-axis-tic)))))
20081 @end group
20082 @group
20083 (concat
20084 (make-string leading-spaces ? )
20085 (number-to-string number)
20086 Y-axis-tic)))
20087 @end group
20088 @end smallexample
20089
20090 The @code{Y-axis-element} function concatenates together the leading
20091 spaces, if any; the number, as a string; and the tic mark.
20092
20093 To figure out how many leading spaces the label will need, the
20094 function subtracts the actual length of the label---the length of the
20095 number plus the length of the tic mark---from the desired label width.
20096
20097 @findex make-string
20098 Blank spaces are inserted using the @code{make-string} function. This
20099 function takes two arguments: the first tells it how long the string
20100 will be and the second is a symbol for the character to insert, in a
20101 special format. The format is a question mark followed by a blank
20102 space, like this, @samp{? }. @xref{Character Type, , Character Type,
20103 elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
20104 syntax for characters. (Of course, you might want to replace the
20105 blank space by some other character @dots{} You know what to do.)
20106
20107 The @code{number-to-string} function is used in the concatenation
20108 expression, to convert the number to a string that is concatenated
20109 with the leading spaces and the tic mark.
20110
20111 @node Y-axis-column
20112 @appendixsubsec Create a Y Axis Column
20113
20114 The preceding functions provide all the tools needed to construct a
20115 function that generates a list of numbered and blank strings to insert
20116 as the label for the vertical axis:
20117
20118 @findex Y-axis-column
20119 @smallexample
20120 @group
20121 (defun Y-axis-column (height width-of-label)
20122 "Construct list of Y axis labels and blank strings.
20123 For HEIGHT of line above base and WIDTH-OF-LABEL."
20124 (let (Y-axis)
20125 @group
20126 @end group
20127 (while (> height 1)
20128 (if (zerop (% height Y-axis-label-spacing))
20129 ;; @r{Insert label.}
20130 (setq Y-axis
20131 (cons
20132 (Y-axis-element height width-of-label)
20133 Y-axis))
20134 @group
20135 @end group
20136 ;; @r{Else, insert blanks.}
20137 (setq Y-axis
20138 (cons
20139 (make-string width-of-label ? )
20140 Y-axis)))
20141 (setq height (1- height)))
20142 ;; @r{Insert base line.}
20143 (setq Y-axis
20144 (cons (Y-axis-element 1 width-of-label) Y-axis))
20145 (nreverse Y-axis)))
20146 @end group
20147 @end smallexample
20148
20149 In this function, we start with the value of @code{height} and
20150 repetitively subtract one from its value. After each subtraction, we
20151 test to see whether the value is an integral multiple of the
20152 @code{Y-axis-label-spacing}. If it is, we construct a numbered label
20153 using the @code{Y-axis-element} function; if not, we construct a
20154 blank label using the @code{make-string} function. The base line
20155 consists of the number one followed by a tic mark.
20156
20157 @need 2000
20158 @node print-Y-axis Penultimate
20159 @appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
20160
20161 The list constructed by the @code{Y-axis-column} function is passed to
20162 the @code{print-Y-axis} function, which inserts the list as a column.
20163
20164 @findex print-Y-axis
20165 @smallexample
20166 @group
20167 (defun print-Y-axis (height full-Y-label-width)
20168 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
20169 Height must be the maximum height of the graph.
20170 Full width is the width of the highest label element."
20171 ;; Value of height and full-Y-label-width
20172 ;; are passed by `print-graph'.
20173 @end group
20174 @group
20175 (let ((start (point)))
20176 (insert-rectangle
20177 (Y-axis-column height full-Y-label-width))
20178 ;; @r{Place point ready for inserting graph.}
20179 (goto-char start)
20180 ;; @r{Move point forward by value of} full-Y-label-width
20181 (forward-char full-Y-label-width)))
20182 @end group
20183 @end smallexample
20184
20185 The @code{print-Y-axis} uses the @code{insert-rectangle} function to
20186 insert the Y axis labels created by the @code{Y-axis-column} function.
20187 In addition, it places point at the correct position for printing the body of
20188 the graph.
20189
20190 You can test @code{print-Y-axis}:
20191
20192 @enumerate
20193 @item
20194 Install
20195
20196 @smallexample
20197 @group
20198 Y-axis-label-spacing
20199 Y-axis-tic
20200 Y-axis-element
20201 Y-axis-column
20202 print-Y-axis
20203 @end group
20204 @end smallexample
20205
20206 @item
20207 Copy the following expression:
20208
20209 @smallexample
20210 (print-Y-axis 12 5)
20211 @end smallexample
20212
20213 @item
20214 Switch to the @file{*scratch*} buffer and place the cursor where you
20215 want the axis labels to start.
20216
20217 @item
20218 Type @kbd{M-:} (@code{eval-expression}).
20219
20220 @item
20221 Yank the @code{graph-body-print} expression into the minibuffer
20222 with @kbd{C-y} (@code{yank)}.
20223
20224 @item
20225 Press @key{RET} to evaluate the expression.
20226 @end enumerate
20227
20228 Emacs will print labels vertically, the top one being @w{@samp{10 -@w{
20229 }}}. (The @code{print-graph} function will pass the value of
20230 @code{height-of-top-line}, which in this case will end up as 15,
20231 thereby getting rid of what might appear as a bug.)
20232
20233 @need 2000
20234 @node print-X-axis
20235 @appendixsec The @code{print-X-axis} Function
20236 @cindex Axis, print horizontal
20237 @cindex X axis printing
20238 @cindex Print horizontal axis
20239 @cindex Horizontal axis printing
20240
20241 X axis labels are much like Y axis labels, except that the ticks are on a
20242 line above the numbers. Labels should look like this:
20243
20244 @smallexample
20245 @group
20246 | | | |
20247 1 5 10 15
20248 @end group
20249 @end smallexample
20250
20251 The first tic is under the first column of the graph and is preceded by
20252 several blank spaces. These spaces provide room in rows above for the Y
20253 axis labels. The second, third, fourth, and subsequent ticks are all
20254 spaced equally, according to the value of @code{X-axis-label-spacing}.
20255
20256 The second row of the X axis consists of numbers, preceded by several
20257 blank spaces and also separated according to the value of the variable
20258 @code{X-axis-label-spacing}.
20259
20260 The value of the variable @code{X-axis-label-spacing} should itself be
20261 measured in units of @code{symbol-width}, since you may want to change
20262 the width of the symbols that you are using to print the body of the
20263 graph without changing the ways the graph is labeled.
20264
20265 @menu
20266 * Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
20267 * X Axis Tic Marks:: Create tic marks for the horizontal axis.
20268 @end menu
20269
20270 @ifnottex
20271 @node Similarities differences
20272 @unnumberedsubsec Similarities and differences
20273 @end ifnottex
20274
20275 The @code{print-X-axis} function is constructed in more or less the
20276 same fashion as the @code{print-Y-axis} function except that it has
20277 two lines: the line of tic marks and the numbers. We will write a
20278 separate function to print each line and then combine them within the
20279 @code{print-X-axis} function.
20280
20281 This is a three step process:
20282
20283 @enumerate
20284 @item
20285 Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
20286
20287 @item
20288 Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
20289
20290 @item
20291 Write a function to print both lines, the @code{print-X-axis} function,
20292 using @code{print-X-axis-tic-line} and
20293 @code{print-X-axis-numbered-line}.
20294 @end enumerate
20295
20296 @node X Axis Tic Marks
20297 @appendixsubsec X Axis Tic Marks
20298
20299 The first function should print the X axis tic marks. We must specify
20300 the tic marks themselves and their spacing:
20301
20302 @smallexample
20303 @group
20304 (defvar X-axis-label-spacing
20305 (if (boundp 'graph-blank)
20306 (* 5 (length graph-blank)) 5)
20307 "Number of units from one X axis label to next.")
20308 @end group
20309 @end smallexample
20310
20311 @noindent
20312 (Note that the value of @code{graph-blank} is set by another
20313 @code{defvar}. The @code{boundp} predicate checks whether it has
20314 already been set; @code{boundp} returns @code{nil} if it has not. If
20315 @code{graph-blank} were unbound and we did not use this conditional
20316 construction, in a recent GNU Emacs, we would enter the debugger and
20317 see an error message saying @samp{@w{Debugger entered--Lisp error:}
20318 @w{(void-variable graph-blank)}}.)
20319
20320 @need 1200
20321 Here is the @code{defvar} for @code{X-axis-tic-symbol}:
20322
20323 @smallexample
20324 @group
20325 (defvar X-axis-tic-symbol "|"
20326 "String to insert to point to a column in X axis.")
20327 @end group
20328 @end smallexample
20329
20330 @need 1250
20331 The goal is to make a line that looks like this:
20332
20333 @smallexample
20334 | | | |
20335 @end smallexample
20336
20337 The first tic is indented so that it is under the first column, which is
20338 indented to provide space for the Y axis labels.
20339
20340 A tic element consists of the blank spaces that stretch from one tic to
20341 the next plus a tic symbol. The number of blanks is determined by the
20342 width of the tic symbol and the @code{X-axis-label-spacing}.
20343
20344 @need 1250
20345 The code looks like this:
20346
20347 @smallexample
20348 @group
20349 ;;; X-axis-tic-element
20350 @dots{}
20351 (concat
20352 (make-string
20353 ;; @r{Make a string of blanks.}
20354 (- (* symbol-width X-axis-label-spacing)
20355 (length X-axis-tic-symbol))
20356 ? )
20357 ;; @r{Concatenate blanks with tic symbol.}
20358 X-axis-tic-symbol)
20359 @dots{}
20360 @end group
20361 @end smallexample
20362
20363 Next, we determine how many blanks are needed to indent the first tic
20364 mark to the first column of the graph. This uses the value of
20365 @code{full-Y-label-width} passed it by the @code{print-graph} function.
20366
20367 @need 1250
20368 The code to make @code{X-axis-leading-spaces}
20369 looks like this:
20370
20371 @smallexample
20372 @group
20373 ;; X-axis-leading-spaces
20374 @dots{}
20375 (make-string full-Y-label-width ? )
20376 @dots{}
20377 @end group
20378 @end smallexample
20379
20380 We also need to determine the length of the horizontal axis, which is
20381 the length of the numbers list, and the number of ticks in the horizontal
20382 axis:
20383
20384 @smallexample
20385 @group
20386 ;; X-length
20387 @dots{}
20388 (length numbers-list)
20389 @end group
20390
20391 @group
20392 ;; tic-width
20393 @dots{}
20394 (* symbol-width X-axis-label-spacing)
20395 @end group
20396
20397 @group
20398 ;; number-of-X-ticks
20399 (if (zerop (% (X-length tic-width)))
20400 (/ (X-length tic-width))
20401 (1+ (/ (X-length tic-width))))
20402 @end group
20403 @end smallexample
20404
20405 @need 1250
20406 All this leads us directly to the function for printing the X axis tic line:
20407
20408 @findex print-X-axis-tic-line
20409 @smallexample
20410 @group
20411 (defun print-X-axis-tic-line
20412 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20413 "Print ticks for X axis."
20414 (insert X-axis-leading-spaces)
20415 (insert X-axis-tic-symbol) ; @r{Under first column.}
20416 @end group
20417 @group
20418 ;; @r{Insert second tic in the right spot.}
20419 (insert (concat
20420 (make-string
20421 (- (* symbol-width X-axis-label-spacing)
20422 ;; @r{Insert white space up to second tic symbol.}
20423 (* 2 (length X-axis-tic-symbol)))
20424 ? )
20425 X-axis-tic-symbol))
20426 @end group
20427 @group
20428 ;; @r{Insert remaining ticks.}
20429 (while (> number-of-X-tics 1)
20430 (insert X-axis-tic-element)
20431 (setq number-of-X-tics (1- number-of-X-tics))))
20432 @end group
20433 @end smallexample
20434
20435 The line of numbers is equally straightforward:
20436
20437 @need 1250
20438 First, we create a numbered element with blank spaces before each number:
20439
20440 @findex X-axis-element
20441 @smallexample
20442 @group
20443 (defun X-axis-element (number)
20444 "Construct a numbered X axis element."
20445 (let ((leading-spaces
20446 (- (* symbol-width X-axis-label-spacing)
20447 (length (number-to-string number)))))
20448 (concat (make-string leading-spaces ? )
20449 (number-to-string number))))
20450 @end group
20451 @end smallexample
20452
20453 Next, we create the function to print the numbered line, starting with
20454 the number ``1'' under the first column:
20455
20456 @findex print-X-axis-numbered-line
20457 @smallexample
20458 @group
20459 (defun print-X-axis-numbered-line
20460 (number-of-X-tics X-axis-leading-spaces)
20461 "Print line of X-axis numbers"
20462 (let ((number X-axis-label-spacing))
20463 (insert X-axis-leading-spaces)
20464 (insert "1")
20465 @end group
20466 @group
20467 (insert (concat
20468 (make-string
20469 ;; @r{Insert white space up to next number.}
20470 (- (* symbol-width X-axis-label-spacing) 2)
20471 ? )
20472 (number-to-string number)))
20473 @end group
20474 @group
20475 ;; @r{Insert remaining numbers.}
20476 (setq number (+ number X-axis-label-spacing))
20477 (while (> number-of-X-tics 1)
20478 (insert (X-axis-element number))
20479 (setq number (+ number X-axis-label-spacing))
20480 (setq number-of-X-tics (1- number-of-X-tics)))))
20481 @end group
20482 @end smallexample
20483
20484 Finally, we need to write the @code{print-X-axis} that uses
20485 @code{print-X-axis-tic-line} and
20486 @code{print-X-axis-numbered-line}.
20487
20488 The function must determine the local values of the variables used by both
20489 @code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
20490 then it must call them. Also, it must print the carriage return that
20491 separates the two lines.
20492
20493 The function consists of a varlist that specifies five local variables,
20494 and calls to each of the two line printing functions:
20495
20496 @findex print-X-axis
20497 @smallexample
20498 @group
20499 (defun print-X-axis (numbers-list)
20500 "Print X axis labels to length of NUMBERS-LIST."
20501 (let* ((leading-spaces
20502 (make-string full-Y-label-width ? ))
20503 @end group
20504 @group
20505 ;; symbol-width @r{is provided by} graph-body-print
20506 (tic-width (* symbol-width X-axis-label-spacing))
20507 (X-length (length numbers-list))
20508 @end group
20509 @group
20510 (X-tic
20511 (concat
20512 (make-string
20513 @end group
20514 @group
20515 ;; @r{Make a string of blanks.}
20516 (- (* symbol-width X-axis-label-spacing)
20517 (length X-axis-tic-symbol))
20518 ? )
20519 @end group
20520 @group
20521 ;; @r{Concatenate blanks with tic symbol.}
20522 X-axis-tic-symbol))
20523 @end group
20524 @group
20525 (tic-number
20526 (if (zerop (% X-length tic-width))
20527 (/ X-length tic-width)
20528 (1+ (/ X-length tic-width)))))
20529 @end group
20530 @group
20531 (print-X-axis-tic-line tic-number leading-spaces X-tic)
20532 (insert "\n")
20533 (print-X-axis-numbered-line tic-number leading-spaces)))
20534 @end group
20535 @end smallexample
20536
20537 @need 1250
20538 You can test @code{print-X-axis}:
20539
20540 @enumerate
20541 @item
20542 Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
20543 @code{print-X-axis-tic-line}, as well as @code{X-axis-element},
20544 @code{print-X-axis-numbered-line}, and @code{print-X-axis}.
20545
20546 @item
20547 Copy the following expression:
20548
20549 @smallexample
20550 @group
20551 (progn
20552 (let ((full-Y-label-width 5)
20553 (symbol-width 1))
20554 (print-X-axis
20555 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
20556 @end group
20557 @end smallexample
20558
20559 @item
20560 Switch to the @file{*scratch*} buffer and place the cursor where you
20561 want the axis labels to start.
20562
20563 @item
20564 Type @kbd{M-:} (@code{eval-expression}).
20565
20566 @item
20567 Yank the test expression into the minibuffer
20568 with @kbd{C-y} (@code{yank)}.
20569
20570 @item
20571 Press @key{RET} to evaluate the expression.
20572 @end enumerate
20573
20574 @need 1250
20575 Emacs will print the horizontal axis like this:
20576 @sp 1
20577
20578 @smallexample
20579 @group
20580 | | | | |
20581 1 5 10 15 20
20582 @end group
20583 @end smallexample
20584
20585 @node Print Whole Graph
20586 @appendixsec Printing the Whole Graph
20587 @cindex Printing the whole graph
20588 @cindex Whole graph printing
20589 @cindex Graph, printing all
20590
20591 Now we are nearly ready to print the whole graph.
20592
20593 The function to print the graph with the proper labels follows the
20594 outline we created earlier (@pxref{Full Graph, , A Graph with Labeled
20595 Axes}), but with additions.
20596
20597 @need 1250
20598 Here is the outline:
20599
20600 @smallexample
20601 @group
20602 (defun print-graph (numbers-list)
20603 "@var{documentation}@dots{}"
20604 (let ((height @dots{}
20605 @dots{}))
20606 @end group
20607 @group
20608 (print-Y-axis height @dots{} )
20609 (graph-body-print numbers-list)
20610 (print-X-axis @dots{} )))
20611 @end group
20612 @end smallexample
20613
20614 @menu
20615 * The final version:: A few changes.
20616 * Test print-graph:: Run a short test.
20617 * Graphing words in defuns:: Executing the final code.
20618 * lambda:: How to write an anonymous function.
20619 * mapcar:: Apply a function to elements of a list.
20620 * Another Bug:: Yet another bug @dots{} most insidious.
20621 * Final printed graph:: The graph itself!
20622 @end menu
20623
20624 @ifnottex
20625 @node The final version
20626 @unnumberedsubsec Changes for the Final Version
20627 @end ifnottex
20628
20629 The final version is different from what we planned in two ways:
20630 first, it contains additional values calculated once in the varlist;
20631 second, it carries an option to specify the labels' increment per row.
20632 This latter feature turns out to be essential; otherwise, a graph may
20633 have more rows than fit on a display or on a sheet of paper.
20634
20635 @need 1500
20636 This new feature requires a change to the @code{Y-axis-column}
20637 function, to add @code{vertical-step} to it. The function looks like
20638 this:
20639
20640 @findex Y-axis-column @r{Final version.}
20641 @smallexample
20642 @group
20643 ;;; @r{Final version.}
20644 (defun Y-axis-column
20645 (height width-of-label &optional vertical-step)
20646 "Construct list of labels for Y axis.
20647 HEIGHT is maximum height of graph.
20648 WIDTH-OF-LABEL is maximum width of label.
20649 VERTICAL-STEP, an option, is a positive integer
20650 that specifies how much a Y axis label increments
20651 for each line. For example, a step of 5 means
20652 that each line is five units of the graph."
20653 @end group
20654 @group
20655 (let (Y-axis
20656 (number-per-line (or vertical-step 1)))
20657 (while (> height 1)
20658 (if (zerop (% height Y-axis-label-spacing))
20659 @end group
20660 @group
20661 ;; @r{Insert label.}
20662 (setq Y-axis
20663 (cons
20664 (Y-axis-element
20665 (* height number-per-line)
20666 width-of-label)
20667 Y-axis))
20668 @end group
20669 @group
20670 ;; @r{Else, insert blanks.}
20671 (setq Y-axis
20672 (cons
20673 (make-string width-of-label ? )
20674 Y-axis)))
20675 (setq height (1- height)))
20676 @end group
20677 @group
20678 ;; @r{Insert base line.}
20679 (setq Y-axis (cons (Y-axis-element
20680 (or vertical-step 1)
20681 width-of-label)
20682 Y-axis))
20683 (nreverse Y-axis)))
20684 @end group
20685 @end smallexample
20686
20687 The values for the maximum height of graph and the width of a symbol
20688 are computed by @code{print-graph} in its @code{let} expression; so
20689 @code{graph-body-print} must be changed to accept them.
20690
20691 @findex graph-body-print @r{Final version.}
20692 @smallexample
20693 @group
20694 ;;; @r{Final version.}
20695 (defun graph-body-print (numbers-list height symbol-width)
20696 "Print a bar graph of the NUMBERS-LIST.
20697 The numbers-list consists of the Y-axis values.
20698 HEIGHT is maximum height of graph.
20699 SYMBOL-WIDTH is number of each column."
20700 @end group
20701 @group
20702 (let (from-position)
20703 (while numbers-list
20704 (setq from-position (point))
20705 (insert-rectangle
20706 (column-of-graph height (car numbers-list)))
20707 (goto-char from-position)
20708 (forward-char symbol-width)
20709 @end group
20710 @group
20711 ;; @r{Draw graph column by column.}
20712 (sit-for 0)
20713 (setq numbers-list (cdr numbers-list)))
20714 ;; @r{Place point for X axis labels.}
20715 (forward-line height)
20716 (insert "\n")))
20717 @end group
20718 @end smallexample
20719
20720 @need 1250
20721 Finally, the code for the @code{print-graph} function:
20722
20723 @findex print-graph @r{Final version.}
20724 @smallexample
20725 @group
20726 ;;; @r{Final version.}
20727 (defun print-graph
20728 (numbers-list &optional vertical-step)
20729 "Print labeled bar graph of the NUMBERS-LIST.
20730 The numbers-list consists of the Y-axis values.
20731 @end group
20732
20733 @group
20734 Optionally, VERTICAL-STEP, a positive integer,
20735 specifies how much a Y axis label increments for
20736 each line. For example, a step of 5 means that
20737 each row is five units."
20738 @end group
20739 @group
20740 (let* ((symbol-width (length graph-blank))
20741 ;; @code{height} @r{is both the largest number}
20742 ;; @r{and the number with the most digits.}
20743 (height (apply 'max numbers-list))
20744 @end group
20745 @group
20746 (height-of-top-line
20747 (if (zerop (% height Y-axis-label-spacing))
20748 height
20749 ;; @r{else}
20750 (* (1+ (/ height Y-axis-label-spacing))
20751 Y-axis-label-spacing)))
20752 @end group
20753 @group
20754 (vertical-step (or vertical-step 1))
20755 (full-Y-label-width
20756 (length
20757 @end group
20758 @group
20759 (concat
20760 (number-to-string
20761 (* height-of-top-line vertical-step))
20762 Y-axis-tic))))
20763 @end group
20764
20765 @group
20766 (print-Y-axis
20767 height-of-top-line full-Y-label-width vertical-step)
20768 @end group
20769 @group
20770 (graph-body-print
20771 numbers-list height-of-top-line symbol-width)
20772 (print-X-axis numbers-list)))
20773 @end group
20774 @end smallexample
20775
20776 @node Test print-graph
20777 @appendixsubsec Testing @code{print-graph}
20778
20779 @need 1250
20780 We can test the @code{print-graph} function with a short list of numbers:
20781
20782 @enumerate
20783 @item
20784 Install the final versions of @code{Y-axis-column},
20785 @code{graph-body-print}, and @code{print-graph} (in addition to the
20786 rest of the code.)
20787
20788 @item
20789 Copy the following expression:
20790
20791 @smallexample
20792 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
20793 @end smallexample
20794
20795 @item
20796 Switch to the @file{*scratch*} buffer and place the cursor where you
20797 want the axis labels to start.
20798
20799 @item
20800 Type @kbd{M-:} (@code{eval-expression}).
20801
20802 @item
20803 Yank the test expression into the minibuffer
20804 with @kbd{C-y} (@code{yank)}.
20805
20806 @item
20807 Press @key{RET} to evaluate the expression.
20808 @end enumerate
20809
20810 @need 1250
20811 Emacs will print a graph that looks like this:
20812
20813 @smallexample
20814 @group
20815 10 -
20816
20817
20818 *
20819 ** *
20820 5 - **** *
20821 **** ***
20822 * *********
20823 ************
20824 1 - *************
20825
20826 | | | |
20827 1 5 10 15
20828 @end group
20829 @end smallexample
20830
20831 @need 1200
20832 On the other hand, if you pass @code{print-graph} a
20833 @code{vertical-step} value of 2, by evaluating this expression:
20834
20835 @smallexample
20836 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
20837 @end smallexample
20838
20839 @need 1250
20840 @noindent
20841 The graph looks like this:
20842
20843 @smallexample
20844 @group
20845 20 -
20846
20847
20848 *
20849 ** *
20850 10 - **** *
20851 **** ***
20852 * *********
20853 ************
20854 2 - *************
20855
20856 | | | |
20857 1 5 10 15
20858 @end group
20859 @end smallexample
20860
20861 @noindent
20862 (A question: is the `2' on the bottom of the vertical axis a bug or a
20863 feature? If you think it is a bug, and should be a `1' instead, (or
20864 even a `0'), you can modify the sources.)
20865
20866 @node Graphing words in defuns
20867 @appendixsubsec Graphing Numbers of Words and Symbols
20868
20869 Now for the graph for which all this code was written: a graph that
20870 shows how many function definitions contain fewer than 10 words and
20871 symbols, how many contain between 10 and 19 words and symbols, how
20872 many contain between 20 and 29 words and symbols, and so on.
20873
20874 This is a multi-step process. First make sure you have loaded all the
20875 requisite code.
20876
20877 @need 1500
20878 It is a good idea to reset the value of @code{top-of-ranges} in case
20879 you have set it to some different value. You can evaluate the
20880 following:
20881
20882 @smallexample
20883 @group
20884 (setq top-of-ranges
20885 '(10 20 30 40 50
20886 60 70 80 90 100
20887 110 120 130 140 150
20888 160 170 180 190 200
20889 210 220 230 240 250
20890 260 270 280 290 300)
20891 @end group
20892 @end smallexample
20893
20894 @noindent
20895 Next create a list of the number of words and symbols in each range.
20896
20897 @need 1500
20898 @noindent
20899 Evaluate the following:
20900
20901 @smallexample
20902 @group
20903 (setq list-for-graph
20904 (defuns-per-range
20905 (sort
20906 (recursive-lengths-list-many-files
20907 (directory-files "/usr/local/emacs/lisp"
20908 t ".+el$"))
20909 '<)
20910 top-of-ranges))
20911 @end group
20912 @end smallexample
20913
20914 @noindent
20915 On my old machine, this took about an hour. It looked though 303 Lisp
20916 files in my copy of Emacs version 19.23. After all that computing,
20917 the @code{list-for-graph} had this value:
20918
20919 @smallexample
20920 @group
20921 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
20922 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20923 @end group
20924 @end smallexample
20925
20926 @noindent
20927 This means that my copy of Emacs had 537 function definitions with
20928 fewer than 10 words or symbols in them, 1,027 function definitions
20929 with 10 to 19 words or symbols in them, 955 function definitions with
20930 20 to 29 words or symbols in them, and so on.
20931
20932 Clearly, just by looking at this list we can see that most function
20933 definitions contain ten to thirty words and symbols.
20934
20935 Now for printing. We do @emph{not} want to print a graph that is
20936 1,030 lines high @dots{} Instead, we should print a graph that is
20937 fewer than twenty-five lines high. A graph that height can be
20938 displayed on almost any monitor, and easily printed on a sheet of paper.
20939
20940 This means that each value in @code{list-for-graph} must be reduced to
20941 one-fiftieth its present value.
20942
20943 Here is a short function to do just that, using two functions we have
20944 not yet seen, @code{mapcar} and @code{lambda}.
20945
20946 @smallexample
20947 @group
20948 (defun one-fiftieth (full-range)
20949 "Return list, each number one-fiftieth of previous."
20950 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20951 @end group
20952 @end smallexample
20953
20954 @node lambda
20955 @appendixsubsec A @code{lambda} Expression: Useful Anonymity
20956 @cindex Anonymous function
20957 @findex lambda
20958
20959 @code{lambda} is the symbol for an anonymous function, a function
20960 without a name. Every time you use an anonymous function, you need to
20961 include its whole body.
20962
20963 @need 1250
20964 @noindent
20965 Thus,
20966
20967 @smallexample
20968 (lambda (arg) (/ arg 50))
20969 @end smallexample
20970
20971 @noindent
20972 is a function definition that says `return the value resulting from
20973 dividing whatever is passed to me as @code{arg} by 50'.
20974
20975 @need 1200
20976 Earlier, for example, we had a function @code{multiply-by-seven}; it
20977 multiplied its argument by 7. This function is similar, except it
20978 divides its argument by 50; and, it has no name. The anonymous
20979 equivalent of @code{multiply-by-seven} is:
20980
20981 @smallexample
20982 (lambda (number) (* 7 number))
20983 @end smallexample
20984
20985 @noindent
20986 (@xref{defun, , The @code{defun} Special Form}.)
20987
20988 @need 1250
20989 @noindent
20990 If we want to multiply 3 by 7, we can write:
20991
20992 @c !!! Clear print-postscript-figures if the computer formatting this
20993 @c document is too small and cannot handle all the diagrams and figures.
20994 @c clear print-postscript-figures
20995 @c set print-postscript-figures
20996 @c lambda example diagram #1
20997 @ifnottex
20998 @smallexample
20999 @group
21000 (multiply-by-seven 3)
21001 \_______________/ ^
21002 | |
21003 function argument
21004 @end group
21005 @end smallexample
21006 @end ifnottex
21007 @ifset print-postscript-figures
21008 @sp 1
21009 @tex
21010 @center @image{lambda-1}
21011 %%%% old method of including an image
21012 % \input /usr/local/lib/tex/inputs/psfig.tex
21013 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
21014 % \catcode`\@=0 %
21015 @end tex
21016 @sp 1
21017 @end ifset
21018 @ifclear print-postscript-figures
21019 @iftex
21020 @smallexample
21021 @group
21022 (multiply-by-seven 3)
21023 \_______________/ ^
21024 | |
21025 function argument
21026 @end group
21027 @end smallexample
21028 @end iftex
21029 @end ifclear
21030
21031 @noindent
21032 This expression returns 21.
21033
21034 @need 1250
21035 @noindent
21036 Similarly, we can write:
21037
21038 @c lambda example diagram #2
21039 @ifnottex
21040 @smallexample
21041 @group
21042 ((lambda (number) (* 7 number)) 3)
21043 \____________________________/ ^
21044 | |
21045 anonymous function argument
21046 @end group
21047 @end smallexample
21048 @end ifnottex
21049 @ifset print-postscript-figures
21050 @sp 1
21051 @tex
21052 @center @image{lambda-2}
21053 %%%% old method of including an image
21054 % \input /usr/local/lib/tex/inputs/psfig.tex
21055 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
21056 % \catcode`\@=0 %
21057 @end tex
21058 @sp 1
21059 @end ifset
21060 @ifclear print-postscript-figures
21061 @iftex
21062 @smallexample
21063 @group
21064 ((lambda (number) (* 7 number)) 3)
21065 \____________________________/ ^
21066 | |
21067 anonymous function argument
21068 @end group
21069 @end smallexample
21070 @end iftex
21071 @end ifclear
21072
21073 @need 1250
21074 @noindent
21075 If we want to divide 100 by 50, we can write:
21076
21077 @c lambda example diagram #3
21078 @ifnottex
21079 @smallexample
21080 @group
21081 ((lambda (arg) (/ arg 50)) 100)
21082 \______________________/ \_/
21083 | |
21084 anonymous function argument
21085 @end group
21086 @end smallexample
21087 @end ifnottex
21088 @ifset print-postscript-figures
21089 @sp 1
21090 @tex
21091 @center @image{lambda-3}
21092 %%%% old method of including an image
21093 % \input /usr/local/lib/tex/inputs/psfig.tex
21094 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
21095 % \catcode`\@=0 %
21096 @end tex
21097 @sp 1
21098 @end ifset
21099 @ifclear print-postscript-figures
21100 @iftex
21101 @smallexample
21102 @group
21103 ((lambda (arg) (/ arg 50)) 100)
21104 \______________________/ \_/
21105 | |
21106 anonymous function argument
21107 @end group
21108 @end smallexample
21109 @end iftex
21110 @end ifclear
21111
21112 @noindent
21113 This expression returns 2. The 100 is passed to the function, which
21114 divides that number by 50.
21115
21116 @xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
21117 Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
21118 expressions derive from the Lambda Calculus.
21119
21120 @node mapcar
21121 @appendixsubsec The @code{mapcar} Function
21122 @findex mapcar
21123
21124 @code{mapcar} is a function that calls its first argument with each
21125 element of its second argument, in turn. The second argument must be
21126 a sequence.
21127
21128 The @samp{map} part of the name comes from the mathematical phrase,
21129 `mapping over a domain', meaning to apply a function to each of the
21130 elements in a domain. The mathematical phrase is based on the
21131 metaphor of a surveyor walking, one step at a time, over an area he is
21132 mapping. And @samp{car}, of course, comes from the Lisp notion of the
21133 first of a list.
21134
21135 @need 1250
21136 @noindent
21137 For example,
21138
21139 @smallexample
21140 @group
21141 (mapcar '1+ '(2 4 6))
21142 @result{} (3 5 7)
21143 @end group
21144 @end smallexample
21145
21146 @noindent
21147 The function @code{1+} which adds one to its argument, is executed on
21148 @emph{each} element of the list, and a new list is returned.
21149
21150 Contrast this with @code{apply}, which applies its first argument to
21151 all the remaining.
21152 (@xref{Readying a Graph, , Readying a Graph}, for a explanation of
21153 @code{apply}.)
21154
21155 @need 1250
21156 In the definition of @code{one-fiftieth}, the first argument is the
21157 anonymous function:
21158
21159 @smallexample
21160 (lambda (arg) (/ arg 50))
21161 @end smallexample
21162
21163 @noindent
21164 and the second argument is @code{full-range}, which will be bound to
21165 @code{list-for-graph}.
21166
21167 @need 1250
21168 The whole expression looks like this:
21169
21170 @smallexample
21171 (mapcar '(lambda (arg) (/ arg 50)) full-range))
21172 @end smallexample
21173
21174 @xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
21175 Lisp Reference Manual}, for more about @code{mapcar}.
21176
21177 Using the @code{one-fiftieth} function, we can generate a list in
21178 which each element is one-fiftieth the size of the corresponding
21179 element in @code{list-for-graph}.
21180
21181 @smallexample
21182 @group
21183 (setq fiftieth-list-for-graph
21184 (one-fiftieth list-for-graph))
21185 @end group
21186 @end smallexample
21187
21188 @need 1250
21189 The resulting list looks like this:
21190
21191 @smallexample
21192 @group
21193 (10 20 19 15 11 9 6 5 4 3 3 2 2
21194 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
21195 @end group
21196 @end smallexample
21197
21198 @noindent
21199 This, we are almost ready to print! (We also notice the loss of
21200 information: many of the higher ranges are 0, meaning that fewer than
21201 50 defuns had that many words or symbols---but not necessarily meaning
21202 that none had that many words or symbols.)
21203
21204 @node Another Bug
21205 @appendixsubsec Another Bug @dots{} Most Insidious
21206 @cindex Bug, most insidious type
21207 @cindex Insidious type of bug
21208
21209 I said `almost ready to print'! Of course, there is a bug in the
21210 @code{print-graph} function @dots{} It has a @code{vertical-step}
21211 option, but not a @code{horizontal-step} option. The
21212 @code{top-of-range} scale goes from 10 to 300 by tens. But the
21213 @code{print-graph} function will print only by ones.
21214
21215 This is a classic example of what some consider the most insidious
21216 type of bug, the bug of omission. This is not the kind of bug you can
21217 find by studying the code, for it is not in the code; it is an omitted
21218 feature. Your best actions are to try your program early and often;
21219 and try to arrange, as much as you can, to write code that is easy to
21220 understand and easy to change. Try to be aware, whenever you can,
21221 that whatever you have written, @emph{will} be rewritten, if not soon,
21222 eventually. A hard maxim to follow.
21223
21224 It is the @code{print-X-axis-numbered-line} function that needs the
21225 work; and then the @code{print-X-axis} and the @code{print-graph}
21226 functions need to be adapted. Not much needs to be done; there is one
21227 nicety: the numbers ought to line up under the tic marks. This takes
21228 a little thought.
21229
21230 @need 1250
21231 Here is the corrected @code{print-X-axis-numbered-line}:
21232
21233 @smallexample
21234 @group
21235 (defun print-X-axis-numbered-line
21236 (number-of-X-tics X-axis-leading-spaces
21237 &optional horizontal-step)
21238 "Print line of X-axis numbers"
21239 (let ((number X-axis-label-spacing)
21240 (horizontal-step (or horizontal-step 1)))
21241 @end group
21242 @group
21243 (insert X-axis-leading-spaces)
21244 ;; @r{Delete extra leading spaces.}
21245 (delete-char
21246 (- (1-
21247 (length (number-to-string horizontal-step)))))
21248 (insert (concat
21249 (make-string
21250 @end group
21251 @group
21252 ;; @r{Insert white space.}
21253 (- (* symbol-width
21254 X-axis-label-spacing)
21255 (1-
21256 (length
21257 (number-to-string horizontal-step)))
21258 2)
21259 ? )
21260 (number-to-string
21261 (* number horizontal-step))))
21262 @end group
21263 @group
21264 ;; @r{Insert remaining numbers.}
21265 (setq number (+ number X-axis-label-spacing))
21266 (while (> number-of-X-tics 1)
21267 (insert (X-axis-element
21268 (* number horizontal-step)))
21269 (setq number (+ number X-axis-label-spacing))
21270 (setq number-of-X-tics (1- number-of-X-tics)))))
21271 @end group
21272 @end smallexample
21273
21274 @need 1500
21275 If you are reading this in Info, you can see the new versions of
21276 @code{print-X-axis} @code{print-graph} and evaluate them. If you are
21277 reading this in a printed book, you can see the changed lines here
21278 (the full text is too much to print).
21279
21280 @iftex
21281 @smallexample
21282 @group
21283 (defun print-X-axis (numbers-list horizontal-step)
21284 @dots{}
21285 (print-X-axis-numbered-line
21286 tic-number leading-spaces horizontal-step))
21287 @end group
21288 @end smallexample
21289
21290 @smallexample
21291 @group
21292 (defun print-graph
21293 (numbers-list
21294 &optional vertical-step horizontal-step)
21295 @dots{}
21296 (print-X-axis numbers-list horizontal-step))
21297 @end group
21298 @end smallexample
21299 @end iftex
21300
21301 @ifnottex
21302 @smallexample
21303 @group
21304 (defun print-X-axis (numbers-list horizontal-step)
21305 "Print X axis labels to length of NUMBERS-LIST.
21306 Optionally, HORIZONTAL-STEP, a positive integer,
21307 specifies how much an X axis label increments for
21308 each column."
21309 @end group
21310 @group
21311 ;; Value of symbol-width and full-Y-label-width
21312 ;; are passed by `print-graph'.
21313 (let* ((leading-spaces
21314 (make-string full-Y-label-width ? ))
21315 ;; symbol-width @r{is provided by} graph-body-print
21316 (tic-width (* symbol-width X-axis-label-spacing))
21317 (X-length (length numbers-list))
21318 @end group
21319 @group
21320 (X-tic
21321 (concat
21322 (make-string
21323 ;; @r{Make a string of blanks.}
21324 (- (* symbol-width X-axis-label-spacing)
21325 (length X-axis-tic-symbol))
21326 ? )
21327 @end group
21328 @group
21329 ;; @r{Concatenate blanks with tic symbol.}
21330 X-axis-tic-symbol))
21331 (tic-number
21332 (if (zerop (% X-length tic-width))
21333 (/ X-length tic-width)
21334 (1+ (/ X-length tic-width)))))
21335 @end group
21336
21337 @group
21338 (print-X-axis-tic-line
21339 tic-number leading-spaces X-tic)
21340 (insert "\n")
21341 (print-X-axis-numbered-line
21342 tic-number leading-spaces horizontal-step)))
21343 @end group
21344 @end smallexample
21345
21346 @smallexample
21347 @group
21348 (defun print-graph
21349 (numbers-list &optional vertical-step horizontal-step)
21350 "Print labeled bar graph of the NUMBERS-LIST.
21351 The numbers-list consists of the Y-axis values.
21352 @end group
21353
21354 @group
21355 Optionally, VERTICAL-STEP, a positive integer,
21356 specifies how much a Y axis label increments for
21357 each line. For example, a step of 5 means that
21358 each row is five units.
21359 @end group
21360
21361 @group
21362 Optionally, HORIZONTAL-STEP, a positive integer,
21363 specifies how much an X axis label increments for
21364 each column."
21365 (let* ((symbol-width (length graph-blank))
21366 ;; @code{height} @r{is both the largest number}
21367 ;; @r{and the number with the most digits.}
21368 (height (apply 'max numbers-list))
21369 @end group
21370 @group
21371 (height-of-top-line
21372 (if (zerop (% height Y-axis-label-spacing))
21373 height
21374 ;; @r{else}
21375 (* (1+ (/ height Y-axis-label-spacing))
21376 Y-axis-label-spacing)))
21377 @end group
21378 @group
21379 (vertical-step (or vertical-step 1))
21380 (full-Y-label-width
21381 (length
21382 (concat
21383 (number-to-string
21384 (* height-of-top-line vertical-step))
21385 Y-axis-tic))))
21386 @end group
21387 @group
21388 (print-Y-axis
21389 height-of-top-line full-Y-label-width vertical-step)
21390 (graph-body-print
21391 numbers-list height-of-top-line symbol-width)
21392 (print-X-axis numbers-list horizontal-step)))
21393 @end group
21394 @end smallexample
21395 @end ifnottex
21396
21397 @c qqq
21398 @ignore
21399 Graphing Definitions Re-listed
21400
21401 @need 1250
21402 Here are all the graphing definitions in their final form:
21403
21404 @smallexample
21405 @group
21406 (defvar top-of-ranges
21407 '(10 20 30 40 50
21408 60 70 80 90 100
21409 110 120 130 140 150
21410 160 170 180 190 200
21411 210 220 230 240 250)
21412 "List specifying ranges for `defuns-per-range'.")
21413 @end group
21414
21415 @group
21416 (defvar graph-symbol "*"
21417 "String used as symbol in graph, usually an asterisk.")
21418 @end group
21419
21420 @group
21421 (defvar graph-blank " "
21422 "String used as blank in graph, usually a blank space.
21423 graph-blank must be the same number of columns wide
21424 as graph-symbol.")
21425 @end group
21426
21427 @group
21428 (defvar Y-axis-tic " - "
21429 "String that follows number in a Y axis label.")
21430 @end group
21431
21432 @group
21433 (defvar Y-axis-label-spacing 5
21434 "Number of lines from one Y axis label to next.")
21435 @end group
21436
21437 @group
21438 (defvar X-axis-tic-symbol "|"
21439 "String to insert to point to a column in X axis.")
21440 @end group
21441
21442 @group
21443 (defvar X-axis-label-spacing
21444 (if (boundp 'graph-blank)
21445 (* 5 (length graph-blank)) 5)
21446 "Number of units from one X axis label to next.")
21447 @end group
21448 @end smallexample
21449
21450 @smallexample
21451 @group
21452 (defun count-words-in-defun ()
21453 "Return the number of words and symbols in a defun."
21454 (beginning-of-defun)
21455 (let ((count 0)
21456 (end (save-excursion (end-of-defun) (point))))
21457 @end group
21458
21459 @group
21460 (while
21461 (and (< (point) end)
21462 (re-search-forward
21463 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
21464 end t))
21465 (setq count (1+ count)))
21466 count))
21467 @end group
21468 @end smallexample
21469
21470 @smallexample
21471 @group
21472 (defun lengths-list-file (filename)
21473 "Return list of definitions' lengths within FILE.
21474 The returned list is a list of numbers.
21475 Each number is the number of words or
21476 symbols in one function definition."
21477 @end group
21478
21479 @group
21480 (message "Working on `%s' ... " filename)
21481 (save-excursion
21482 (let ((buffer (find-file-noselect filename))
21483 (lengths-list))
21484 (set-buffer buffer)
21485 (setq buffer-read-only t)
21486 (widen)
21487 (goto-char (point-min))
21488 @end group
21489
21490 @group
21491 (while (re-search-forward "^(defun" nil t)
21492 (setq lengths-list
21493 (cons (count-words-in-defun) lengths-list)))
21494 (kill-buffer buffer)
21495 lengths-list)))
21496 @end group
21497 @end smallexample
21498
21499 @smallexample
21500 @group
21501 (defun lengths-list-many-files (list-of-files)
21502 "Return list of lengths of defuns in LIST-OF-FILES."
21503 (let (lengths-list)
21504 ;;; @r{true-or-false-test}
21505 (while list-of-files
21506 (setq lengths-list
21507 (append
21508 lengths-list
21509 @end group
21510 @group
21511 ;;; @r{Generate a lengths' list.}
21512 (lengths-list-file
21513 (expand-file-name (car list-of-files)))))
21514 ;;; @r{Make files' list shorter.}
21515 (setq list-of-files (cdr list-of-files)))
21516 ;;; @r{Return final value of lengths' list.}
21517 lengths-list))
21518 @end group
21519 @end smallexample
21520
21521 @smallexample
21522 @group
21523 (defun defuns-per-range (sorted-lengths top-of-ranges)
21524 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
21525 (let ((top-of-range (car top-of-ranges))
21526 (number-within-range 0)
21527 defuns-per-range-list)
21528 @end group
21529
21530 @group
21531 ;; @r{Outer loop.}
21532 (while top-of-ranges
21533
21534 ;; @r{Inner loop.}
21535 (while (and
21536 ;; @r{Need number for numeric test.}
21537 (car sorted-lengths)
21538 (< (car sorted-lengths) top-of-range))
21539
21540 ;; @r{Count number of definitions within current range.}
21541 (setq number-within-range (1+ number-within-range))
21542 (setq sorted-lengths (cdr sorted-lengths)))
21543 @end group
21544
21545 @group
21546 ;; @r{Exit inner loop but remain within outer loop.}
21547
21548 (setq defuns-per-range-list
21549 (cons number-within-range defuns-per-range-list))
21550 (setq number-within-range 0) ; @r{Reset count to zero.}
21551
21552 ;; @r{Move to next range.}
21553 (setq top-of-ranges (cdr top-of-ranges))
21554 ;; @r{Specify next top of range value.}
21555 (setq top-of-range (car top-of-ranges)))
21556 @end group
21557
21558 @group
21559 ;; @r{Exit outer loop and count the number of defuns larger than}
21560 ;; @r{ the largest top-of-range value.}
21561 (setq defuns-per-range-list
21562 (cons
21563 (length sorted-lengths)
21564 defuns-per-range-list))
21565
21566 ;; @r{Return a list of the number of definitions within each range,}
21567 ;; @r{ smallest to largest.}
21568 (nreverse defuns-per-range-list)))
21569 @end group
21570 @end smallexample
21571
21572 @smallexample
21573 @group
21574 (defun column-of-graph (max-graph-height actual-height)
21575 "Return list of MAX-GRAPH-HEIGHT strings;
21576 ACTUAL-HEIGHT are graph-symbols.
21577 The graph-symbols are contiguous entries at the end
21578 of the list.
21579 The list will be inserted as one column of a graph.
21580 The strings are either graph-blank or graph-symbol."
21581 @end group
21582
21583 @group
21584 (let ((insert-list nil)
21585 (number-of-top-blanks
21586 (- max-graph-height actual-height)))
21587
21588 ;; @r{Fill in @code{graph-symbols}.}
21589 (while (> actual-height 0)
21590 (setq insert-list (cons graph-symbol insert-list))
21591 (setq actual-height (1- actual-height)))
21592 @end group
21593
21594 @group
21595 ;; @r{Fill in @code{graph-blanks}.}
21596 (while (> number-of-top-blanks 0)
21597 (setq insert-list (cons graph-blank insert-list))
21598 (setq number-of-top-blanks
21599 (1- number-of-top-blanks)))
21600
21601 ;; @r{Return whole list.}
21602 insert-list))
21603 @end group
21604 @end smallexample
21605
21606 @smallexample
21607 @group
21608 (defun Y-axis-element (number full-Y-label-width)
21609 "Construct a NUMBERed label element.
21610 A numbered element looks like this ` 5 - ',
21611 and is padded as needed so all line up with
21612 the element for the largest number."
21613 @end group
21614 @group
21615 (let* ((leading-spaces
21616 (- full-Y-label-width
21617 (length
21618 (concat (number-to-string number)
21619 Y-axis-tic)))))
21620 @end group
21621 @group
21622 (concat
21623 (make-string leading-spaces ? )
21624 (number-to-string number)
21625 Y-axis-tic)))
21626 @end group
21627 @end smallexample
21628
21629 @smallexample
21630 @group
21631 (defun print-Y-axis
21632 (height full-Y-label-width &optional vertical-step)
21633 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
21634 Height must be the maximum height of the graph.
21635 Full width is the width of the highest label element.
21636 Optionally, print according to VERTICAL-STEP."
21637 @end group
21638 @group
21639 ;; Value of height and full-Y-label-width
21640 ;; are passed by `print-graph'.
21641 (let ((start (point)))
21642 (insert-rectangle
21643 (Y-axis-column height full-Y-label-width vertical-step))
21644 @end group
21645 @group
21646 ;; @r{Place point ready for inserting graph.}
21647 (goto-char start)
21648 ;; @r{Move point forward by value of} full-Y-label-width
21649 (forward-char full-Y-label-width)))
21650 @end group
21651 @end smallexample
21652
21653 @smallexample
21654 @group
21655 (defun print-X-axis-tic-line
21656 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
21657 "Print ticks for X axis."
21658 (insert X-axis-leading-spaces)
21659 (insert X-axis-tic-symbol) ; @r{Under first column.}
21660 @end group
21661 @group
21662 ;; @r{Insert second tic in the right spot.}
21663 (insert (concat
21664 (make-string
21665 (- (* symbol-width X-axis-label-spacing)
21666 ;; @r{Insert white space up to second tic symbol.}
21667 (* 2 (length X-axis-tic-symbol)))
21668 ? )
21669 X-axis-tic-symbol))
21670 @end group
21671 @group
21672 ;; @r{Insert remaining ticks.}
21673 (while (> number-of-X-tics 1)
21674 (insert X-axis-tic-element)
21675 (setq number-of-X-tics (1- number-of-X-tics))))
21676 @end group
21677 @end smallexample
21678
21679 @smallexample
21680 @group
21681 (defun X-axis-element (number)
21682 "Construct a numbered X axis element."
21683 (let ((leading-spaces
21684 (- (* symbol-width X-axis-label-spacing)
21685 (length (number-to-string number)))))
21686 (concat (make-string leading-spaces ? )
21687 (number-to-string number))))
21688 @end group
21689 @end smallexample
21690
21691 @smallexample
21692 @group
21693 (defun graph-body-print (numbers-list height symbol-width)
21694 "Print a bar graph of the NUMBERS-LIST.
21695 The numbers-list consists of the Y-axis values.
21696 HEIGHT is maximum height of graph.
21697 SYMBOL-WIDTH is number of each column."
21698 @end group
21699 @group
21700 (let (from-position)
21701 (while numbers-list
21702 (setq from-position (point))
21703 (insert-rectangle
21704 (column-of-graph height (car numbers-list)))
21705 (goto-char from-position)
21706 (forward-char symbol-width)
21707 @end group
21708 @group
21709 ;; @r{Draw graph column by column.}
21710 (sit-for 0)
21711 (setq numbers-list (cdr numbers-list)))
21712 ;; @r{Place point for X axis labels.}
21713 (forward-line height)
21714 (insert "\n")))
21715 @end group
21716 @end smallexample
21717
21718 @smallexample
21719 @group
21720 (defun Y-axis-column
21721 (height width-of-label &optional vertical-step)
21722 "Construct list of labels for Y axis.
21723 HEIGHT is maximum height of graph.
21724 WIDTH-OF-LABEL is maximum width of label.
21725 @end group
21726 @group
21727 VERTICAL-STEP, an option, is a positive integer
21728 that specifies how much a Y axis label increments
21729 for each line. For example, a step of 5 means
21730 that each line is five units of the graph."
21731 (let (Y-axis
21732 (number-per-line (or vertical-step 1)))
21733 @end group
21734 @group
21735 (while (> height 1)
21736 (if (zerop (% height Y-axis-label-spacing))
21737 ;; @r{Insert label.}
21738 (setq Y-axis
21739 (cons
21740 (Y-axis-element
21741 (* height number-per-line)
21742 width-of-label)
21743 Y-axis))
21744 @end group
21745 @group
21746 ;; @r{Else, insert blanks.}
21747 (setq Y-axis
21748 (cons
21749 (make-string width-of-label ? )
21750 Y-axis)))
21751 (setq height (1- height)))
21752 @end group
21753 @group
21754 ;; @r{Insert base line.}
21755 (setq Y-axis (cons (Y-axis-element
21756 (or vertical-step 1)
21757 width-of-label)
21758 Y-axis))
21759 (nreverse Y-axis)))
21760 @end group
21761 @end smallexample
21762
21763 @smallexample
21764 @group
21765 (defun print-X-axis-numbered-line
21766 (number-of-X-tics X-axis-leading-spaces
21767 &optional horizontal-step)
21768 "Print line of X-axis numbers"
21769 (let ((number X-axis-label-spacing)
21770 (horizontal-step (or horizontal-step 1)))
21771 @end group
21772 @group
21773 (insert X-axis-leading-spaces)
21774 ;; line up number
21775 (delete-char (- (1- (length (number-to-string horizontal-step)))))
21776 (insert (concat
21777 (make-string
21778 ;; @r{Insert white space up to next number.}
21779 (- (* symbol-width X-axis-label-spacing)
21780 (1- (length (number-to-string horizontal-step)))
21781 2)
21782 ? )
21783 (number-to-string (* number horizontal-step))))
21784 @end group
21785 @group
21786 ;; @r{Insert remaining numbers.}
21787 (setq number (+ number X-axis-label-spacing))
21788 (while (> number-of-X-tics 1)
21789 (insert (X-axis-element (* number horizontal-step)))
21790 (setq number (+ number X-axis-label-spacing))
21791 (setq number-of-X-tics (1- number-of-X-tics)))))
21792 @end group
21793 @end smallexample
21794
21795 @smallexample
21796 @group
21797 (defun print-X-axis (numbers-list horizontal-step)
21798 "Print X axis labels to length of NUMBERS-LIST.
21799 Optionally, HORIZONTAL-STEP, a positive integer,
21800 specifies how much an X axis label increments for
21801 each column."
21802 @end group
21803 @group
21804 ;; Value of symbol-width and full-Y-label-width
21805 ;; are passed by `print-graph'.
21806 (let* ((leading-spaces
21807 (make-string full-Y-label-width ? ))
21808 ;; symbol-width @r{is provided by} graph-body-print
21809 (tic-width (* symbol-width X-axis-label-spacing))
21810 (X-length (length numbers-list))
21811 @end group
21812 @group
21813 (X-tic
21814 (concat
21815 (make-string
21816 ;; @r{Make a string of blanks.}
21817 (- (* symbol-width X-axis-label-spacing)
21818 (length X-axis-tic-symbol))
21819 ? )
21820 @end group
21821 @group
21822 ;; @r{Concatenate blanks with tic symbol.}
21823 X-axis-tic-symbol))
21824 (tic-number
21825 (if (zerop (% X-length tic-width))
21826 (/ X-length tic-width)
21827 (1+ (/ X-length tic-width)))))
21828 @end group
21829
21830 @group
21831 (print-X-axis-tic-line
21832 tic-number leading-spaces X-tic)
21833 (insert "\n")
21834 (print-X-axis-numbered-line
21835 tic-number leading-spaces horizontal-step)))
21836 @end group
21837 @end smallexample
21838
21839 @smallexample
21840 @group
21841 (defun one-fiftieth (full-range)
21842 "Return list, each number of which is 1/50th previous."
21843 (mapcar '(lambda (arg) (/ arg 50)) full-range))
21844 @end group
21845 @end smallexample
21846
21847 @smallexample
21848 @group
21849 (defun print-graph
21850 (numbers-list &optional vertical-step horizontal-step)
21851 "Print labeled bar graph of the NUMBERS-LIST.
21852 The numbers-list consists of the Y-axis values.
21853 @end group
21854
21855 @group
21856 Optionally, VERTICAL-STEP, a positive integer,
21857 specifies how much a Y axis label increments for
21858 each line. For example, a step of 5 means that
21859 each row is five units.
21860 @end group
21861
21862 @group
21863 Optionally, HORIZONTAL-STEP, a positive integer,
21864 specifies how much an X axis label increments for
21865 each column."
21866 (let* ((symbol-width (length graph-blank))
21867 ;; @code{height} @r{is both the largest number}
21868 ;; @r{and the number with the most digits.}
21869 (height (apply 'max numbers-list))
21870 @end group
21871 @group
21872 (height-of-top-line
21873 (if (zerop (% height Y-axis-label-spacing))
21874 height
21875 ;; @r{else}
21876 (* (1+ (/ height Y-axis-label-spacing))
21877 Y-axis-label-spacing)))
21878 @end group
21879 @group
21880 (vertical-step (or vertical-step 1))
21881 (full-Y-label-width
21882 (length
21883 (concat
21884 (number-to-string
21885 (* height-of-top-line vertical-step))
21886 Y-axis-tic))))
21887 @end group
21888 @group
21889
21890 (print-Y-axis
21891 height-of-top-line full-Y-label-width vertical-step)
21892 (graph-body-print
21893 numbers-list height-of-top-line symbol-width)
21894 (print-X-axis numbers-list horizontal-step)))
21895 @end group
21896 @end smallexample
21897 @c qqq
21898 @end ignore
21899
21900 @page
21901 @node Final printed graph
21902 @appendixsubsec The Printed Graph
21903
21904 When made and installed, you can call the @code{print-graph} command
21905 like this:
21906 @sp 1
21907
21908 @smallexample
21909 @group
21910 (print-graph fiftieth-list-for-graph 50 10)
21911 @end group
21912 @end smallexample
21913 @sp 1
21914
21915 @noindent
21916 Here is the graph:
21917 @sp 2
21918
21919 @smallexample
21920 @group
21921 1000 - *
21922 **
21923 **
21924 **
21925 **
21926 750 - ***
21927 ***
21928 ***
21929 ***
21930 ****
21931 500 - *****
21932 ******
21933 ******
21934 ******
21935 *******
21936 250 - ********
21937 ********* *
21938 *********** *
21939 ************* *
21940 50 - ***************** * *
21941 | | | | | | | |
21942 10 50 100 150 200 250 300 350
21943 @end group
21944 @end smallexample
21945
21946 @sp 2
21947
21948 @noindent
21949 The largest group of functions contain 10 -- 19 words and symbols each.
21950
21951 @node Free Software and Free Manuals
21952 @appendix Free Software and Free Manuals
21953
21954 @strong{by Richard M. Stallman}
21955 @sp 1
21956
21957 The biggest deficiency in free operating systems is not in the
21958 software---it is the lack of good free manuals that we can include in
21959 these systems. Many of our most important programs do not come with
21960 full manuals. Documentation is an essential part of any software
21961 package; when an important free software package does not come with a
21962 free manual, that is a major gap. We have many such gaps today.
21963
21964 Once upon a time, many years ago, I thought I would learn Perl. I got
21965 a copy of a free manual, but I found it hard to read. When I asked
21966 Perl users about alternatives, they told me that there were better
21967 introductory manuals---but those were not free.
21968
21969 Why was this? The authors of the good manuals had written them for
21970 O'Reilly Associates, which published them with restrictive terms---no
21971 copying, no modification, source files not available---which exclude
21972 them from the free software community.
21973
21974 That wasn't the first time this sort of thing has happened, and (to
21975 our community's great loss) it was far from the last. Proprietary
21976 manual publishers have enticed a great many authors to restrict their
21977 manuals since then. Many times I have heard a GNU user eagerly tell me
21978 about a manual that he is writing, with which he expects to help the
21979 GNU project---and then had my hopes dashed, as he proceeded to explain
21980 that he had signed a contract with a publisher that would restrict it
21981 so that we cannot use it.
21982
21983 Given that writing good English is a rare skill among programmers, we
21984 can ill afford to lose manuals this way.
21985
21986 Free documentation, like free software, is a matter of freedom, not
21987 price. The problem with these manuals was not that O'Reilly Associates
21988 charged a price for printed copies---that in itself is fine. The Free
21989 Software Foundation @uref{http://shop.fsf.org, sells printed copies} of
21990 free @uref{http://www.gnu.org/doc/doc.html, GNU manuals}, too.
21991 But GNU manuals are available in source code form, while these manuals
21992 are available only on paper. GNU manuals come with permission to copy
21993 and modify; the Perl manuals do not. These restrictions are the
21994 problems.
21995
21996 The criterion for a free manual is pretty much the same as for free
21997 software: it is a matter of giving all users certain
21998 freedoms. Redistribution (including commercial redistribution) must be
21999 permitted, so that the manual can accompany every copy of the program,
22000 on-line or on paper. Permission for modification is crucial too.
22001
22002 As a general rule, I don't believe that it is essential for people to
22003 have permission to modify all sorts of articles and books. The issues
22004 for writings are not necessarily the same as those for software. For
22005 example, I don't think you or I are obliged to give permission to
22006 modify articles like this one, which describe our actions and our
22007 views.
22008
22009 But there is a particular reason why the freedom to modify is crucial
22010 for documentation for free software. When people exercise their right
22011 to modify the software, and add or change its features, if they are
22012 conscientious they will change the manual too---so they can provide
22013 accurate and usable documentation with the modified program. A manual
22014 which forbids programmers to be conscientious and finish the job, or
22015 more precisely requires them to write a new manual from scratch if
22016 they change the program, does not fill our community's needs.
22017
22018 While a blanket prohibition on modification is unacceptable, some
22019 kinds of limits on the method of modification pose no problem. For
22020 example, requirements to preserve the original author's copyright
22021 notice, the distribution terms, or the list of authors, are ok. It is
22022 also no problem to require modified versions to include notice that
22023 they were modified, even to have entire sections that may not be
22024 deleted or changed, as long as these sections deal with nontechnical
22025 topics. (Some GNU manuals have them.)
22026
22027 These kinds of restrictions are not a problem because, as a practical
22028 matter, they don't stop the conscientious programmer from adapting the
22029 manual to fit the modified program. In other words, they don't block
22030 the free software community from making full use of the manual.
22031
22032 However, it must be possible to modify all the technical content of
22033 the manual, and then distribute the result in all the usual media,
22034 through all the usual channels; otherwise, the restrictions do block
22035 the community, the manual is not free, and so we need another manual.
22036
22037 Unfortunately, it is often hard to find someone to write another
22038 manual when a proprietary manual exists. The obstacle is that many
22039 users think that a proprietary manual is good enough---so they don't
22040 see the need to write a free manual. They do not see that the free
22041 operating system has a gap that needs filling.
22042
22043 Why do users think that proprietary manuals are good enough? Some have
22044 not considered the issue. I hope this article will do something to
22045 change that.
22046
22047 Other users consider proprietary manuals acceptable for the same
22048 reason so many people consider proprietary software acceptable: they
22049 judge in purely practical terms, not using freedom as a
22050 criterion. These people are entitled to their opinions, but since
22051 those opinions spring from values which do not include freedom, they
22052 are no guide for those of us who do value freedom.
22053
22054 Please spread the word about this issue. We continue to lose manuals
22055 to proprietary publishing. If we spread the word that proprietary
22056 manuals are not sufficient, perhaps the next person who wants to help
22057 GNU by writing documentation will realize, before it is too late, that
22058 he must above all make it free.
22059
22060 We can also encourage commercial publishers to sell free, copylefted
22061 manuals instead of proprietary ones. One way you can help this is to
22062 check the distribution terms of a manual before you buy it, and prefer
22063 copylefted manuals to non-copylefted ones.
22064
22065 @sp 2
22066 @noindent
22067 Note: The Free Software Foundation maintains a page on its Web site
22068 that lists free books available from other publishers:@*
22069 @uref{http://www.gnu.org/doc/other-free-books.html}
22070
22071 @node GNU Free Documentation License
22072 @appendix GNU Free Documentation License
22073
22074 @cindex FDL, GNU Free Documentation License
22075 @include doclicense.texi
22076
22077 @node Index
22078 @unnumbered Index
22079
22080 @ignore
22081 MENU ENTRY: NODE NAME.
22082 @end ignore
22083
22084 @printindex cp
22085
22086 @iftex
22087 @c Place biographical information on right-hand (verso) page
22088
22089 @tex
22090 \par\vfill\supereject
22091 \ifodd\pageno
22092 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22093 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
22094 %\page\hbox{}\page
22095 \else
22096 % \par\vfill\supereject
22097 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22098 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
22099 %\page\hbox{}%\page
22100 %\page\hbox{}%\page
22101 \fi
22102 @end tex
22103
22104 @c page
22105 @w{ }
22106
22107 @c ================ Biographical information ================
22108
22109 @w{ }
22110 @sp 8
22111 @center About the Author
22112 @sp 1
22113 @end iftex
22114
22115 @ifnottex
22116 @node About the Author
22117 @unnumbered About the Author
22118 @end ifnottex
22119
22120 @quotation
22121 Robert J. Chassell has worked with GNU Emacs since 1985. He writes
22122 and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
22123 world on software freedom. Chassell was a founding Director and
22124 Treasurer of the Free Software Foundation, Inc. He is co-author of
22125 the @cite{Texinfo} manual, and has edited more than a dozen other
22126 books. He graduated from Cambridge University, in England. He has an
22127 abiding interest in social and economic history and flies his own
22128 airplane.
22129 @end quotation
22130
22131 @c @page
22132 @c @w{ }
22133 @c
22134 @c @c Prevent page number on blank verso, so eject it first.
22135 @c @tex
22136 @c \par\vfill\supereject
22137 @c @end tex
22138
22139 @c @iftex
22140 @c @headings off
22141 @c @evenheading @thispage @| @| @thistitle
22142 @c @oddheading @| @| @thispage
22143 @c @end iftex
22144
22145 @bye