* admin/gitmerge.el (gitmerge-missing):
[emacs.git] / doc / lispintro / emacs-lisp-intro.texi
blob65ded50c3965afbfc73758a6c2181d698288de6d
1 \input texinfo                       @c -*- mode: texinfo; coding: utf-8 -*-
2 @comment %**start of header
3 @setfilename ../../info/eintr.info
4 @c setfilename emacs-lisp-intro.info
5 @c sethtmlfilename emacs-lisp-intro.html
6 @settitle Programming in Emacs Lisp
7 @include docstyle.texi
8 @syncodeindex vr cp
9 @syncodeindex fn cp
10 @finalout
12 @include emacsver.texi
14 @c ================ How to Print a Book in Various Sizes ================
16 @c This book can be printed in any of three different sizes.
17 @c Set the following @-commands appropriately.
19 @c     7 by 9.25 inches:
20 @c              @smallbook
21 @c              @clear largebook
23 @c     8.5 by 11 inches:
24 @c              @c smallbook
25 @c              @set largebook
27 @c     European A4 size paper:
28 @c              @c smallbook
29 @c              @afourpaper
30 @c              @set largebook
32 @c (Note: if you edit the book so as to change the length of the
33 @c table of contents, you may have to change the value of 'pageno' below.)
35 @c <<<< For hard copy printing, this file is now
36 @c      set for smallbook, which works for all sizes
37 @c      of paper, and with PostScript figures >>>>
39 @set smallbook
40 @ifset smallbook
41 @smallbook
42 @clear  largebook
43 @end ifset
45 @c ================ Included Figures ================
47 @c If you clear this, the figures will be printed as ASCII diagrams
48 @c rather than PostScript/PDF.
49 @c (This is not relevant to Info, since Info only handles ASCII.)
50 @set print-postscript-figures
51 @c clear print-postscript-figures
53 @comment %**end of header
55 @c per rms and peterb, use 10pt fonts for the main text, mostly to
56 @c save on paper cost.
57 @c Do this inside @tex for now, so current makeinfo does not complain.
58 @tex
59 @ifset smallbook
60 @fonttextsize 10
62 @end ifset
63 \global\hbadness=6666 % don't worry about not-too-underfull boxes
64 @end tex
66 @c These refer to the printed book sold by the FSF.
67 @set edition-number 3.10
68 @set update-date 28 October 2009
70 @c For next or subsequent edition:
71 @c   create function using with-output-to-temp-buffer
72 @c   create a major mode, with keymaps
73 @c   run an asynchronous process, like grep or diff
75 @c For 8.5 by 11 inch format: do not use such a small amount of
76 @c whitespace between paragraphs as smallbook format
77 @ifset largebook
78 @tex
79 \global\parskip 6pt plus 1pt
80 @end tex
81 @end ifset
83 @c For all sized formats:  print within-book cross
84 @c reference with ``...''  rather than [...]
86 @c This works with the texinfo.tex file, version 2003-05-04.08,
87 @c in the Texinfo version 4.6 of the 2003 Jun 13 distribution.
89 @tex
90 \if \xrefprintnodename
91  \global\def\xrefprintnodename#1{\unskip, ``#1''}
92  \else
93  \global\def\xrefprintnodename#1{ ``#1''}
94 \fi
95 % \global\def\xrefprintnodename#1{, ``#1''}
96 @end tex
98 @c ----------------------------------------------------
100 @dircategory Emacs lisp
101 @direntry
102 * Emacs Lisp Intro: (eintr).    A simple introduction to Emacs Lisp programming.
103 @end direntry
105 @copying
106 This is an @cite{Introduction to Programming in Emacs Lisp}, for
107 people who are not programmers.
108 @sp 1
109 @iftex
110 Edition @value{edition-number}, @value{update-date}
111 @end iftex
112 @ifnottex
113 Distributed with Emacs version @value{EMACSVER}.
114 @end ifnottex
115 @sp 1
116 Copyright @copyright{} 1990--1995, 1997, 2001--2017 Free Software
117 Foundation, Inc.
118 @sp 1
120 @iftex
121 Published by the:@*
123 GNU Press,               @hfill @uref{https://www.fsf.org/licensing/gnu-press/}@*
124 a division of the               @hfill email: @email{sales@@fsf.org}@*
125 Free Software Foundation, Inc.  @hfill Tel: +1 (617) 542-5942@*
126 51 Franklin Street, Fifth Floor @hfill Fax: +1 (617) 542-2652@*
127 Boston, MA 02110-1301 USA
128 @end iftex
130 @ifnottex
131 Printed copies available from @uref{https://shop.fsf.org/}. Published by:
133 @example
134 GNU Press,                        https://www.fsf.org/licensing/gnu-press/
135 a division of the                 email: sales@@fsf.org
136 Free Software Foundation, Inc.    Tel: +1 (617) 542-5942
137 51 Franklin Street, Fifth Floor   Fax: +1 (617) 542-2652
138 Boston, MA 02110-1301 USA
139 @end example
140 @end ifnottex
142 @sp 1
143 ISBN 1-882114-43-4
145 @quotation
146 Permission is granted to copy, distribute and/or modify this document
147 under the terms of the GNU Free Documentation License, Version 1.3 or
148 any later version published by the Free Software Foundation; there
149 being no Invariant Section, with the Front-Cover Texts being ``A GNU
150 Manual'', and with the Back-Cover Texts as in (a) below.  A copy of
151 the license is included in the section entitled ``GNU Free
152 Documentation License''.
154 (a) The FSF's Back-Cover Text is: ``You have the freedom to
155 copy and modify this GNU manual.  Buying copies from the FSF
156 supports it in developing GNU and promoting software freedom.''
157 @end quotation
158 @end copying
160 @c half title; two lines here, so do not use 'shorttitlepage'
161 @tex
162 {\begingroup%
163     \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
164         \endgroup}%
165 {\begingroup\hbox{}\vskip 0.25in \chaprm%
166         \centerline{Programming in Emacs Lisp}%
167         \endgroup\page\hbox{}\page}
168 @end tex
170 @titlepage
171 @sp 6
172 @center @titlefont{An Introduction to}
173 @sp 2
174 @center @titlefont{Programming in Emacs Lisp}
175 @sp 2
176 @center Revised Third Edition
177 @sp 4
178 @center by Robert J. Chassell
180 @page
181 @vskip 0pt plus 1filll
182 @insertcopying
183 @end titlepage
185 @iftex
186 @headings off
187 @evenheading @thispage @| @| @thischapter
188 @oddheading @thissection @| @| @thispage
189 @end iftex
191 @ifnothtml
192 @c     Keep T.O.C. short by tightening up for largebook
193 @ifset largebook
194 @tex
195 \global\parskip 2pt plus 1pt
196 \global\advance\baselineskip by -1pt
197 @end tex
198 @end ifset
199 @end ifnothtml
201 @shortcontents
202 @contents
204 @ifnottex
205 @node Top
206 @top An Introduction to Programming in Emacs Lisp
208 @ifset WWW_GNU_ORG
209 @html
210 <p>The homepage for GNU Emacs is at
211 <a href="/software/emacs/">https://www.gnu.org/software/emacs/</a>.<br>
212 To view this manual in other formats, click
213 <a href="/software/emacs/manual/eintr.html">here</a>.
214 @end html
215 @end ifset
217 @insertcopying
219 This master menu first lists each chapter and index; then it lists
220 every node in every chapter.
221 @end ifnottex
223 @c >>>> Set pageno appropriately <<<<
225 @c The first page of the Preface is a roman numeral; it is the first
226 @c right handed page after the Table of Contents; hence the following
227 @c setting must be for an odd negative number.
229 @c iftex
230 @c global@pageno = -11
231 @c end iftex
233 @set COUNT-WORDS count-words-example
234 @c Length of variable name chosen so that things still line up when expanded.
236 @menu
237 * Preface::                     What to look for.
238 * List Processing::             What is Lisp?
239 * Practicing Evaluation::       Running several programs.
240 * Writing Defuns::              How to write function definitions.
241 * Buffer Walk Through::         Exploring a few buffer-related functions.
242 * More Complex::                A few, even more complex functions.
243 * Narrowing & Widening::        Restricting your and Emacs attention to
244                                     a region.
245 * car cdr & cons::              Fundamental functions in Lisp.
246 * Cutting & Storing Text::      Removing text and saving it.
247 * List Implementation::         How lists are implemented in the computer.
248 * Yanking::                     Pasting stored text.
249 * Loops & Recursion::           How to repeat a process.
250 * Regexp Search::               Regular expression searches.
251 * Counting Words::              A review of repetition and regexps.
252 * Words in a defun::            Counting words in a @code{defun}.
253 * Readying a Graph::            A prototype graph printing function.
254 * Emacs Initialization::        How to write a @file{.emacs} file.
255 * Debugging::                   How to run the Emacs Lisp debuggers.
256 * Conclusion::                  Now you have the basics.
257 * the-the::                     An appendix: how to find reduplicated words.
258 * Kill Ring::                   An appendix: how the kill ring works.
259 * Full Graph::                  How to create a graph with labeled axes.
260 * Free Software and Free Manuals::
261 * GNU Free Documentation License::
262 * Index::
263 * About the Author::
265 @detailmenu
266  --- The Detailed Node Listing ---
268 Preface
270 * Why::                         Why learn Emacs Lisp?
271 * On Reading this Text::        Read, gain familiarity, pick up habits....
272 * Who You Are::                 For whom this is written.
273 * Lisp History::
274 * Note for Novices::            You can read this as a novice.
275 * Thank You::
277 List Processing
279 * Lisp Lists::                  What are lists?
280 * Run a Program::               Any list in Lisp is a program ready to run.
281 * Making Errors::               Generating an error message.
282 * Names & Definitions::         Names of symbols and function definitions.
283 * Lisp Interpreter::            What the Lisp interpreter does.
284 * Evaluation::                  Running a program.
285 * Variables::                   Returning a value from a variable.
286 * Arguments::                   Passing information to a function.
287 * set & setq::                  Setting the value of a variable.
288 * Summary::                     The major points.
289 * Error Message Exercises::
291 Lisp Lists
293 * Numbers Lists::               List have numbers, other lists, in them.
294 * Lisp Atoms::                  Elemental entities.
295 * Whitespace in Lists::         Formatting lists to be readable.
296 * Typing Lists::                How GNU Emacs helps you type lists.
298 The Lisp Interpreter
300 * Complications::               Variables, Special forms, Lists within.
301 * Byte Compiling::              Specially processing code for speed.
303 Evaluation
305 * How the Interpreter Acts::    Returns and Side Effects...
306 * Evaluating Inner Lists::      Lists within lists...
308 Variables
310 * fill-column Example::
311 * Void Function::               The error message for a symbol
312                                   without a function.
313 * Void Variable::               The error message for a symbol without a value.
315 Arguments
317 * Data types::                  Types of data passed to a function.
318 * Args as Variable or List::    An argument can be the value
319                                   of a variable or list.
320 * Variable Number of Arguments::  Some functions may take a
321                                   variable number of arguments.
322 * Wrong Type of Argument::      Passing an argument of the wrong type
323                                   to a function.
324 * message::                     A useful function for sending messages.
326 Setting the Value of a Variable
328 * Using set::                  Setting values.
329 * Using setq::                 Setting a quoted value.
330 * Counting::                   Using @code{setq} to count.
332 Practicing Evaluation
334 * How to Evaluate::            Typing editing commands or @kbd{C-x C-e}
335                                  causes evaluation.
336 * Buffer Names::               Buffers and files are different.
337 * Getting Buffers::            Getting a buffer itself, not merely its name.
338 * Switching Buffers::          How to change to another buffer.
339 * Buffer Size & Locations::    Where point is located and the size of
340                                the buffer.
341 * Evaluation Exercise::
343 How To Write Function Definitions
345 * Primitive Functions::
346 * defun::                        The @code{defun} macro.
347 * Install::                      Install a function definition.
348 * Interactive::                  Making a function interactive.
349 * Interactive Options::          Different options for @code{interactive}.
350 * Permanent Installation::       Installing code permanently.
351 * let::                          Creating and initializing local variables.
352 * if::                           What if?
353 * else::                         If--then--else expressions.
354 * Truth & Falsehood::            What Lisp considers false and true.
355 * save-excursion::               Keeping track of point and buffer.
356 * Review::
357 * defun Exercises::
359 Install a Function Definition
361 * Effect of installation::
362 * Change a defun::              How to change a function definition.
364 Make a Function Interactive
366 * Interactive multiply-by-seven::  An overview.
367 * multiply-by-seven in detail::    The interactive version.
369 @code{let}
371 * Prevent confusion::
372 * Parts of let Expression::
373 * Sample let Expression::
374 * Uninitialized let Variables::
376 The @code{if} Special Form
378 * if in more detail::
379 * type-of-animal in detail::    An example of an @code{if} expression.
381 Truth and Falsehood in Emacs Lisp
383 * nil explained::               @code{nil} has two meanings.
385 @code{save-excursion}
387 * Point and mark::              A review of various locations.
388 * Template for save-excursion::
390 A Few Buffer-Related Functions
392 * Finding More::                How to find more information.
393 * simplified-beginning-of-buffer::  Shows @code{goto-char},
394                                 @code{point-min}, and @code{push-mark}.
395 * mark-whole-buffer::           Almost the same as @code{beginning-of-buffer}.
396 * append-to-buffer::            Uses @code{save-excursion} and
397                                 @code{insert-buffer-substring}.
398 * Buffer Related Review::       Review.
399 * Buffer Exercises::
401 The Definition of @code{mark-whole-buffer}
403 * mark-whole-buffer overview::
404 * Body of mark-whole-buffer::   Only three lines of code.
406 The Definition of @code{append-to-buffer}
408 * append-to-buffer overview::
409 * append interactive::          A two part interactive expression.
410 * append-to-buffer body::       Incorporates a @code{let} expression.
411 * append save-excursion::       How the @code{save-excursion} works.
413 A Few More Complex Functions
415 * copy-to-buffer::              With @code{set-buffer}, @code{get-buffer-create}.
416 * insert-buffer::               Read-only, and with @code{or}.
417 * beginning-of-buffer::         Shows @code{goto-char},
418                                 @code{point-min}, and @code{push-mark}.
419 * Second Buffer Related Review::
420 * optional Exercise::
422 The Definition of @code{insert-buffer}
424 * insert-buffer code::
425 * insert-buffer interactive::   When you can read, but not write.
426 * insert-buffer body::          The body has an @code{or} and a @code{let}.
427 * if & or::                     Using an @code{if} instead of an @code{or}.
428 * Insert or::                   How the @code{or} expression works.
429 * Insert let::                  Two @code{save-excursion} expressions.
430 * New insert-buffer::
432 The Interactive Expression in @code{insert-buffer}
434 * Read-only buffer::            When a buffer cannot be modified.
435 * b for interactive::           An existing buffer or else its name.
437 Complete Definition of @code{beginning-of-buffer}
439 * Optional Arguments::
440 * beginning-of-buffer opt arg::  Example with optional argument.
441 * beginning-of-buffer complete::
443 @code{beginning-of-buffer} with an Argument
445 * Disentangle beginning-of-buffer::
446 * Large buffer case::
447 * Small buffer case::
449 Narrowing and Widening
451 * Narrowing advantages::        The advantages of narrowing
452 * save-restriction::            The @code{save-restriction} special form.
453 * what-line::                   The number of the line that point is on.
454 * narrow Exercise::
456 @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
458 * Strange Names::               An historical aside: why the strange names?
459 * car & cdr::                   Functions for extracting part of a list.
460 * cons::                        Constructing a list.
461 * nthcdr::                      Calling @code{cdr} repeatedly.
462 * nth::
463 * setcar::                      Changing the first element of a list.
464 * setcdr::                      Changing the rest of a list.
465 * cons Exercise::
467 @code{cons}
469 * Build a list::
470 * length::                      How to find the length of a list.
472 Cutting and Storing Text
474 * Storing Text::                Text is stored in a list.
475 * zap-to-char::                 Cutting out text up to a character.
476 * kill-region::                 Cutting text out of a region.
477 * copy-region-as-kill::         A definition for copying text.
478 * Digression into C::           Minor note on C programming language macros.
479 * defvar::                      How to give a variable an initial value.
480 * cons & search-fwd Review::
481 * search Exercises::
483 @code{zap-to-char}
485 * Complete zap-to-char::        The complete implementation.
486 * zap-to-char interactive::     A three part interactive expression.
487 * zap-to-char body::            A short overview.
488 * search-forward::              How to search for a string.
489 * progn::                       The @code{progn} special form.
490 * Summing up zap-to-char::      Using @code{point} and @code{search-forward}.
492 @code{kill-region}
494 * Complete kill-region::        The function definition.
495 * condition-case::              Dealing with a problem.
496 * Lisp macro::
498 @code{copy-region-as-kill}
500 * Complete copy-region-as-kill::  The complete function definition.
501 * copy-region-as-kill body::      The body of @code{copy-region-as-kill}.
503 The Body of @code{copy-region-as-kill}
505 * last-command & this-command::
506 * kill-append function::
507 * kill-new function::
509 Initializing a Variable with @code{defvar}
511 * See variable current value::
512 * defvar and asterisk::
514 How Lists are Implemented
516 * Lists diagrammed::
517 * Symbols as Chest::            Exploring a powerful metaphor.
518 * List Exercise::
520 Yanking Text Back
522 * Kill Ring Overview::
523 * kill-ring-yank-pointer::      The kill ring is a list.
524 * yank nthcdr Exercises::       The @code{kill-ring-yank-pointer} variable.
526 Loops and Recursion
528 * while::                       Causing a stretch of code to repeat.
529 * dolist dotimes::
530 * Recursion::                   Causing a function to call itself.
531 * Looping exercise::
533 @code{while}
535 * Looping with while::          Repeat so long as test returns true.
536 * Loop Example::                A @code{while} loop that uses a list.
537 * print-elements-of-list::      Uses @code{while}, @code{car}, @code{cdr}.
538 * Incrementing Loop::           A loop with an incrementing counter.
539 * Incrementing Loop Details::
540 * Decrementing Loop::           A loop with a decrementing counter.
542 Details of an Incrementing Loop
544 * Incrementing Example::        Counting pebbles in a triangle.
545 * Inc Example parts::           The parts of the function definition.
546 * Inc Example altogether::      Putting the function definition together.
548 Loop with a Decrementing Counter
550 * Decrementing Example::        More pebbles on the beach.
551 * Dec Example parts::           The parts of the function definition.
552 * Dec Example altogether::      Putting the function definition together.
554 Save your time: @code{dolist} and @code{dotimes}
556 * dolist::
557 * dotimes::
559 Recursion
561 * Building Robots::             Same model, different serial number ...
562 * Recursive Definition Parts::  Walk until you stop ...
563 * Recursion with list::         Using a list as the test whether to recurse.
564 * Recursive triangle function::
565 * Recursion with cond::
566 * Recursive Patterns::          Often used templates.
567 * No Deferment::                Don't store up work ...
568 * No deferment solution::
570 Recursion in Place of a Counter
572 * Recursive Example arg of 1 or 2::
573 * Recursive Example arg of 3 or 4::
575 Recursive Patterns
577 * Every::
578 * Accumulate::
579 * Keep::
581 Regular Expression Searches
583 * sentence-end::                The regular expression for @code{sentence-end}.
584 * re-search-forward::           Very similar to @code{search-forward}.
585 * forward-sentence::            A straightforward example of regexp search.
586 * forward-paragraph::           A somewhat complex example.
587 * Regexp Review::
588 * re-search Exercises::
590 @code{forward-sentence}
592 * Complete forward-sentence::
593 * fwd-sentence while loops::    Two @code{while} loops.
594 * fwd-sentence re-search::      A regular expression search.
596 @code{forward-paragraph}: a Goldmine of Functions
598 * forward-paragraph in brief::  Key parts of the function definition.
599 * fwd-para let::                The @code{let*} expression.
600 * fwd-para while::              The forward motion @code{while} loop.
602 Counting: Repetition and Regexps
604 * Why Count Words::
605 * @value{COUNT-WORDS}::         Use a regexp, but find a problem.
606 * recursive-count-words::       Start with case of no words in region.
607 * Counting Exercise::
609 The @code{@value{COUNT-WORDS}} Function
611 * Design @value{COUNT-WORDS}::  The definition using a @code{while} loop.
612 * Whitespace Bug::              The Whitespace Bug in @code{@value{COUNT-WORDS}}.
614 Counting Words in a @code{defun}
616 * Divide and Conquer::
617 * Words and Symbols::           What to count?
618 * Syntax::                      What constitutes a word or symbol?
619 * count-words-in-defun::        Very like @code{@value{COUNT-WORDS}}.
620 * Several defuns::              Counting several defuns in a file.
621 * Find a File::                 Do you want to look at a file?
622 * lengths-list-file::           A list of the lengths of many definitions.
623 * Several files::               Counting in definitions in different files.
624 * Several files recursively::   Recursively counting in different files.
625 * Prepare the data::            Prepare the data for display in a graph.
627 Count Words in @code{defuns} in Different Files
629 * lengths-list-many-files::     Return a list of the lengths of defuns.
630 * append::                      Attach one list to another.
632 Prepare the Data for Display in a Graph
634 * Data for Display in Detail::
635 * Sorting::                     Sorting lists.
636 * Files List::                  Making a list of files.
637 * Counting function definitions::
639 Readying a Graph
641 * Columns of a graph::
642 * graph-body-print::            How to print the body of a graph.
643 * recursive-graph-body-print::
644 * Printed Axes::
645 * Line Graph Exercise::
647 Your @file{.emacs} File
649 * Default Configuration::
650 * Site-wide Init::              You can write site-wide init files.
651 * defcustom::                   Emacs will write code for you.
652 * Beginning init File::         How to write a @file{.emacs} init file.
653 * Text and Auto-fill::          Automatically wrap lines.
654 * Mail Aliases::                Use abbreviations for email addresses.
655 * Indent Tabs Mode::            Don't use tabs with @TeX{}
656 * Keybindings::                 Create some personal keybindings.
657 * Keymaps::                     More about key binding.
658 * Loading Files::               Load (i.e., evaluate) files automatically.
659 * Autoload::                    Make functions available.
660 * Simple Extension::            Define a function; bind it to a key.
661 * X11 Colors::                  Colors in X.
662 * Miscellaneous::
663 * Mode Line::                   How to customize your mode line.
665 Debugging
667 * debug::                       How to use the built-in debugger.
668 * debug-on-entry::              Start debugging when you call a function.
669 * debug-on-quit::               Start debugging when you quit with @kbd{C-g}.
670 * edebug::                      How to use Edebug, a source level debugger.
671 * Debugging Exercises::
673 Handling the Kill Ring
675 * What the Kill Ring Does::
676 * current-kill::
677 * yank::                        Paste a copy of a clipped element.
678 * yank-pop::                    Insert element pointed to.
679 * ring file::
681 The @code{current-kill} Function
683 * Code for current-kill::
684 * Understanding current-kill::
686 @code{current-kill} in Outline
688 * Body of current-kill::
689 * Digression concerning error::  How to mislead humans, but not computers.
690 * Determining the Element::
692 A Graph with Labeled Axes
694 * Labeled Example::
695 * print-graph Varlist::         @code{let} expression in @code{print-graph}.
696 * print-Y-axis::                Print a label for the vertical axis.
697 * print-X-axis::                Print a horizontal label.
698 * Print Whole Graph::           The function to print a complete graph.
700 The @code{print-Y-axis} Function
702 * print-Y-axis in Detail::
703 * Height of label::             What height for the Y axis?
704 * Compute a Remainder::         How to compute the remainder of a division.
705 * Y Axis Element::              Construct a line for the Y axis.
706 * Y-axis-column::               Generate a list of Y axis labels.
707 * print-Y-axis Penultimate::    A not quite final version.
709 The @code{print-X-axis} Function
711 * Similarities differences::    Much like @code{print-Y-axis}, but not exactly.
712 * X Axis Tic Marks::            Create tic marks for the horizontal axis.
714 Printing the Whole Graph
716 * The final version::           A few changes.
717 * Test print-graph::            Run a short test.
718 * Graphing words in defuns::    Executing the final code.
719 * lambda::                      How to write an anonymous function.
720 * mapcar::                      Apply a function to elements of a list.
721 * Another Bug::                 Yet another bug @dots{} most insidious.
722 * Final printed graph::         The graph itself!
724 @end detailmenu
725 @end menu
727 @node Preface
728 @unnumbered Preface
730 Most of the GNU Emacs integrated environment is written in the programming
731 language called Emacs Lisp.  The code written in this programming
732 language is the software---the sets of instructions---that tell the
733 computer what to do when you give it commands.  Emacs is designed so
734 that you can write new code in Emacs Lisp and easily install it as an
735 extension to the editor.
737 (GNU Emacs is sometimes called an ``extensible editor'', but it does
738 much more than provide editing capabilities.  It is better to refer to
739 Emacs as an ``extensible computing environment''.  However, that
740 phrase is quite a mouthful.  It is easier to refer to Emacs simply as
741 an editor.  Moreover, everything you do in Emacs---find the Mayan date
742 and phases of the moon, simplify polynomials, debug code, manage
743 files, read letters, write books---all these activities are kinds of
744 editing in the most general sense of the word.)
746 @menu
747 * Why::                         Why learn Emacs Lisp?
748 * On Reading this Text::        Read, gain familiarity, pick up habits....
749 * Who You Are::                 For whom this is written.
750 * Lisp History::
751 * Note for Novices::            You can read this as a novice.
752 * Thank You::
753 @end menu
755 @ifnottex
756 @node Why
757 @unnumberedsec Why Study Emacs Lisp?
758 @end ifnottex
760 Although Emacs Lisp is usually thought of in association only with Emacs,
761 it is a full computer programming language.  You can use Emacs Lisp as
762 you would any other programming language.
764 Perhaps you want to understand programming; perhaps you want to extend
765 Emacs; or perhaps you want to become a programmer.  This introduction to
766 Emacs Lisp is designed to get you started: to guide you in learning the
767 fundamentals of programming, and more importantly, to show you how you
768 can teach yourself to go further.
770 @node On Reading this Text
771 @unnumberedsec On Reading this Text
773 All through this document, you will see little sample programs you can
774 run inside of Emacs.  If you read this document in Info inside of GNU
775 Emacs, you can run the programs as they appear.  (This is easy to do and
776 is explained when the examples are presented.)  Alternatively, you can
777 read this introduction as a printed book while sitting beside a computer
778 running Emacs.  (This is what I like to do; I like printed books.)  If
779 you don't have a running Emacs beside you, you can still read this book,
780 but in this case, it is best to treat it as a novel or as a travel guide
781 to a country not yet visited: interesting, but not the same as being
782 there.
784 Much of this introduction is dedicated to walkthroughs or guided tours
785 of code used in GNU Emacs.  These tours are designed for two purposes:
786 first, to give you familiarity with real, working code (code you use
787 every day); and, second, to give you familiarity with the way Emacs
788 works.  It is interesting to see how a working environment is
789 implemented.
790 Also, I
791 hope that you will pick up the habit of browsing through source code.
792 You can learn from it and mine it for ideas.  Having GNU Emacs is like
793 having a dragon's cave of treasures.
795 In addition to learning about Emacs as an editor and Emacs Lisp as a
796 programming language, the examples and guided tours will give you an
797 opportunity to get acquainted with Emacs as a Lisp programming
798 environment.  GNU Emacs supports programming and provides tools that
799 you will want to become comfortable using, such as @kbd{M-.} (the key
800 which invokes the @code{find-tag} command).  You will also learn about
801 buffers and other objects that are part of the environment.
802 Learning about these features of Emacs is like learning new routes
803 around your home town.
805 @ignore
806 In addition, I have written several programs as extended examples.
807 Although these are examples, the programs are real.  I use them.
808 Other people use them.  You may use them.  Beyond the fragments of
809 programs used for illustrations, there is very little in here that is
810 just for teaching purposes; what you see is used.  This is a great
811 advantage of Emacs Lisp: it is easy to learn to use it for work.
812 @end ignore
814 Finally, I hope to convey some of the skills for using Emacs to
815 learn aspects of programming that you don't know.  You can often use
816 Emacs to help you understand what puzzles you or to find out how to do
817 something new.  This self-reliance is not only a pleasure, but an
818 advantage.
820 @node Who You Are
821 @unnumberedsec For Whom This is Written
823 This text is written as an elementary introduction for people who are
824 not programmers.  If you are a programmer, you may not be satisfied with
825 this primer.  The reason is that you may have become expert at reading
826 reference manuals and be put off by the way this text is organized.
828 An expert programmer who reviewed this text said to me:
830 @quotation
831 @i{I prefer to learn from reference manuals.  I ``dive into'' each
832 paragraph, and ``come up for air'' between paragraphs.}
834 @i{When I get to the end of a paragraph, I assume that subject is
835 done, finished, that I know everything I need (with the
836 possible exception of the case when the next paragraph starts talking
837 about it in more detail).  I expect that a well written reference manual
838 will not have a lot of redundancy, and that it will have excellent
839 pointers to the (one) place where the information I want is.}
840 @end quotation
842 This introduction is not written for this person!
844 Firstly, I try to say everything at least three times: first, to
845 introduce it; second, to show it in context; and third, to show it in a
846 different context, or to review it.
848 Secondly, I hardly ever put all the information about a subject in one
849 place, much less in one paragraph.  To my way of thinking, that imposes
850 too heavy a burden on the reader.  Instead I try to explain only what
851 you need to know at the time.  (Sometimes I include a little extra
852 information so you won't be surprised later when the additional
853 information is formally introduced.)
855 When you read this text, you are not expected to learn everything the
856 first time.  Frequently, you need make only a nodding
857 acquaintance with some of the items mentioned.  My hope is that I have
858 structured the text and given you enough hints that you will be alert to
859 what is important, and concentrate on it.
861 You will need to dive into some paragraphs; there is no other way
862 to read them.  But I have tried to keep down the number of such
863 paragraphs.  This book is intended as an approachable hill, rather than
864 as a daunting mountain.
866 This introduction to @cite{Programming in Emacs Lisp} has a companion
867 document,
868 @iftex
869 @cite{The GNU Emacs Lisp Reference Manual}.
870 @end iftex
871 @ifnottex
872 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
873 Emacs Lisp Reference Manual}.
874 @end ifnottex
875 The reference manual has more detail than this introduction.  In the
876 reference manual, all the information about one topic is concentrated
877 in one place.  You should turn to it if you are like the programmer
878 quoted above.  And, of course, after you have read this
879 @cite{Introduction}, you will find the @cite{Reference Manual} useful
880 when you are writing your own programs.
882 @node Lisp History
883 @unnumberedsec Lisp History
884 @cindex Lisp history
886 Lisp was first developed in the late 1950s at the Massachusetts
887 Institute of Technology for research in artificial intelligence.  The
888 great power of the Lisp language makes it superior for other purposes as
889 well, such as writing editor commands and integrated environments.
891 @cindex Maclisp
892 @cindex Common Lisp
893 GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
894 in the 1960s.  It is somewhat inspired by Common Lisp, which became a
895 standard in the 1980s.  However, Emacs Lisp is much simpler than Common
896 Lisp.  (The standard Emacs distribution contains an optional extensions
897 file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
899 @node Note for Novices
900 @unnumberedsec A Note for Novices
902 If you don't know GNU Emacs, you can still read this document
903 profitably.  However, I recommend you learn Emacs, if only to learn to
904 move around your computer screen.  You can teach yourself how to use
905 Emacs with the built-in tutorial.  To use it, type @kbd{C-h t}.  (This
906 means you press and release the @key{CTRL} key and the @kbd{h} at the
907 same time, and then press and release @kbd{t}.)
909 Also, I often refer to one of Emacs's standard commands by listing the
910 keys which you press to invoke the command and then giving the name of
911 the command in parentheses, like this: @kbd{M-C-\}
912 (@code{indent-region}).  What this means is that the
913 @code{indent-region} command is customarily invoked by typing
914 @kbd{M-C-\}.  (You can, if you wish, change the keys that are typed to
915 invoke the command; this is called @dfn{rebinding}.  @xref{Keymaps, ,
916 Keymaps}.)  The abbreviation @kbd{M-C-\} means that you type your
917 @key{META} key, @key{CTRL} key and @key{\} key all at the same time.
918 (On many modern keyboards the @key{META} key is labeled
919 @key{ALT}.)
920 Sometimes a combination like this is called a keychord, since it is
921 similar to the way you play a chord on a piano.  If your keyboard does
922 not have a @key{META} key, the @key{ESC} key prefix is used in place
923 of it.  In this case, @kbd{M-C-\} means that you press and release your
924 @key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
925 the same time.  But usually @kbd{M-C-\} means press the @key{CTRL} key
926 along with the key that is labeled @key{ALT} and, at the same time,
927 press the @key{\} key.
929 In addition to typing a lone keychord, you can prefix what you type
930 with @kbd{C-u}, which is called the @dfn{universal argument}.  The
931 @kbd{C-u} keychord passes an argument to the subsequent command.
932 Thus, to indent a region of plain text by 6 spaces, mark the region,
933 and then type @w{@kbd{C-u 6 M-C-\}}.  (If you do not specify a number,
934 Emacs either passes the number 4 to the command or otherwise runs the
935 command differently than it would otherwise.)  @xref{Arguments, ,
936 Numeric Arguments, emacs, The GNU Emacs Manual}.
938 If you are reading this in Info using GNU Emacs, you can read through
939 this whole document just by pressing the space bar, @key{SPC}.
940 (To learn about Info, type @kbd{C-h i} and then select Info.)
942 A note on terminology:  when I use the word Lisp alone, I often am
943 referring to the various dialects of Lisp in general, but when I speak
944 of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
946 @node Thank You
947 @unnumberedsec Thank You
949 My thanks to all who helped me with this book.  My especial thanks to
950 @r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
951 McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.
952 Stallman}, and @w{Melissa Weisshaus}.  My thanks also go to both
953 @w{Philip Johnson} and @w{David Stampe} for their patient
954 encouragement.  My mistakes are my own.
956 @flushright
957 Robert J. Chassell
958 @ifnothtml
959 @email{bob@@gnu.org}
960 @end ifnothtml
961 @ifhtml
962 bob@@gnu.org
963 @end ifhtml
964 @end flushright
966 @c ================ Beginning of main text ================
968 @c Start main text on right-hand (verso) page
970 @tex
971 \par\vfill\supereject
972 \headings off
973 \ifodd\pageno
974     \par\vfill\supereject
975 \else
976     \par\vfill\supereject
977     \page\hbox{}\page
978     \par\vfill\supereject
980 @end tex
982 @c Note: this resetting of the page number back to 1 causes TeX to gripe
983 @c about already having seen page numbers 1-4 before (in the preface):
984 @c   pdfTeX warning (ext4): destination with the same identifier (name{1})
985 @c   has been already used, duplicate ignored
986 @c I guess that is harmless (what happens if a later part of the text
987 @c makes a link to something in the first 4 pages though?).
988 @c E.g., note that the Emacs manual has a preface, but does not bother
989 @c resetting the page numbers back to 1 after that.
990 @iftex
991 @headings off
992 @evenheading @thispage @| @| @thischapter
993 @oddheading @thissection @| @| @thispage
994 @global@pageno = 1
995 @end iftex
997 @node List Processing
998 @chapter List Processing
1000 To the untutored eye, Lisp is a strange programming language.  In Lisp
1001 code there are parentheses everywhere.  Some people even claim that
1002 the name stands for ``Lots of Isolated Silly Parentheses''.  But the
1003 claim is unwarranted.  Lisp stands for LISt Processing, and the
1004 programming language handles @emph{lists} (and lists of lists) by
1005 putting them between parentheses.  The parentheses mark the boundaries
1006 of the list.  Sometimes a list is preceded by an apostrophe @samp{'},
1007 called a @dfn{single-quote} in Lisp.@footnote{A single-quote is an
1008 abbreviation for the special form @code{quote}; you need not think
1009 about special forms now.  @xref{Complications}.}  Lists are the basis
1010 of Lisp.
1012 @menu
1013 * Lisp Lists::                  What are lists?
1014 * Run a Program::               Any list in Lisp is a program ready to run.
1015 * Making Errors::               Generating an error message.
1016 * Names & Definitions::         Names of symbols and function definitions.
1017 * Lisp Interpreter::            What the Lisp interpreter does.
1018 * Evaluation::                  Running a program.
1019 * Variables::                   Returning a value from a variable.
1020 * Arguments::                   Passing information to a function.
1021 * set & setq::                  Setting the value of a variable.
1022 * Summary::                     The major points.
1023 * Error Message Exercises::
1024 @end menu
1026 @node Lisp Lists
1027 @section Lisp Lists
1028 @cindex Lisp Lists
1030 In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1031 This list is preceded by a single apostrophe.  It could just as well be
1032 written as follows, which looks more like the kind of list you are likely
1033 to be familiar with:
1035 @smallexample
1036 @group
1037 '(rose
1038   violet
1039   daisy
1040   buttercup)
1041 @end group
1042 @end smallexample
1044 @noindent
1045 The elements of this list are the names of the four different flowers,
1046 separated from each other by whitespace and surrounded by parentheses,
1047 like flowers in a field with a stone wall around them.
1048 @cindex Flowers in a field
1050 @menu
1051 * Numbers Lists::               List have numbers, other lists, in them.
1052 * Lisp Atoms::                  Elemental entities.
1053 * Whitespace in Lists::         Formatting lists to be readable.
1054 * Typing Lists::                How GNU Emacs helps you type lists.
1055 @end menu
1057 @ifnottex
1058 @node Numbers Lists
1059 @unnumberedsubsec Numbers, Lists inside of Lists
1060 @end ifnottex
1062 Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1063 This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1064 separated by whitespace.
1066 In Lisp, both data and programs are represented the same way; that is,
1067 they are both lists of words, numbers, or other lists, separated by
1068 whitespace and surrounded by parentheses.  (Since a program looks like
1069 data, one program may easily serve as data for another; this is a very
1070 powerful feature of Lisp.)  (Incidentally, these two parenthetical
1071 remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1072 @samp{.} as punctuation marks.)
1074 @need 1200
1075 Here is another list, this time with a list inside of it:
1077 @smallexample
1078 '(this list has (a list inside of it))
1079 @end smallexample
1081 The components of this list are the words @samp{this}, @samp{list},
1082 @samp{has}, and the list @samp{(a list inside of it)}.  The interior
1083 list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1084 @samp{of}, @samp{it}.
1086 @node Lisp Atoms
1087 @subsection Lisp Atoms
1088 @cindex Lisp Atoms
1090 In Lisp, what we have been calling words are called @dfn{atoms}.  This
1091 term comes from the historical meaning of the word atom, which means
1092 ``indivisible''.  As far as Lisp is concerned, the words we have been
1093 using in the lists cannot be divided into any smaller parts and still
1094 mean the same thing as part of a program; likewise with numbers and
1095 single character symbols like @samp{+}.  On the other hand, unlike an
1096 ancient atom, a list can be split into parts.  (@xref{car cdr & cons,
1097 , @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1099 In a list, atoms are separated from each other by whitespace.  They can be
1100 right next to a parenthesis.
1102 @cindex @samp{empty list} defined
1103 Technically speaking, a list in Lisp consists of parentheses surrounding
1104 atoms separated by whitespace or surrounding other lists or surrounding
1105 both atoms and other lists.  A list can have just one atom in it or
1106 have nothing in it at all.  A list with nothing in it looks like this:
1107 @code{()}, and is called the @dfn{empty list}.  Unlike anything else, an
1108 empty list is considered both an atom and a list at the same time.
1110 @cindex Symbolic expressions, introduced
1111 @cindex @samp{expression} defined
1112 @cindex @samp{form} defined
1113 The printed representation of both atoms and lists are called
1114 @dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1115 The word @dfn{expression} by itself can refer to either the printed
1116 representation, or to the atom or list as it is held internally in the
1117 computer.  Often, people use the term @dfn{expression}
1118 indiscriminately.  (Also, in many texts, the word @dfn{form} is used
1119 as a synonym for expression.)
1121 Incidentally, the atoms that make up our universe were named such when
1122 they were thought to be indivisible; but it has been found that physical
1123 atoms are not indivisible.  Parts can split off an atom or it can
1124 fission into two parts of roughly equal size.  Physical atoms were named
1125 prematurely, before their truer nature was found.  In Lisp, certain
1126 kinds of atom, such as an array, can be separated into parts; but the
1127 mechanism for doing this is different from the mechanism for splitting a
1128 list.  As far as list operations are concerned, the atoms of a list are
1129 unsplittable.
1131 As in English, the meanings of the component letters of a Lisp atom
1132 are different from the meaning the letters make as a word.  For
1133 example, the word for the South American sloth, the @samp{ai}, is
1134 completely different from the two words, @samp{a}, and @samp{i}.
1136 There are many kinds of atom in nature but only a few in Lisp: for
1137 example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1138 as @samp{+}, @samp{foo}, or @samp{forward-line}.  The words we have
1139 listed in the examples above are all symbols.  In everyday Lisp
1140 conversation, the word ``atom'' is not often used, because programmers
1141 usually try to be more specific about what kind of atom they are dealing
1142 with.  Lisp programming is mostly about symbols (and sometimes numbers)
1143 within lists.  (Incidentally, the preceding three word parenthetical
1144 remark is a proper list in Lisp, since it consists of atoms, which in
1145 this case are symbols, separated by whitespace and enclosed by
1146 parentheses, without any non-Lisp punctuation.)
1148 @need 1250
1149 Text between double quotation marks---even sentences or
1150 paragraphs---is also an atom.  Here is an example:
1151 @cindex Text between double quotation marks
1153 @smallexample
1154 '(this list includes "text between quotation marks.")
1155 @end smallexample
1157 @cindex @samp{string} defined
1158 @noindent
1159 In Lisp, all of the quoted text including the punctuation mark and the
1160 blank spaces is a single atom.  This kind of atom is called a
1161 @dfn{string} (for ``string of characters'') and is the sort of thing that
1162 is used for messages that a computer can print for a human to read.
1163 Strings are a different kind of atom than numbers or symbols and are
1164 used differently.
1166 @node Whitespace in Lists
1167 @subsection Whitespace in Lists
1168 @cindex Whitespace in lists
1170 @need 1200
1171 The amount of whitespace in a list does not matter.  From the point of view
1172 of the Lisp language,
1174 @smallexample
1175 @group
1176 '(this list
1177    looks like this)
1178 @end group
1179 @end smallexample
1181 @need 800
1182 @noindent
1183 is exactly the same as this:
1185 @smallexample
1186 '(this list looks like this)
1187 @end smallexample
1189 Both examples show what to Lisp is the same list, the list made up of
1190 the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1191 @samp{this} in that order.
1193 Extra whitespace and newlines are designed to make a list more readable
1194 by humans.  When Lisp reads the expression, it gets rid of all the extra
1195 whitespace (but it needs to have at least one space between atoms in
1196 order to tell them apart.)
1198 Odd as it seems, the examples we have seen cover almost all of what Lisp
1199 lists look like!  Every other list in Lisp looks more or less like one
1200 of these examples, except that the list may be longer and more complex.
1201 In brief, a list is between parentheses, a string is between quotation
1202 marks, a symbol looks like a word, and a number looks like a number.
1203 (For certain situations, square brackets, dots and a few other special
1204 characters may be used; however, we will go quite far without them.)
1206 @node Typing Lists
1207 @subsection GNU Emacs Helps You Type Lists
1208 @cindex Help typing lists
1209 @cindex Formatting help
1211 When you type a Lisp expression in GNU Emacs using either Lisp
1212 Interaction mode or Emacs Lisp mode, you have available to you several
1213 commands to format the Lisp expression so it is easy to read.  For
1214 example, pressing the @key{TAB} key automatically indents the line the
1215 cursor is on by the right amount.  A command to properly indent the
1216 code in a region is customarily bound to @kbd{M-C-\}.  Indentation is
1217 designed so that you can see which elements of a list belong to which
1218 list---elements of a sub-list are indented more than the elements of
1219 the enclosing list.
1221 In addition, when you type a closing parenthesis, Emacs momentarily
1222 jumps the cursor back to the matching opening parenthesis, so you can
1223 see which one it is.  This is very useful, since every list you type
1224 in Lisp must have its closing parenthesis match its opening
1225 parenthesis.  (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1226 Manual}, for more information about Emacs's modes.)
1228 @node Run a Program
1229 @section Run a Program
1230 @cindex Run a program
1231 @cindex Program, running one
1233 @cindex @samp{evaluate} defined
1234 A list in Lisp---any list---is a program ready to run.  If you run it
1235 (for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1236 of three things: do nothing except return to you the list itself; send
1237 you an error message; or, treat the first symbol in the list as a
1238 command to do something.  (Usually, of course, it is the last of these
1239 three things that you really want!)
1241 @c use code for the single apostrophe, not samp.
1242 @findex quote
1243 @cindex @code{'} for quoting
1244 @cindex quoting using apostrophe
1245 @cindex apostrophe for quoting
1246 The single apostrophe, @code{'}, that I put in front of some of the
1247 example lists in preceding sections is called a @dfn{quote}; when it
1248 precedes a list, it tells Lisp to do nothing with the list, other than
1249 take it as it is written.  But if there is no quote preceding a list,
1250 the first item of the list is special: it is a command for the computer
1251 to obey.  (In Lisp, these commands are called @emph{functions}.)  The list
1252 @code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1253 understands that the @code{+} is an instruction to do something with the
1254 rest of the list: add the numbers that follow.
1256 @need 1250
1257 If you are reading this inside of GNU Emacs in Info, here is how you can
1258 evaluate such a list:  place your cursor immediately after the right
1259 hand parenthesis of the following list and then type @kbd{C-x C-e}:
1261 @smallexample
1262 (+ 2 2)
1263 @end smallexample
1265 @c use code for the number four, not samp.
1266 @noindent
1267 You will see the number @code{4} appear in the echo area.  (What
1268 you have just done is evaluate the list.  The echo area
1269 is the line at the bottom of the screen that displays or echoes
1270 text.)  Now try the same thing with a quoted list:  place the cursor
1271 right after the following list and type @kbd{C-x C-e}:
1273 @smallexample
1274 '(this is a quoted list)
1275 @end smallexample
1277 @noindent
1278 You will see @code{(this is a quoted list)} appear in the echo area.
1280 @cindex Lisp interpreter, explained
1281 @cindex Interpreter, Lisp, explained
1282 In both cases, what you are doing is giving a command to the program
1283 inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1284 interpreter a command to evaluate the expression.  The name of the Lisp
1285 interpreter comes from the word for the task done by a human who comes
1286 up with the meaning of an expression---who interprets it.
1288 You can also evaluate an atom that is not part of a list---one that is
1289 not surrounded by parentheses; again, the Lisp interpreter translates
1290 from the humanly readable expression to the language of the computer.
1291 But before discussing this (@pxref{Variables}), we will discuss what the
1292 Lisp interpreter does when you make an error.
1294 @node Making Errors
1295 @section Generate an Error Message
1296 @cindex Generate an error message
1297 @cindex Error message generation
1299 Partly so you won't worry if you do it accidentally, we will now give
1300 a command to the Lisp interpreter that generates an error message.
1301 This is a harmless activity; and indeed, we will often try to generate
1302 error messages intentionally.  Once you understand the jargon, error
1303 messages can be informative.  Instead of being called ``error''
1304 messages, they should be called ``help'' messages.  They are like
1305 signposts to a traveler in a strange country; deciphering them can be
1306 hard, but once understood, they can point the way.
1308 The error message is generated by a built-in GNU Emacs debugger.  We
1309 will enter the debugger.  You get out of the debugger by typing @code{q}.
1311 What we will do is evaluate a list that is not quoted and does not
1312 have a meaningful command as its first element.  Here is a list almost
1313 exactly the same as the one we just used, but without the single-quote
1314 in front of it.  Position the cursor right after it and type @kbd{C-x
1315 C-e}:
1317 @smallexample
1318 (this is an unquoted list)
1319 @end smallexample
1321 @ignore
1322 @noindent
1323 What you see depends on which version of Emacs you are running.  GNU
1324 Emacs version 22 provides more information than version 20 and before.
1325 First, the more recent result of generating an error; then the
1326 earlier, version 20 result.
1328 @need 1250
1329 @noindent
1330 In GNU Emacs version 22, a @file{*Backtrace*} window will open up and
1331 you will see the following in it:
1332 @end ignore
1334 A @file{*Backtrace*} window will open up and you should see the
1335 following in it:
1337 @smallexample
1338 @group
1339 ---------- Buffer: *Backtrace* ----------
1340 Debugger entered--Lisp error: (void-function this)
1341   (this is an unquoted list)
1342   eval((this is an unquoted list))
1343   eval-last-sexp-1(nil)
1344   eval-last-sexp(nil)
1345   call-interactively(eval-last-sexp)
1346 ---------- Buffer: *Backtrace* ----------
1347 @end group
1348 @end smallexample
1350 @need 1200
1351 @noindent
1352 Your cursor will be in this window (you may have to wait a few seconds
1353 before it becomes visible).  To quit the debugger and make the
1354 debugger window go away, type:
1356 @smallexample
1358 @end smallexample
1360 @noindent
1361 Please type @kbd{q} right now, so you become confident that you can
1362 get out of the debugger.  Then, type @kbd{C-x C-e} again to re-enter
1365 @cindex @samp{function} defined
1366 Based on what we already know, we can almost read this error message.
1368 You read the @file{*Backtrace*} buffer from the bottom up; it tells
1369 you what Emacs did.  When you typed @kbd{C-x C-e}, you made an
1370 interactive call to the command @code{eval-last-sexp}.  @code{eval} is
1371 an abbreviation for ``evaluate'' and @code{sexp} is an abbreviation for
1372 ``symbolic expression''.  The command means ``evaluate last symbolic
1373 expression'', which is the expression just before your cursor.
1375 Each line above tells you what the Lisp interpreter evaluated next.
1376 The most recent action is at the top.  The buffer is called the
1377 @file{*Backtrace*} buffer because it enables you to track Emacs
1378 backwards.
1380 @need 800
1381 At the top of the @file{*Backtrace*} buffer, you see the line:
1383 @smallexample
1384 Debugger entered--Lisp error: (void-function this)
1385 @end smallexample
1387 @noindent
1388 The Lisp interpreter tried to evaluate the first atom of the list, the
1389 word @samp{this}.  It is this action that generated the error message
1390 @samp{void-function this}.
1392 The message contains the words @samp{void-function} and @samp{this}.
1394 @cindex @samp{function} defined
1395 The word @samp{function} was mentioned once before.  It is a very
1396 important word.  For our purposes, we can define it by saying that a
1397 @dfn{function} is a set of instructions to the computer that tell the
1398 computer to do something.
1400 Now we can begin to understand the error message: @samp{void-function
1401 this}.  The function (that is, the word @samp{this}) does not have a
1402 definition of any set of instructions for the computer to carry out.
1404 The slightly odd word, @samp{void-function}, is designed to cover the
1405 way Emacs Lisp is implemented, which is that when a symbol does not
1406 have a function definition attached to it, the place that should
1407 contain the instructions is void.
1409 On the other hand, since we were able to add 2 plus 2 successfully, by
1410 evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1411 have a set of instructions for the computer to obey and those
1412 instructions must be to add the numbers that follow the @code{+}.
1414 It is possible to prevent Emacs entering the debugger in cases like
1415 this.  We do not explain how to do that here, but we will mention what
1416 the result looks like, because you may encounter a similar situation
1417 if there is a bug in some Emacs code that you are using.  In such
1418 cases, you will see only one line of error message; it will appear in
1419 the echo area and look like this:
1421 @smallexample
1422 Symbol's function definition is void:@: this
1423 @end smallexample
1425 @noindent
1426 @ignore
1427 (Also, your terminal may beep at you---some do, some don't; and others
1428 blink.  This is just a device to get your attention.)
1429 @end ignore
1430 The message goes away as soon as you type a key, even just to
1431 move the cursor.
1433 We know the meaning of the word @samp{Symbol}.  It refers to the first
1434 atom of the list, the word @samp{this}.  The word @samp{function}
1435 refers to the instructions that tell the computer what to do.
1436 (Technically, the symbol tells the computer where to find the
1437 instructions, but this is a complication we can ignore for the
1438 moment.)
1440 The error message can be understood: @samp{Symbol's function
1441 definition is void:@: this}.  The symbol (that is, the word
1442 @samp{this}) lacks instructions for the computer to carry out.
1444 @node Names & Definitions
1445 @section Symbol Names and Function Definitions
1446 @cindex Symbol names
1448 We can articulate another characteristic of Lisp based on what we have
1449 discussed so far---an important characteristic: a symbol, like
1450 @code{+}, is not itself the set of instructions for the computer to
1451 carry out.  Instead, the symbol is used, perhaps temporarily, as a way
1452 of locating the definition or set of instructions.  What we see is the
1453 name through which the instructions can be found.  Names of people
1454 work the same way.  I can be referred to as @samp{Bob}; however, I am
1455 not the letters @samp{B}, @samp{o}, @samp{b} but am, or was, the
1456 consciousness consistently associated with a particular life-form.
1457 The name is not me, but it can be used to refer to me.
1459 In Lisp, one set of instructions can be attached to several names.
1460 For example, the computer instructions for adding numbers can be
1461 linked to the symbol @code{plus} as well as to the symbol @code{+}
1462 (and are in some dialects of Lisp).  Among humans, I can be referred
1463 to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1465 On the other hand, a symbol can have only one function definition
1466 attached to it at a time.  Otherwise, the computer would be confused as
1467 to which definition to use.  If this were the case among people, only
1468 one person in the world could be named @samp{Bob}.  However, the function
1469 definition to which the name refers can be changed readily.
1470 (@xref{Install, , Install a Function Definition}.)
1472 Since Emacs Lisp is large, it is customary to name symbols in a way
1473 that identifies the part of Emacs to which the function belongs.
1474 Thus, all the names for functions that deal with Texinfo start with
1475 @samp{texinfo-} and those for functions that deal with reading mail
1476 start with @samp{rmail-}.
1478 @node Lisp Interpreter
1479 @section The Lisp Interpreter
1480 @cindex Lisp interpreter, what it does
1481 @cindex Interpreter, what it does
1483 Based on what we have seen, we can now start to figure out what the
1484 Lisp interpreter does when we command it to evaluate a list.
1485 First, it looks to see whether there is a quote before the list; if
1486 there is, the interpreter just gives us the list.  On the other
1487 hand, if there is no quote, the interpreter looks at the first element
1488 in the list and sees whether it has a function definition.  If it does,
1489 the interpreter carries out the instructions in the function definition.
1490 Otherwise, the interpreter prints an error message.
1492 This is how Lisp works.  Simple.  There are added complications which we
1493 will get to in a minute, but these are the fundamentals.  Of course, to
1494 write Lisp programs, you need to know how to write function definitions
1495 and attach them to names, and how to do this without confusing either
1496 yourself or the computer.
1498 @menu
1499 * Complications::               Variables, Special forms, Lists within.
1500 * Byte Compiling::              Specially processing code for speed.
1501 @end menu
1503 @ifnottex
1504 @node Complications
1505 @unnumberedsubsec Complications
1506 @end ifnottex
1508 Now, for the first complication.  In addition to lists, the Lisp
1509 interpreter can evaluate a symbol that is not quoted and does not have
1510 parentheses around it.  The Lisp interpreter will attempt to determine
1511 the symbol's value as a @dfn{variable}.  This situation is described
1512 in the section on variables.  (@xref{Variables}.)
1514 @cindex Special form
1515 The second complication occurs because some functions are unusual and
1516 do not work in the usual manner.  Those that don't are called
1517 @dfn{special forms}.  They are used for special jobs, like defining a
1518 function, and there are not many of them.  In the next few chapters,
1519 you will be introduced to several of the more important special forms.
1521 As well as special forms, there are also @dfn{macros}.  A macro
1522 is a construct defined in Lisp, which differs from a function in that it
1523 translates a Lisp expression into another expression that is to be
1524 evaluated in place of the original expression.  (@xref{Lisp macro}.)
1526 For the purposes of this introduction, you do not need to worry too much
1527 about whether something is a special form, macro, or ordinary function.
1528 For example, @code{if} is a special form (@pxref{if}), but @code{when}
1529 is a macro (@pxref{Lisp macro}).  In earlier versions of Emacs,
1530 @code{defun} was a special form, but now it is a macro (@pxref{defun}).
1531 It still behaves in the same way.
1533 The final complication is this: if the function that the
1534 Lisp interpreter is looking at is not a special form, and if it is part
1535 of a list, the Lisp interpreter looks to see whether the list has a list
1536 inside of it.  If there is an inner list, the Lisp interpreter first
1537 figures out what it should do with the inside list, and then it works on
1538 the outside list.  If there is yet another list embedded inside the
1539 inner list, it works on that one first, and so on.  It always works on
1540 the innermost list first.  The interpreter works on the innermost list
1541 first, to evaluate the result of that list.  The result may be
1542 used by the enclosing expression.
1544 Otherwise, the interpreter works left to right, from one expression to
1545 the next.
1547 @node Byte Compiling
1548 @subsection Byte Compiling
1549 @cindex Byte compiling
1551 One other aspect of interpreting: the Lisp interpreter is able to
1552 interpret two kinds of entity: humanly readable code, on which we will
1553 focus exclusively, and specially processed code, called @dfn{byte
1554 compiled} code, which is not humanly readable.  Byte compiled code
1555 runs faster than humanly readable code.
1557 You can transform humanly readable code into byte compiled code by
1558 running one of the compile commands such as @code{byte-compile-file}.
1559 Byte compiled code is usually stored in a file that ends with a
1560 @file{.elc} extension rather than a @file{.el} extension.  You will
1561 see both kinds of file in the @file{emacs/lisp} directory; the files
1562 to read are those with @file{.el} extensions.
1564 As a practical matter, for most things you might do to customize or
1565 extend Emacs, you do not need to byte compile; and I will not discuss
1566 the topic here.  @xref{Byte Compilation, , Byte Compilation, elisp,
1567 The GNU Emacs Lisp Reference Manual}, for a full description of byte
1568 compilation.
1570 @node Evaluation
1571 @section Evaluation
1572 @cindex Evaluation
1574 When the Lisp interpreter works on an expression, the term for the
1575 activity is called @dfn{evaluation}.  We say that the interpreter
1576 ``evaluates the expression''.  I've used this term several times before.
1577 The word comes from its use in everyday language, ``to ascertain the
1578 value or amount of; to appraise'', according to @cite{Webster's New
1579 Collegiate Dictionary}.
1581 @menu
1582 * How the Interpreter Acts::    Returns and Side Effects...
1583 * Evaluating Inner Lists::      Lists within lists...
1584 @end menu
1586 @ifnottex
1587 @node How the Interpreter Acts
1588 @unnumberedsubsec How the Lisp Interpreter Acts
1589 @end ifnottex
1591 @cindex @samp{returned value} explained
1592 After evaluating an expression, the Lisp interpreter will most likely
1593 @dfn{return} the value that the computer produces by carrying out the
1594 instructions it found in the function definition, or perhaps it will
1595 give up on that function and produce an error message.  (The interpreter
1596 may also find itself tossed, so to speak, to a different function or it
1597 may attempt to repeat continually what it is doing for ever and ever in
1598 an infinite loop.  These actions are less common; and
1599 we can ignore them.)  Most frequently, the interpreter returns a value.
1601 @cindex @samp{side effect} defined
1602 At the same time the interpreter returns a value, it may do something
1603 else as well, such as move a cursor or copy a file; this other kind of
1604 action is called a @dfn{side effect}.  Actions that we humans think are
1605 important, such as printing results, are often side effects to the
1606 Lisp interpreter.  It is fairly easy to learn to use side effects.
1608 In summary, evaluating a symbolic expression most commonly causes the
1609 Lisp interpreter to return a value and perhaps carry out a side effect;
1610 or else produce an error.
1612 @node Evaluating Inner Lists
1613 @subsection Evaluating Inner Lists
1614 @cindex Inner list evaluation
1615 @cindex Evaluating inner lists
1617 If evaluation applies to a list that is inside another list, the outer
1618 list may use the value returned by the first evaluation as information
1619 when the outer list is evaluated.  This explains why inner expressions
1620 are evaluated first: the values they return are used by the outer
1621 expressions.
1623 @need 1250
1624 We can investigate this process by evaluating another addition example.
1625 Place your cursor after the following expression and type @kbd{C-x C-e}:
1627 @smallexample
1628 (+ 2 (+ 3 3))
1629 @end smallexample
1631 @noindent
1632 The number 8 will appear in the echo area.
1634 What happens is that the Lisp interpreter first evaluates the inner
1635 expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1636 evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1637 returns the value 8.  Since there are no more enclosing expressions to
1638 evaluate, the interpreter prints that value in the echo area.
1640 Now it is easy to understand the name of the command invoked by the
1641 keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}.  The
1642 letters @code{sexp} are an abbreviation for ``symbolic expression'', and
1643 @code{eval} is an abbreviation for ``evaluate''.  The command
1644 evaluates the last symbolic expression.
1646 As an experiment, you can try evaluating the expression by putting the
1647 cursor at the beginning of the next line immediately following the
1648 expression, or inside the expression.
1650 @need 800
1651 Here is another copy of the expression:
1653 @smallexample
1654 (+ 2 (+ 3 3))
1655 @end smallexample
1657 @noindent
1658 If you place the cursor at the beginning of the blank line that
1659 immediately follows the expression and type @kbd{C-x C-e}, you will
1660 still get the value 8 printed in the echo area.  Now try putting the
1661 cursor inside the expression.  If you put it right after the next to
1662 last parenthesis (so it appears to sit on top of the last parenthesis),
1663 you will get a 6 printed in the echo area!  This is because the command
1664 evaluates the expression @code{(+ 3 3)}.
1666 Now put the cursor immediately after a number.  Type @kbd{C-x C-e} and
1667 you will get the number itself.  In Lisp, if you evaluate a number, you
1668 get the number itself---this is how numbers differ from symbols.  If you
1669 evaluate a list starting with a symbol like @code{+}, you will get a
1670 value returned that is the result of the computer carrying out the
1671 instructions in the function definition attached to that name.  If a
1672 symbol by itself is evaluated, something different happens, as we will
1673 see in the next section.
1675 @node Variables
1676 @section Variables
1677 @cindex Variables
1679 In Emacs Lisp, a symbol can have a value attached to it just as it can
1680 have a function definition attached to it.  The two are different.
1681 The function definition is a set of instructions that a computer will
1682 obey.  A value, on the other hand, is something, such as number or a
1683 name, that can vary (which is why such a symbol is called a variable).
1684 The value of a symbol can be any expression in Lisp, such as a symbol,
1685 number, list, or string.  A symbol that has a value is often called a
1686 @dfn{variable}.
1688 A symbol can have both a function definition and a value attached to
1689 it at the same time.  Or it can have just one or the other.
1690 The two are separate.  This is somewhat similar
1691 to the way the name Cambridge can refer to the city in Massachusetts
1692 and have some information attached to the name as well, such as
1693 ``great programming center''.
1695 @ignore
1696 (Incidentally, in Emacs Lisp, a symbol can have two
1697 other things attached to it, too: a property list and a documentation
1698 string; these are discussed later.)
1699 @end ignore
1701 Another way to think about this is to imagine a symbol as being a chest
1702 of drawers.  The function definition is put in one drawer, the value in
1703 another, and so on.  What is put in the drawer holding the value can be
1704 changed without affecting the contents of the drawer holding the
1705 function definition, and vice versa.
1707 @menu
1708 * fill-column Example::
1709 * Void Function::               The error message for a symbol
1710                                   without a function.
1711 * Void Variable::               The error message for a symbol without a value.
1712 @end menu
1714 @ifnottex
1715 @node fill-column Example
1716 @unnumberedsubsec @code{fill-column}, an Example Variable
1717 @end ifnottex
1719 @findex fill-column, @r{an example variable}
1720 @cindex Example variable, @code{fill-column}
1721 @cindex Variable, example of, @code{fill-column}
1722 The variable @code{fill-column} illustrates a symbol with a value
1723 attached to it: in every GNU Emacs buffer, this symbol is set to some
1724 value, usually 72 or 70, but sometimes to some other value.  To find the
1725 value of this symbol, evaluate it by itself.  If you are reading this in
1726 Info inside of GNU Emacs, you can do this by putting the cursor after
1727 the symbol and typing @kbd{C-x C-e}:
1729 @smallexample
1730 fill-column
1731 @end smallexample
1733 @noindent
1734 After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1735 area.  This is the value for which @code{fill-column} is set for me as I
1736 write this.  It may be different for you in your Info buffer.  Notice
1737 that the value returned as a variable is printed in exactly the same way
1738 as the value returned by a function carrying out its instructions.  From
1739 the point of view of the Lisp interpreter, a value returned is a value
1740 returned.  What kind of expression it came from ceases to matter once
1741 the value is known.
1743 A symbol can have any value attached to it or, to use the jargon, we can
1744 @dfn{bind} the variable to a value: to a number, such as 72; to a
1745 string, @code{"such as this"}; to a list, such as @code{(spruce pine
1746 oak)}; we can even bind a variable to a function definition.
1748 A symbol can be bound to a value in several ways.  @xref{set & setq, ,
1749 Setting the Value of a Variable}, for information about one way to do
1750 this.
1752 @node Void Function
1753 @subsection Error Message for a Symbol Without a Function
1754 @cindex Symbol without function error
1755 @cindex Error for symbol without function
1757 When we evaluated @code{fill-column} to find its value as a variable,
1758 we did not place parentheses around the word.  This is because we did
1759 not intend to use it as a function name.
1761 If @code{fill-column} were the first or only element of a list, the
1762 Lisp interpreter would attempt to find the function definition
1763 attached to it.  But @code{fill-column} has no function definition.
1764 Try evaluating this:
1766 @smallexample
1767 (fill-column)
1768 @end smallexample
1770 @need 1250
1771 @noindent
1772 You will create a @file{*Backtrace*} buffer that says:
1774 @smallexample
1775 @group
1776 ---------- Buffer: *Backtrace* ----------
1777 Debugger entered--Lisp error: (void-function fill-column)
1778   (fill-column)
1779   eval((fill-column))
1780   eval-last-sexp-1(nil)
1781   eval-last-sexp(nil)
1782   call-interactively(eval-last-sexp)
1783 ---------- Buffer: *Backtrace* ----------
1784 @end group
1785 @end smallexample
1787 @noindent
1788 (Remember, to quit the debugger and make the debugger window go away,
1789 type @kbd{q} in the @file{*Backtrace*} buffer.)
1791 @ignore
1792 @need 800
1793 In GNU Emacs 20 and before, you will produce an error message that says:
1795 @smallexample
1796 Symbol's function definition is void:@: fill-column
1797 @end smallexample
1799 @noindent
1800 (The message will go away as soon as you move the cursor or type
1801 another key.)
1802 @end ignore
1804 @node Void Variable
1805 @subsection Error Message for a Symbol Without a Value
1806 @cindex Symbol without value error
1807 @cindex Error for symbol without value
1809 If you attempt to evaluate a symbol that does not have a value bound to
1810 it, you will receive an error message.  You can see this by
1811 experimenting with our 2 plus 2 addition.  In the following expression,
1812 put your cursor right after the @code{+}, before the first number 2,
1813 type @kbd{C-x C-e}:
1815 @smallexample
1816 (+ 2 2)
1817 @end smallexample
1819 @need 1500
1820 @noindent
1821 In GNU Emacs 22, you will create a @file{*Backtrace*} buffer that
1822 says:
1824 @smallexample
1825 @group
1826 ---------- Buffer: *Backtrace* ----------
1827 Debugger entered--Lisp error: (void-variable +)
1828   eval(+)
1829   eval-last-sexp-1(nil)
1830   eval-last-sexp(nil)
1831   call-interactively(eval-last-sexp)
1832 ---------- Buffer: *Backtrace* ----------
1833 @end group
1834 @end smallexample
1836 @noindent
1837 (Again, you can quit the debugger by
1838 typing @kbd{q} in the @file{*Backtrace*} buffer.)
1840 This backtrace is different from the very first error message we saw,
1841 which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1842 In this case, the function does not have a value as a variable; while
1843 in the other error message, the function (the word @samp{this}) did not
1844 have a definition.
1846 In this experiment with the @code{+}, what we did was cause the Lisp
1847 interpreter to evaluate the @code{+} and look for the value of the
1848 variable instead of the function definition.  We did this by placing the
1849 cursor right after the symbol rather than after the parenthesis of the
1850 enclosing list as we did before.  As a consequence, the Lisp interpreter
1851 evaluated the preceding s-expression, which in this case was
1852 @code{+} by itself.
1854 Since @code{+} does not have a value bound to it, just the function
1855 definition, the error message reported that the symbol's value as a
1856 variable was void.
1858 @ignore
1859 @need 800
1860 In GNU Emacs version 20 and before, your error message will say:
1862 @example
1863 Symbol's value as variable is void:@: +
1864 @end example
1866 @noindent
1867 The meaning is the same as in GNU Emacs 22.
1868 @end ignore
1870 @node Arguments
1871 @section Arguments
1872 @cindex Arguments
1873 @cindex Passing information to functions
1875 To see how information is passed to functions, let's look again at
1876 our old standby, the addition of two plus two.  In Lisp, this is written
1877 as follows:
1879 @smallexample
1880 (+ 2 2)
1881 @end smallexample
1883 If you evaluate this expression, the number 4 will appear in your echo
1884 area.  What the Lisp interpreter does is add the numbers that follow
1885 the @code{+}.
1887 @cindex @samp{argument} defined
1888 The numbers added by @code{+} are called the @dfn{arguments} of the
1889 function @code{+}.  These numbers are the information that is given to
1890 or @dfn{passed} to the function.
1892 The word ``argument'' comes from the way it is used in mathematics and
1893 does not refer to a disputation between two people; instead it refers to
1894 the information presented to the function, in this case, to the
1895 @code{+}.  In Lisp, the arguments to a function are the atoms or lists
1896 that follow the function.  The values returned by the evaluation of
1897 these atoms or lists are passed to the function.  Different functions
1898 require different numbers of arguments; some functions require none at
1899 all.@footnote{It is curious to track the path by which the word ``argument''
1900 came to have two different meanings, one in mathematics and the other in
1901 everyday English.  According to the @cite{Oxford English Dictionary},
1902 the word derives from the Latin for @samp{to make clear, prove}; thus it
1903 came to mean, by one thread of derivation, ``the evidence offered as
1904 proof'', which is to say, ``the information offered'', which led to its
1905 meaning in Lisp.  But in the other thread of derivation, it came to mean
1906 ``to assert in a manner against which others may make counter
1907 assertions'', which led to the meaning of the word as a disputation.
1908 (Note here that the English word has two different definitions attached
1909 to it at the same time.  By contrast, in Emacs Lisp, a symbol cannot
1910 have two different function definitions at the same time.)}
1912 @menu
1913 * Data types::                  Types of data passed to a function.
1914 * Args as Variable or List::    An argument can be the value
1915                                   of a variable or list.
1916 * Variable Number of Arguments::  Some functions may take a
1917                                   variable number of arguments.
1918 * Wrong Type of Argument::      Passing an argument of the wrong type
1919                                   to a function.
1920 * message::                     A useful function for sending messages.
1921 @end menu
1923 @node Data types
1924 @subsection Arguments' Data Types
1925 @cindex Data types
1926 @cindex Types of data
1927 @cindex Arguments' data types
1929 The type of data that should be passed to a function depends on what
1930 kind of information it uses.  The arguments to a function such as
1931 @code{+} must have values that are numbers, since @code{+} adds numbers.
1932 Other functions use different kinds of data for their arguments.
1934 @need 1250
1935 @findex concat
1936 For example, the @code{concat} function links together or unites two or
1937 more strings of text to produce a string.  The arguments are strings.
1938 Concatenating the two character strings @code{abc}, @code{def} produces
1939 the single string @code{abcdef}.  This can be seen by evaluating the
1940 following:
1942 @smallexample
1943 (concat "abc" "def")
1944 @end smallexample
1946 @noindent
1947 The value produced by evaluating this expression is @code{"abcdef"}.
1949 @cindex substring
1950 A function such as @code{substring} uses both a string and numbers as
1951 arguments.  The function returns a part of the string, a @dfn{substring} of
1952 the first argument.  This function takes three arguments.  Its first
1953 argument is the string of characters, the second and third arguments
1954 are numbers that indicate the beginning (inclusive) and end
1955 (exclusive) of the substring.  The numbers are a count of the number
1956 of characters (including spaces and punctuation) from the beginning of
1957 the string. Note that the characters in a string are numbered from
1958 zero, not one.
1960 @need 800
1961 For example, if you evaluate the following:
1963 @smallexample
1964 (substring "The quick brown fox jumped." 16 19)
1965 @end smallexample
1967 @noindent
1968 you will see @code{"fox"} appear in the echo area.  The arguments are the
1969 string and the two numbers.
1971 Note that the string passed to @code{substring} is a single atom even
1972 though it is made up of several words separated by spaces.  Lisp counts
1973 everything between the two quotation marks as part of the string,
1974 including the spaces.  You can think of the @code{substring} function as
1975 a kind of atom smasher since it takes an otherwise indivisible atom
1976 and extracts a part.  However, @code{substring} is only able to extract
1977 a substring from an argument that is a string, not from another type of
1978 atom such as a number or symbol.
1980 @node Args as Variable or List
1981 @subsection An Argument as the Value of a Variable or List
1983 An argument can be a symbol that returns a value when it is evaluated.
1984 For example, when the symbol @code{fill-column} by itself is evaluated,
1985 it returns a number.  This number can be used in an addition.
1987 @need 1250
1988 Position the cursor after the following expression and type @kbd{C-x
1989 C-e}:
1991 @smallexample
1992 (+ 2 fill-column)
1993 @end smallexample
1995 @noindent
1996 The value will be a number two more than what you get by evaluating
1997 @code{fill-column} alone.  For me, this is 74, because my value of
1998 @code{fill-column} is 72.
2000 As we have just seen, an argument can be a symbol that returns a value
2001 when evaluated.  In addition, an argument can be a list that returns a
2002 value when it is evaluated.  For example, in the following expression,
2003 the arguments to the function @code{concat} are the strings
2004 @w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2005 @code{(number-to-string (+ 2 fill-column))}.
2007 @c For GNU Emacs 22, need number-to-string
2008 @smallexample
2009 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2010 @end smallexample
2012 @noindent
2013 If you evaluate this expression---and if, as with my Emacs,
2014 @code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2015 appear in the echo area.  (Note that you must put spaces after the
2016 word @samp{The} and before the word @samp{red} so they will appear in
2017 the final string.  The function @code{number-to-string} converts the
2018 integer that the addition function returns to a string.
2019 @code{number-to-string} is also known as @code{int-to-string}.)
2021 @node Variable Number of Arguments
2022 @subsection Variable Number of Arguments
2023 @cindex Variable number of arguments
2024 @cindex Arguments, variable number of
2026 Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2027 number of arguments.  (The @code{*} is the symbol for multiplication.)
2028 This can be seen by evaluating each of the following expressions in
2029 the usual way.  What you will see in the echo area is printed in this
2030 text after @samp{@result{}}, which you may read as ``evaluates to''.
2032 @need 1250
2033 In the first set, the functions have no arguments:
2035 @smallexample
2036 @group
2037 (+)       @result{} 0
2039 (*)       @result{} 1
2040 @end group
2041 @end smallexample
2043 @need 1250
2044 In this set, the functions have one argument each:
2046 @smallexample
2047 @group
2048 (+ 3)     @result{} 3
2050 (* 3)     @result{} 3
2051 @end group
2052 @end smallexample
2054 @need 1250
2055 In this set, the functions have three arguments each:
2057 @smallexample
2058 @group
2059 (+ 3 4 5) @result{} 12
2061 (* 3 4 5) @result{} 60
2062 @end group
2063 @end smallexample
2065 @node Wrong Type of Argument
2066 @subsection Using the Wrong Type Object as an Argument
2067 @cindex Wrong type of argument
2068 @cindex Argument, wrong type of
2070 When a function is passed an argument of the wrong type, the Lisp
2071 interpreter produces an error message.  For example, the @code{+}
2072 function expects the values of its arguments to be numbers.  As an
2073 experiment we can pass it the quoted symbol @code{hello} instead of a
2074 number.  Position the cursor after the following expression and type
2075 @kbd{C-x C-e}:
2077 @smallexample
2078 (+ 2 'hello)
2079 @end smallexample
2081 @noindent
2082 When you do this you will generate an error message.  What has happened
2083 is that @code{+} has tried to add the 2 to the value returned by
2084 @code{'hello}, but the value returned by @code{'hello} is the symbol
2085 @code{hello}, not a number.  Only numbers can be added.  So @code{+}
2086 could not carry out its addition.
2088 @need 1250
2089 You will create and enter a @file{*Backtrace*} buffer that says:
2091 @noindent
2092 @smallexample
2093 @group
2094 ---------- Buffer: *Backtrace* ----------
2095 Debugger entered--Lisp error:
2096          (wrong-type-argument number-or-marker-p hello)
2097   +(2 hello)
2098   eval((+ 2 (quote hello)))
2099   eval-last-sexp-1(nil)
2100   eval-last-sexp(nil)
2101   call-interactively(eval-last-sexp)
2102 ---------- Buffer: *Backtrace* ----------
2103 @end group
2104 @end smallexample
2106 @need 1250
2107 As usual, the error message tries to be helpful and makes sense after you
2108 learn how to read it.@footnote{@code{(quote hello)} is an expansion of
2109 the abbreviation @code{'hello}.}
2111 The first part of the error message is straightforward; it says
2112 @samp{wrong type argument}.  Next comes the mysterious jargon word
2113 @w{@samp{number-or-marker-p}}.  This word is trying to tell you what
2114 kind of argument the @code{+} expected.
2116 The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2117 trying to determine whether the information presented it (the value of
2118 the argument) is a number or a marker (a special object representing a
2119 buffer position).  What it does is test to see whether the @code{+} is
2120 being given numbers to add.  It also tests to see whether the
2121 argument is something called a marker, which is a specific feature of
2122 Emacs Lisp.  (In Emacs, locations in a buffer are recorded as markers.
2123 When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2124 its position is kept as a marker.  The mark can be considered a
2125 number---the number of characters the location is from the beginning
2126 of the buffer.)  In Emacs Lisp, @code{+} can be used to add the
2127 numeric value of marker positions as numbers.
2129 The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2130 practice started in the early days of Lisp programming.  The @samp{p}
2131 stands for ``predicate''.  In the jargon used by the early Lisp
2132 researchers, a predicate refers to a function to determine whether some
2133 property is true or false.  So the @samp{p} tells us that
2134 @code{number-or-marker-p} is the name of a function that determines
2135 whether it is true or false that the argument supplied is a number or
2136 a marker.  Other Lisp symbols that end in @samp{p} include @code{zerop},
2137 a function that tests whether its argument has the value of zero, and
2138 @code{listp}, a function that tests whether its argument is a list.
2140 Finally, the last part of the error message is the symbol @code{hello}.
2141 This is the value of the argument that was passed to @code{+}.  If the
2142 addition had been passed the correct type of object, the value passed
2143 would have been a number, such as 37, rather than a symbol like
2144 @code{hello}.  But then you would not have got the error message.
2146 @ignore
2147 @need 1250
2148 In GNU Emacs version 20 and before, the echo area displays an error
2149 message that says:
2151 @smallexample
2152 Wrong type argument:@: number-or-marker-p, hello
2153 @end smallexample
2155 This says, in different words, the same as the top line of the
2156 @file{*Backtrace*} buffer.
2157 @end ignore
2159 @node message
2160 @subsection The @code{message} Function
2161 @findex message
2163 Like @code{+}, the @code{message} function takes a variable number of
2164 arguments.  It is used to send messages to the user and is so useful
2165 that we will describe it here.
2167 @need 1250
2168 A message is printed in the echo area.  For example, you can print a
2169 message in your echo area by evaluating the following list:
2171 @smallexample
2172 (message "This message appears in the echo area!")
2173 @end smallexample
2175 The whole string between double quotation marks is a single argument
2176 and is printed @i{in toto}.  (Note that in this example, the message
2177 itself will appear in the echo area within double quotes; that is
2178 because you see the value returned by the @code{message} function.  In
2179 most uses of @code{message} in programs that you write, the text will
2180 be printed in the echo area as a side-effect, without the quotes.
2181 @xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2182 detail}, for an example of this.)
2184 However, if there is a @samp{%s} in the quoted string of characters, the
2185 @code{message} function does not print the @samp{%s} as such, but looks
2186 to the argument that follows the string.  It evaluates the second
2187 argument and prints the value at the location in the string where the
2188 @samp{%s} is.
2190 @need 1250
2191 You can see this by positioning the cursor after the following
2192 expression and typing @kbd{C-x C-e}:
2194 @smallexample
2195 (message "The name of this buffer is: %s." (buffer-name))
2196 @end smallexample
2198 @noindent
2199 In Info, @code{"The name of this buffer is: *info*."} will appear in the
2200 echo area.  The function @code{buffer-name} returns the name of the
2201 buffer as a string, which the @code{message} function inserts in place
2202 of @code{%s}.
2204 To print a value as an integer, use @samp{%d} in the same way as
2205 @samp{%s}.  For example, to print a message in the echo area that
2206 states the value of the @code{fill-column}, evaluate the following:
2208 @smallexample
2209 (message "The value of fill-column is %d." fill-column)
2210 @end smallexample
2212 @noindent
2213 On my system, when I evaluate this list, @code{"The value of
2214 fill-column is 72."} appears in my echo area@footnote{Actually, you
2215 can use @code{%s} to print a number.  It is non-specific.  @code{%d}
2216 prints only the part of a number left of a decimal point, and not
2217 anything that is not a number.}.
2219 If there is more than one @samp{%s} in the quoted string, the value of
2220 the first argument following the quoted string is printed at the
2221 location of the first @samp{%s} and the value of the second argument is
2222 printed at the location of the second @samp{%s}, and so on.
2224 @need 1250
2225 For example, if you evaluate the following,
2227 @smallexample
2228 @group
2229 (message "There are %d %s in the office!"
2230          (- fill-column 14) "pink elephants")
2231 @end group
2232 @end smallexample
2234 @noindent
2235 a rather whimsical message will appear in your echo area.  On my system
2236 it says, @code{"There are 58 pink elephants in the office!"}.
2238 The expression @code{(- fill-column 14)} is evaluated and the resulting
2239 number is inserted in place of the @samp{%d}; and the string in double
2240 quotes, @code{"pink elephants"}, is treated as a single argument and
2241 inserted in place of the @samp{%s}.  (That is to say, a string between
2242 double quotes evaluates to itself, like a number.)
2244 Finally, here is a somewhat complex example that not only illustrates
2245 the computation of a number, but also shows how you can use an
2246 expression within an expression to generate the text that is substituted
2247 for @samp{%s}:
2249 @smallexample
2250 @group
2251 (message "He saw %d %s"
2252          (- fill-column 32)
2253          (concat "red "
2254                  (substring
2255                   "The quick brown foxes jumped." 16 21)
2256                  " leaping."))
2257 @end group
2258 @end smallexample
2260 In this example, @code{message} has three arguments: the string,
2261 @code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2262 the expression beginning with the function @code{concat}.  The value
2263 resulting from the evaluation of @code{(- fill-column 32)} is inserted
2264 in place of the @samp{%d}; and the value returned by the expression
2265 beginning with @code{concat} is inserted in place of the @samp{%s}.
2267 When your fill column is 70 and you evaluate the expression, the
2268 message @code{"He saw 38 red foxes leaping."} appears in your echo
2269 area.
2271 @node set & setq
2272 @section Setting the Value of a Variable
2273 @cindex Variable, setting value
2274 @cindex Setting value of variable
2276 @cindex @samp{bind} defined
2277 There are several ways by which a variable can be given a value.  One of
2278 the ways is to use either the function @code{set} or the function
2279 @code{setq}.  Another way is to use @code{let} (@pxref{let}).  (The
2280 jargon for this process is to @dfn{bind} a variable to a value.)
2282 The following sections not only describe how @code{set} and @code{setq}
2283 work but also illustrate how arguments are passed.
2285 @menu
2286 * Using set::                  Setting values.
2287 * Using setq::                 Setting a quoted value.
2288 * Counting::                   Using @code{setq} to count.
2289 @end menu
2291 @node Using set
2292 @subsection Using @code{set}
2293 @findex set
2295 To set the value of the symbol @code{flowers} to the list @code{'(rose
2296 violet daisy buttercup)}, evaluate the following expression by
2297 positioning the cursor after the expression and typing @kbd{C-x C-e}.
2299 @smallexample
2300 (set 'flowers '(rose violet daisy buttercup))
2301 @end smallexample
2303 @noindent
2304 The list @code{(rose violet daisy buttercup)} will appear in the echo
2305 area.  This is what is @emph{returned} by the @code{set} function.  As a
2306 side effect, the symbol @code{flowers} is bound to the list; that is,
2307 the symbol @code{flowers}, which can be viewed as a variable, is given
2308 the list as its value.  (This process, by the way, illustrates how a
2309 side effect to the Lisp interpreter, setting the value, can be the
2310 primary effect that we humans are interested in.  This is because every
2311 Lisp function must return a value if it does not get an error, but it
2312 will only have a side effect if it is designed to have one.)
2314 After evaluating the @code{set} expression, you can evaluate the symbol
2315 @code{flowers} and it will return the value you just set.  Here is the
2316 symbol.  Place your cursor after it and type @kbd{C-x C-e}.
2318 @smallexample
2319 flowers
2320 @end smallexample
2322 @noindent
2323 When you evaluate @code{flowers}, the list
2324 @code{(rose violet daisy buttercup)} appears in the echo area.
2326 Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2327 in front of it, what you will see in the echo area is the symbol itself,
2328 @code{flowers}.  Here is the quoted symbol, so you can try this:
2330 @smallexample
2331 'flowers
2332 @end smallexample
2334 Note also, that when you use @code{set}, you need to quote both
2335 arguments to @code{set}, unless you want them evaluated.  Since we do
2336 not want either argument evaluated, neither the variable
2337 @code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2338 are quoted.  (When you use @code{set} without quoting its first
2339 argument, the first argument is evaluated before anything else is
2340 done.  If you did this and @code{flowers} did not have a value
2341 already, you would get an error message that the @samp{Symbol's value
2342 as variable is void}; on the other hand, if @code{flowers} did return
2343 a value after it was evaluated, the @code{set} would attempt to set
2344 the value that was returned.  There are situations where this is the
2345 right thing for the function to do; but such situations are rare.)
2347 @node Using setq
2348 @subsection Using @code{setq}
2349 @findex setq
2351 As a practical matter, you almost always quote the first argument to
2352 @code{set}.  The combination of @code{set} and a quoted first argument
2353 is so common that it has its own name: the special form @code{setq}.
2354 This special form is just like @code{set} except that the first argument
2355 is quoted automatically, so you don't need to type the quote mark
2356 yourself.  Also, as an added convenience, @code{setq} permits you to set
2357 several different variables to different values, all in one expression.
2359 To set the value of the variable @code{carnivores} to the list
2360 @code{'(lion tiger leopard)} using @code{setq}, the following expression
2361 is used:
2363 @smallexample
2364 (setq carnivores '(lion tiger leopard))
2365 @end smallexample
2367 @noindent
2368 This is exactly the same as using @code{set} except the first argument
2369 is automatically quoted by @code{setq}.  (The @samp{q} in @code{setq}
2370 means @code{quote}.)
2372 @need 1250
2373 With @code{set}, the expression would look like this:
2375 @smallexample
2376 (set 'carnivores '(lion tiger leopard))
2377 @end smallexample
2379 Also, @code{setq} can be used to assign different values to
2380 different variables.  The first argument is bound to the value
2381 of the second argument, the third argument is bound to the value of the
2382 fourth argument, and so on.  For example, you could use the following to
2383 assign a list of trees to the symbol @code{trees} and a list of herbivores
2384 to the symbol @code{herbivores}:
2386 @smallexample
2387 @group
2388 (setq trees '(pine fir oak maple)
2389       herbivores '(gazelle antelope zebra))
2390 @end group
2391 @end smallexample
2393 @noindent
2394 (The expression could just as well have been on one line, but it might
2395 not have fit on a page; and humans find it easier to read nicely
2396 formatted lists.)
2398 Although I have been using the term ``assign'', there is another way of
2399 thinking about the workings of @code{set} and @code{setq}; and that is to
2400 say that @code{set} and @code{setq} make the symbol @emph{point} to the
2401 list.  This latter way of thinking is very common and in forthcoming
2402 chapters we shall come upon at least one symbol that has ``pointer'' as
2403 part of its name.  The name is chosen because the symbol has a value,
2404 specifically a list, attached to it; or, expressed another way,
2405 the symbol is set to point to the list.
2407 @node Counting
2408 @subsection Counting
2409 @cindex Counting
2411 Here is an example that shows how to use @code{setq} in a counter.  You
2412 might use this to count how many times a part of your program repeats
2413 itself.  First set a variable to zero; then add one to the number each
2414 time the program repeats itself.  To do this, you need a variable that
2415 serves as a counter, and two expressions: an initial @code{setq}
2416 expression that sets the counter variable to zero; and a second
2417 @code{setq} expression that increments the counter each time it is
2418 evaluated.
2420 @smallexample
2421 @group
2422 (setq counter 0)                ; @r{Let's call this the initializer.}
2424 (setq counter (+ counter 1))    ; @r{This is the incrementer.}
2426 counter                         ; @r{This is the counter.}
2427 @end group
2428 @end smallexample
2430 @noindent
2431 (The text following the @samp{;} are comments.  @xref{Change a
2432 defun, , Change a Function Definition}.)
2434 If you evaluate the first of these expressions, the initializer,
2435 @code{(setq counter 0)}, and then evaluate the third expression,
2436 @code{counter}, the number @code{0} will appear in the echo area.  If
2437 you then evaluate the second expression, the incrementer, @code{(setq
2438 counter (+ counter 1))}, the counter will get the value 1.  So if you
2439 again evaluate @code{counter}, the number @code{1} will appear in the
2440 echo area.  Each time you evaluate the second expression, the value of
2441 the counter will be incremented.
2443 When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2444 the Lisp interpreter first evaluates the innermost list; this is the
2445 addition.  In order to evaluate this list, it must evaluate the variable
2446 @code{counter} and the number @code{1}.  When it evaluates the variable
2447 @code{counter}, it receives its current value.  It passes this value and
2448 the number @code{1} to the @code{+} which adds them together.  The sum
2449 is then returned as the value of the inner list and passed to the
2450 @code{setq} which sets the variable @code{counter} to this new value.
2451 Thus, the value of the variable, @code{counter}, is changed.
2453 @node Summary
2454 @section Summary
2456 Learning Lisp is like climbing a hill in which the first part is the
2457 steepest.  You have now climbed the most difficult part; what remains
2458 becomes easier as you progress onwards.
2460 @need 1000
2461 In summary,
2463 @itemize @bullet
2465 @item
2466 Lisp programs are made up of expressions, which are lists or single atoms.
2468 @item
2469 Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2470 surrounded by parentheses.  A list can be empty.
2472 @item
2473 Atoms are multi-character symbols, like @code{forward-paragraph}, single
2474 character symbols like @code{+}, strings of characters between double
2475 quotation marks, or numbers.
2477 @item
2478 A number evaluates to itself.
2480 @item
2481 A string between double quotes also evaluates to itself.
2483 @item
2484 When you evaluate a symbol by itself, its value is returned.
2486 @item
2487 When you evaluate a list, the Lisp interpreter looks at the first symbol
2488 in the list and then at the function definition bound to that symbol.
2489 Then the instructions in the function definition are carried out.
2491 @item
2492 A single-quote @samp{'} tells the Lisp interpreter that it should
2493 return the following expression as written, and not evaluate it as it
2494 would if the quote were not there.
2496 @item
2497 Arguments are the information passed to a function.  The arguments to a
2498 function are computed by evaluating the rest of the elements of the list
2499 of which the function is the first element.
2501 @item
2502 A function always returns a value when it is evaluated (unless it gets
2503 an error); in addition, it may also carry out some action that is a
2504 side effect.  In many cases, a function's primary purpose is to
2505 create a side effect.
2506 @end itemize
2508 @node Error Message Exercises
2509 @section Exercises
2511 A few simple exercises:
2513 @itemize @bullet
2514 @item
2515 Generate an error message by evaluating an appropriate symbol that is
2516 not within parentheses.
2518 @item
2519 Generate an error message by evaluating an appropriate symbol that is
2520 between parentheses.
2522 @item
2523 Create a counter that increments by two rather than one.
2525 @item
2526 Write an expression that prints a message in the echo area when
2527 evaluated.
2528 @end itemize
2530 @node Practicing Evaluation
2531 @chapter Practicing Evaluation
2532 @cindex Practicing evaluation
2533 @cindex Evaluation practice
2535 Before learning how to write a function definition in Emacs Lisp, it is
2536 useful to spend a little time evaluating various expressions that have
2537 already been written.  These expressions will be lists with the
2538 functions as their first (and often only) element.  Since some of the
2539 functions associated with buffers are both simple and interesting, we
2540 will start with those.  In this section, we will evaluate a few of
2541 these.  In another section, we will study the code of several other
2542 buffer-related functions, to see how they were written.
2544 @menu
2545 * How to Evaluate::            Typing editing commands or @kbd{C-x C-e}
2546                                  causes evaluation.
2547 * Buffer Names::               Buffers and files are different.
2548 * Getting Buffers::            Getting a buffer itself, not merely its name.
2549 * Switching Buffers::          How to change to another buffer.
2550 * Buffer Size & Locations::    Where point is located and the size of
2551                                the buffer.
2552 * Evaluation Exercise::
2553 @end menu
2555 @ifnottex
2556 @node How to Evaluate
2557 @unnumberedsec How to Evaluate
2558 @end ifnottex
2560 @i{Whenever you give an editing command} to Emacs Lisp, such as the
2561 command to move the cursor or to scroll the screen, @i{you are evaluating
2562 an expression,} the first element of which is a function.  @i{This is
2563 how Emacs works.}
2565 @cindex @samp{interactive function} defined
2566 @cindex @samp{command} defined
2567 When you type keys, you cause the Lisp interpreter to evaluate an
2568 expression and that is how you get your results.  Even typing plain text
2569 involves evaluating an Emacs Lisp function, in this case, one that uses
2570 @code{self-insert-command}, which simply inserts the character you
2571 typed.  The functions you evaluate by typing keystrokes are called
2572 @dfn{interactive} functions, or @dfn{commands}; how you make a function
2573 interactive will be illustrated in the chapter on how to write function
2574 definitions.  @xref{Interactive, , Making a Function Interactive}.
2576 In addition to typing keyboard commands, we have seen a second way to
2577 evaluate an expression: by positioning the cursor after a list and
2578 typing @kbd{C-x C-e}.  This is what we will do in the rest of this
2579 section.  There are other ways to evaluate an expression as well; these
2580 will be described as we come to them.
2582 Besides being used for practicing evaluation, the functions shown in the
2583 next few sections are important in their own right.  A study of these
2584 functions makes clear the distinction between buffers and files, how to
2585 switch to a buffer, and how to determine a location within it.
2587 @node Buffer Names
2588 @section Buffer Names
2589 @findex buffer-name
2590 @findex buffer-file-name
2592 The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2593 the difference between a file and a buffer.  When you evaluate the
2594 following expression, @code{(buffer-name)}, the name of the buffer
2595 appears in the echo area.  When you evaluate @code{(buffer-file-name)},
2596 the name of the file to which the buffer refers appears in the echo
2597 area.  Usually, the name returned by @code{(buffer-name)} is the same as
2598 the name of the file to which it refers, and the name returned by
2599 @code{(buffer-file-name)} is the full path-name of the file.
2601 A file and a buffer are two different entities.  A file is information
2602 recorded permanently in the computer (unless you delete it).  A buffer,
2603 on the other hand, is information inside of Emacs that will vanish at
2604 the end of the editing session (or when you kill the buffer).  Usually,
2605 a buffer contains information that you have copied from a file; we say
2606 the buffer is @dfn{visiting} that file.  This copy is what you work on
2607 and modify.  Changes to the buffer do not change the file, until you
2608 save the buffer.  When you save the buffer, the buffer is copied to the file
2609 and is thus saved permanently.
2611 @need 1250
2612 If you are reading this in Info inside of GNU Emacs, you can evaluate
2613 each of the following expressions by positioning the cursor after it and
2614 typing @kbd{C-x C-e}.
2616 @example
2617 @group
2618 (buffer-name)
2620 (buffer-file-name)
2621 @end group
2622 @end example
2624 @noindent
2625 When I do this in Info, the value returned by evaluating
2626 @code{(buffer-name)} is @file{"*info*"}, and the value returned by
2627 evaluating @code{(buffer-file-name)} is @file{nil}.
2629 On the other hand, while I am writing this document, the value
2630 returned by evaluating @code{(buffer-name)} is
2631 @file{"introduction.texinfo"}, and the value returned by evaluating
2632 @code{(buffer-file-name)} is
2633 @file{"/gnu/work/intro/introduction.texinfo"}.
2635 @cindex @code{nil}, history of word
2636 The former is the name of the buffer and the latter is the name of the
2637 file.  In Info, the buffer name is @file{"*info*"}.  Info does not
2638 point to any file, so the result of evaluating
2639 @code{(buffer-file-name)} is @file{nil}.  The symbol @code{nil} is
2640 from the Latin word for ``nothing''; in this case, it means that the
2641 buffer is not associated with any file.  (In Lisp, @code{nil} is also
2642 used to mean ``false'' and is a synonym for the empty list, @code{()}.)
2644 When I am writing, the name of my buffer is
2645 @file{"introduction.texinfo"}.  The name of the file to which it
2646 points is @file{"/gnu/work/intro/introduction.texinfo"}.
2648 (In the expressions, the parentheses tell the Lisp interpreter to
2649 treat @w{@code{buffer-name}} and @w{@code{buffer-file-name}} as
2650 functions; without the parentheses, the interpreter would attempt to
2651 evaluate the symbols as variables.  @xref{Variables}.)
2653 In spite of the distinction between files and buffers, you will often
2654 find that people refer to a file when they mean a buffer and vice versa.
2655 Indeed, most people say, ``I am editing a file,'' rather than saying,
2656 ``I am editing a buffer which I will soon save to a file.''  It is
2657 almost always clear from context what people mean.  When dealing with
2658 computer programs, however, it is important to keep the distinction in mind,
2659 since the computer is not as smart as a person.
2661 @cindex Buffer, history of word
2662 The word ``buffer'', by the way, comes from the meaning of the word as a
2663 cushion that deadens the force of a collision.  In early computers, a
2664 buffer cushioned the interaction between files and the computer's
2665 central processing unit.  The drums or tapes that held a file and the
2666 central processing unit were pieces of equipment that were very
2667 different from each other, working at their own speeds, in spurts.  The
2668 buffer made it possible for them to work together effectively.
2669 Eventually, the buffer grew from being an intermediary, a temporary
2670 holding place, to being the place where work is done.  This
2671 transformation is rather like that of a small seaport that grew into a
2672 great city: once it was merely the place where cargo was warehoused
2673 temporarily before being loaded onto ships; then it became a business
2674 and cultural center in its own right.
2676 Not all buffers are associated with files.  For example, a
2677 @file{*scratch*} buffer does not visit any file.  Similarly, a
2678 @file{*Help*} buffer is not associated with any file.
2680 In the old days, when you lacked a @file{~/.emacs} file and started an
2681 Emacs session by typing the command @code{emacs} alone, without naming
2682 any files, Emacs started with the @file{*scratch*} buffer visible.
2683 Nowadays, you will see a splash screen.  You can follow one of the
2684 commands suggested on the splash screen, visit a file, or press the
2685 spacebar to reach the @file{*scratch*} buffer.
2687 If you switch to the @file{*scratch*} buffer, type
2688 @code{(buffer-name)}, position the cursor after it, and then type
2689 @kbd{C-x C-e} to evaluate the expression.  The name @code{"*scratch*"}
2690 will be returned and will appear in the echo area.  @code{"*scratch*"}
2691 is the name of the buffer.  When you type @code{(buffer-file-name)} in
2692 the @file{*scratch*} buffer and evaluate that, @code{nil} will appear
2693 in the echo area, just as it does when you evaluate
2694 @code{(buffer-file-name)} in Info.
2696 Incidentally, if you are in the @file{*scratch*} buffer and want the
2697 value returned by an expression to appear in the @file{*scratch*}
2698 buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2699 instead of @kbd{C-x C-e}.  This causes the value returned to appear
2700 after the expression.  The buffer will look like this:
2702 @smallexample
2703 (buffer-name)"*scratch*"
2704 @end smallexample
2706 @noindent
2707 You cannot do this in Info since Info is read-only and it will not allow
2708 you to change the contents of the buffer.  But you can do this in any
2709 buffer you can edit; and when you write code or documentation (such as
2710 this book), this feature is very useful.
2712 @node Getting Buffers
2713 @section Getting Buffers
2714 @findex current-buffer
2715 @findex other-buffer
2716 @cindex Getting a buffer
2718 The @code{buffer-name} function returns the @emph{name} of the buffer;
2719 to get the buffer @emph{itself}, a different function is needed: the
2720 @code{current-buffer} function.  If you use this function in code, what
2721 you get is the buffer itself.
2723 A name and the object or entity to which the name refers are different
2724 from each other.  You are not your name.  You are a person to whom
2725 others refer by name.  If you ask to speak to George and someone hands you
2726 a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2727 @samp{g}, and @samp{e} written on it, you might be amused, but you would
2728 not be satisfied.  You do not want to speak to the name, but to the
2729 person to whom the name refers.  A buffer is similar: the name of the
2730 scratch buffer is @file{*scratch*}, but the name is not the buffer.  To
2731 get a buffer itself, you need to use a function such as
2732 @code{current-buffer}.
2734 However, there is a slight complication: if you evaluate
2735 @code{current-buffer} in an expression on its own, as we will do here,
2736 what you see is a printed representation of the name of the buffer
2737 without the contents of the buffer.  Emacs works this way for two
2738 reasons: the buffer may be thousands of lines long---too long to be
2739 conveniently displayed; and, another buffer may have the same contents
2740 but a different name, and it is important to distinguish between them.
2742 @need 800
2743 Here is an expression containing the function:
2745 @smallexample
2746 (current-buffer)
2747 @end smallexample
2749 @noindent
2750 If you evaluate this expression in Info in Emacs in the usual way,
2751 @file{#<buffer *info*>} will appear in the echo area.  The special
2752 format indicates that the buffer itself is being returned, rather than
2753 just its name.
2755 Incidentally, while you can type a number or symbol into a program, you
2756 cannot do that with the printed representation of a buffer: the only way
2757 to get a buffer itself is with a function such as @code{current-buffer}.
2759 A related function is @code{other-buffer}.  This returns the most
2760 recently selected buffer other than the one you are in currently, not
2761 a printed representation of its name.  If you have recently switched
2762 back and forth from the @file{*scratch*} buffer, @code{other-buffer}
2763 will return that buffer.
2765 @need 800
2766 You can see this by evaluating the expression:
2768 @smallexample
2769 (other-buffer)
2770 @end smallexample
2772 @noindent
2773 You should see @file{#<buffer *scratch*>} appear in the echo area, or
2774 the name of whatever other buffer you switched back from most
2775 recently@footnote{Actually, by default, if the buffer from which you
2776 just switched is visible to you in another window, @code{other-buffer}
2777 will choose the most recent buffer that you cannot see; this is a
2778 subtlety that I often forget.}.
2780 @node Switching Buffers
2781 @section Switching Buffers
2782 @findex switch-to-buffer
2783 @findex set-buffer
2784 @cindex Switching to a buffer
2786 The @code{other-buffer} function actually provides a buffer when it is
2787 used as an argument to a function that requires one.  We can see this
2788 by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2789 different buffer.
2791 But first, a brief introduction to the @code{switch-to-buffer}
2792 function.  When you switched back and forth from Info to the
2793 @file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2794 likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2795 rather, to save typing, you probably only typed @kbd{RET} if the
2796 default buffer was @file{*scratch*}, or if it was different, then you
2797 typed just part of the name, such as @code{*sc}, pressed your
2798 @kbd{TAB} key to cause it to expand to the full name, and then typed
2799 @kbd{RET}.} when prompted in the minibuffer for the name of
2800 the buffer to which you wanted to switch.  The keystrokes, @kbd{C-x
2801 b}, cause the Lisp interpreter to evaluate the interactive function
2802 @code{switch-to-buffer}.  As we said before, this is how Emacs works:
2803 different keystrokes call or run different functions.  For example,
2804 @kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2805 @code{forward-sentence}, and so on.
2807 By writing @code{switch-to-buffer} in an expression, and giving it a
2808 buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2809 does:
2811 @smallexample
2812 (switch-to-buffer (other-buffer))
2813 @end smallexample
2815 @noindent
2816 The symbol @code{switch-to-buffer} is the first element of the list,
2817 so the Lisp interpreter will treat it as a function and carry out the
2818 instructions that are attached to it.  But before doing that, the
2819 interpreter will note that @code{other-buffer} is inside parentheses
2820 and work on that symbol first.  @code{other-buffer} is the first (and
2821 in this case, the only) element of this list, so the Lisp interpreter
2822 calls or runs the function.  It returns another buffer.  Next, the
2823 interpreter runs @code{switch-to-buffer}, passing to it, as an
2824 argument, the other buffer, which is what Emacs will switch to.  If
2825 you are reading this in Info, try this now.  Evaluate the expression.
2826 (To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2827 expression will move you to your most recent other buffer that you
2828 cannot see.  If you really want to go to your most recently selected
2829 buffer, even if you can still see it, you need to evaluate the
2830 following more complex expression:
2832 @smallexample
2833 (switch-to-buffer (other-buffer (current-buffer) t))
2834 @end smallexample
2836 @c noindent
2837 In this case, the first argument to @code{other-buffer} tells it which
2838 buffer to skip---the current one---and the second argument tells
2839 @code{other-buffer} it is OK to switch to a visible buffer.  In
2840 regular use, @code{switch-to-buffer} takes you to a buffer not visible
2841 in windows since you would most likely use @kbd{C-x o}
2842 (@code{other-window}) to go to another visible buffer.}
2844 In the programming examples in later sections of this document, you will
2845 see the function @code{set-buffer} more often than
2846 @code{switch-to-buffer}.  This is because of a difference between
2847 computer programs and humans: humans have eyes and expect to see the
2848 buffer on which they are working on their computer terminals.  This is
2849 so obvious, it almost goes without saying.  However, programs do not
2850 have eyes.  When a computer program works on a buffer, that buffer does
2851 not need to be visible on the screen.
2853 @code{switch-to-buffer} is designed for humans and does two different
2854 things: it switches the buffer to which Emacs's attention is directed; and
2855 it switches the buffer displayed in the window to the new buffer.
2856 @code{set-buffer}, on the other hand, does only one thing: it switches
2857 the attention of the computer program to a different buffer.  The buffer
2858 on the screen remains unchanged (of course, normally nothing happens
2859 there until the command finishes running).
2861 @cindex @samp{call} defined
2862 Also, we have just introduced another jargon term, the word @dfn{call}.
2863 When you evaluate a list in which the first symbol is a function, you
2864 are calling that function.  The use of the term comes from the notion of
2865 the function as an entity that can do something for you if you call
2866 it---just as a plumber is an entity who can fix a leak if you call him
2867 or her.
2869 @node Buffer Size & Locations
2870 @section Buffer Size and the Location of Point
2871 @cindex Size of buffer
2872 @cindex Buffer size
2873 @cindex Point location
2874 @cindex Location of point
2876 Finally, let's look at several rather simple functions,
2877 @code{buffer-size}, @code{point}, @code{point-min}, and
2878 @code{point-max}.  These give information about the size of a buffer and
2879 the location of point within it.
2881 The function @code{buffer-size} tells you the size of the current
2882 buffer; that is, the function returns a count of the number of
2883 characters in the buffer.
2885 @smallexample
2886 (buffer-size)
2887 @end smallexample
2889 @noindent
2890 You can evaluate this in the usual way, by positioning the
2891 cursor after the expression and typing @kbd{C-x C-e}.
2893 @cindex @samp{point} defined
2894 In Emacs, the current  position of the cursor is called @dfn{point}.
2895 The expression @code{(point)} returns a number that tells you where the
2896 cursor is located as a count of the number of characters from the
2897 beginning of the buffer up to point.
2899 @need 1250
2900 You can see the character count for point in this buffer by evaluating
2901 the following expression in the usual way:
2903 @smallexample
2904 (point)
2905 @end smallexample
2907 @noindent
2908 As I write this, the value of point is 65724.  The @code{point}
2909 function is frequently used in some of the examples later in this
2910 book.
2912 @need 1250
2913 The value of point depends, of course, on its location within the
2914 buffer.  If you evaluate point in this spot, the number will be larger:
2916 @smallexample
2917 (point)
2918 @end smallexample
2920 @noindent
2921 For me, the value of point in this location is 66043, which means that
2922 there are 319 characters (including spaces) between the two
2923 expressions.  (Doubtless, you will see different numbers, since I will
2924 have edited this since I first evaluated point.)
2926 @cindex @samp{narrowing} defined
2927 The function @code{point-min} is somewhat similar to @code{point}, but
2928 it returns the value of the minimum permissible value of point in the
2929 current buffer.  This is the number 1 unless @dfn{narrowing} is in
2930 effect.  (Narrowing is a mechanism whereby you can restrict yourself,
2931 or a program, to operations on just a part of a buffer.
2932 @xref{Narrowing & Widening, , Narrowing and Widening}.)  Likewise, the
2933 function @code{point-max} returns the value of the maximum permissible
2934 value of point in the current buffer.
2936 @node Evaluation Exercise
2937 @section Exercise
2939 Find a file with which you are working and move towards its middle.
2940 Find its buffer name, file name, length, and your position in the file.
2942 @node Writing Defuns
2943 @chapter How To Write Function Definitions
2944 @cindex Definition writing
2945 @cindex Function definition writing
2946 @cindex Writing a function definition
2948 When the Lisp interpreter evaluates a list, it looks to see whether the
2949 first symbol on the list has a function definition attached to it; or,
2950 put another way, whether the symbol points to a function definition.  If
2951 it does, the computer carries out the instructions in the definition.  A
2952 symbol that has a function definition is called, simply, a function
2953 (although, properly speaking, the definition is the function and the
2954 symbol refers to it.)
2956 @menu
2957 * Primitive Functions::
2958 * defun::                        The @code{defun} macro.
2959 * Install::                      Install a function definition.
2960 * Interactive::                  Making a function interactive.
2961 * Interactive Options::          Different options for @code{interactive}.
2962 * Permanent Installation::       Installing code permanently.
2963 * let::                          Creating and initializing local variables.
2964 * if::                           What if?
2965 * else::                         If--then--else expressions.
2966 * Truth & Falsehood::            What Lisp considers false and true.
2967 * save-excursion::               Keeping track of point and buffer.
2968 * Review::
2969 * defun Exercises::
2970 @end menu
2972 @ifnottex
2973 @node Primitive Functions
2974 @unnumberedsec An Aside about Primitive Functions
2975 @end ifnottex
2976 @cindex Primitive functions
2977 @cindex Functions, primitive
2979 @cindex C language primitives
2980 @cindex Primitives written in C
2981 All functions are defined in terms of other functions, except for a few
2982 @dfn{primitive} functions that are written in the C programming
2983 language.  When you write functions' definitions, you will write them in
2984 Emacs Lisp and use other functions as your building blocks.  Some of the
2985 functions you will use will themselves be written in Emacs Lisp (perhaps
2986 by you) and some will be primitives written in C@.  The primitive
2987 functions are used exactly like those written in Emacs Lisp and behave
2988 like them.  They are written in C so we can easily run GNU Emacs on any
2989 computer that has sufficient power and can run C.
2991 Let me re-emphasize this: when you write code in Emacs Lisp, you do not
2992 distinguish between the use of functions written in C and the use of
2993 functions written in Emacs Lisp.  The difference is irrelevant.  I
2994 mention the distinction only because it is interesting to know.  Indeed,
2995 unless you investigate, you won't know whether an already-written
2996 function is written in Emacs Lisp or C.
2998 @node defun
2999 @section The @code{defun} Macro
3000 @findex defun
3002 @cindex @samp{function definition} defined
3003 In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3004 it that tells the computer what to do when the function is called.
3005 This code is called the @dfn{function definition} and is created by
3006 evaluating a Lisp expression that starts with the symbol @code{defun}
3007 (which is an abbreviation for @emph{define function}).
3009 In subsequent sections, we will look at function definitions from the
3010 Emacs source code, such as @code{mark-whole-buffer}.  In this section,
3011 we will describe a simple function definition so you can see how it
3012 looks.  This function definition uses arithmetic because it makes for a
3013 simple example.  Some people dislike examples using arithmetic; however,
3014 if you are such a person, do not despair.  Hardly any of the code we
3015 will study in the remainder of this introduction involves arithmetic or
3016 mathematics.  The examples mostly involve text in one way or another.
3018 A function definition has up to five parts following the word
3019 @code{defun}:
3021 @enumerate
3022 @item
3023 The name of the symbol to which the function definition should be
3024 attached.
3026 @item
3027 A list of the arguments that will be passed to the function.  If no
3028 arguments will be passed to the function, this is an empty list,
3029 @code{()}.
3031 @item
3032 Documentation describing the function.  (Technically optional, but
3033 strongly recommended.)
3035 @item
3036 Optionally, an expression to make the function interactive so you can
3037 use it by typing @kbd{M-x} and then the name of the function; or by
3038 typing an appropriate key or keychord.
3040 @cindex @samp{body} defined
3041 @item
3042 The code that instructs the computer what to do: the @dfn{body} of the
3043 function definition.
3044 @end enumerate
3046 It is helpful to think of the five parts of a function definition as
3047 being organized in a template, with slots for each part:
3049 @smallexample
3050 @group
3051 (defun @var{function-name} (@var{arguments}@dots{})
3052   "@var{optional-documentation}@dots{}"
3053   (interactive @var{argument-passing-info})     ; @r{optional}
3054   @var{body}@dots{})
3055 @end group
3056 @end smallexample
3058 As an example, here is the code for a function that multiplies its
3059 argument by 7.  (This example is not interactive.  @xref{Interactive,
3060 , Making a Function Interactive}, for that information.)
3062 @smallexample
3063 @group
3064 (defun multiply-by-seven (number)
3065   "Multiply NUMBER by seven."
3066   (* 7 number))
3067 @end group
3068 @end smallexample
3070 This definition begins with a parenthesis and the symbol @code{defun},
3071 followed by the name of the function.
3073 @cindex @samp{argument list} defined
3074 The name of the function is followed by a list that contains the
3075 arguments that will be passed to the function.  This list is called
3076 the @dfn{argument list}.  In this example, the list has only one
3077 element, the symbol, @code{number}.  When the function is used, the
3078 symbol will be bound to the value that is used as the argument to the
3079 function.
3081 Instead of choosing the word @code{number} for the name of the argument,
3082 I could have picked any other name.  For example, I could have chosen
3083 the word @code{multiplicand}.  I picked the word ``number'' because it
3084 tells what kind of value is intended for this slot; but I could just as
3085 well have chosen the word ``multiplicand'' to indicate the role that the
3086 value placed in this slot will play in the workings of the function.  I
3087 could have called it @code{foogle}, but that would have been a bad
3088 choice because it would not tell humans what it means.  The choice of
3089 name is up to the programmer and should be chosen to make the meaning of
3090 the function clear.
3092 Indeed, you can choose any name you wish for a symbol in an argument
3093 list, even the name of a symbol used in some other function: the name
3094 you use in an argument list is private to that particular definition.
3095 In that definition, the name refers to a different entity than any use
3096 of the same name outside the function definition.  Suppose you have a
3097 nick-name ``Shorty'' in your family; when your family members refer to
3098 ``Shorty'', they mean you.  But outside your family, in a movie, for
3099 example, the name ``Shorty'' refers to someone else.  Because a name in an
3100 argument list is private to the function definition, you can change the
3101 value of such a symbol inside the body of a function without changing
3102 its value outside the function.  The effect is similar to that produced
3103 by a @code{let} expression.  (@xref{let, , @code{let}}.)
3105 @ignore
3106 Note also that we discuss the word ``number'' in two different ways: as a
3107 symbol that appears in the code, and as the name of something that will
3108 be replaced by a something else during the evaluation of the function.
3109 In the first case, @code{number} is a symbol, not a number; it happens
3110 that within the function, it is a variable who value is the number in
3111 question, but our primary interest in it is as a symbol.  On the other
3112 hand, when we are talking about the function, our interest is that we
3113 will substitute a number for the word @var{number}.  To keep this
3114 distinction clear, we use different typography for the two
3115 circumstances.  When we talk about this function, or about how it works,
3116 we refer to this number by writing @var{number}.  In the function
3117 itself, we refer to it by writing @code{number}.
3118 @end ignore
3120 The argument list is followed by the documentation string that
3121 describes the function.  This is what you see when you type
3122 @w{@kbd{C-h f}} and the name of a function.  Incidentally, when you
3123 write a documentation string like this, you should make the first line
3124 a complete sentence since some commands, such as @code{apropos}, print
3125 only the first line of a multi-line documentation string.  Also, you
3126 should not indent the second line of a documentation string, if you
3127 have one, because that looks odd when you use @kbd{C-h f}
3128 (@code{describe-function}).  The documentation string is optional, but
3129 it is so useful, it should be included in almost every function you
3130 write.
3132 @findex * @r{(multiplication)}
3133 The third line of the example consists of the body of the function
3134 definition.  (Most functions' definitions, of course, are longer than
3135 this.)  In this function, the body is the list, @code{(* 7 number)}, which
3136 says to multiply the value of @var{number} by 7.  (In Emacs Lisp,
3137 @code{*} is the function for multiplication, just as @code{+} is the
3138 function for addition.)
3140 When you use the @code{multiply-by-seven} function, the argument
3141 @code{number} evaluates to the actual number you want used.  Here is an
3142 example that shows how @code{multiply-by-seven} is used; but don't try
3143 to evaluate this yet!
3145 @smallexample
3146 (multiply-by-seven 3)
3147 @end smallexample
3149 @noindent
3150 The symbol @code{number}, specified in the function definition in the
3151 next section, is bound to the value 3 in the actual use of
3152 the function.  Note that although @code{number} was inside parentheses
3153 in the function definition, the argument passed to the
3154 @code{multiply-by-seven} function is not in parentheses.  The
3155 parentheses are written in the function definition so the computer can
3156 figure out where the argument list ends and the rest of the function
3157 definition begins.
3159 If you evaluate this example, you are likely to get an error message.
3160 (Go ahead, try it!)  This is because we have written the function
3161 definition, but not yet told the computer about the definition---we have
3162 not yet loaded the function definition in Emacs.
3163 Installing a function is the process that tells the Lisp interpreter the
3164 definition of the function.  Installation is described in the next
3165 section.
3167 @node Install
3168 @section Install a Function Definition
3169 @cindex Install a Function Definition
3170 @cindex Definition installation
3171 @cindex Function definition installation
3173 If you are reading this inside of Info in Emacs, you can try out the
3174 @code{multiply-by-seven} function by first evaluating the function
3175 definition and then evaluating @code{(multiply-by-seven 3)}.  A copy of
3176 the function definition follows.  Place the cursor after the last
3177 parenthesis of the function definition and type @kbd{C-x C-e}.  When you
3178 do this, @code{multiply-by-seven} will appear in the echo area.  (What
3179 this means is that when a function definition is evaluated, the value it
3180 returns is the name of the defined function.)  At the same time, this
3181 action installs the function definition.
3183 @smallexample
3184 @group
3185 (defun multiply-by-seven (number)
3186   "Multiply NUMBER by seven."
3187   (* 7 number))
3188 @end group
3189 @end smallexample
3191 @noindent
3192 By evaluating this @code{defun}, you have just installed
3193 @code{multiply-by-seven} in Emacs.  The function is now just as much a
3194 part of Emacs as @code{forward-word} or any other editing function you
3195 use.  (@code{multiply-by-seven} will stay installed until you quit
3196 Emacs.  To reload code automatically whenever you start Emacs, see
3197 @ref{Permanent Installation, , Installing Code Permanently}.)
3199 @menu
3200 * Effect of installation::
3201 * Change a defun::              How to change a function definition.
3202 @end menu
3204 @ifnottex
3205 @node Effect of installation
3206 @unnumberedsubsec The effect of installation
3207 @end ifnottex
3209 You can see the effect of installing @code{multiply-by-seven} by
3210 evaluating the following sample.  Place the cursor after the following
3211 expression and type @kbd{C-x C-e}.  The number 21 will appear in the
3212 echo area.
3214 @smallexample
3215 (multiply-by-seven 3)
3216 @end smallexample
3218 If you wish, you can read the documentation for the function by typing
3219 @kbd{C-h f} (@code{describe-function}) and then the name of the
3220 function, @code{multiply-by-seven}.  When you do this, a
3221 @file{*Help*} window will appear on your screen that says:
3223 @smallexample
3224 @group
3225 multiply-by-seven is a Lisp function.
3227 (multiply-by-seven NUMBER)
3229 Multiply NUMBER by seven.
3230 @end group
3231 @end smallexample
3233 @noindent
3234 (To return to a single window on your screen, type @kbd{C-x 1}.)
3236 @node Change a defun
3237 @subsection Change a Function Definition
3238 @cindex Changing a function definition
3239 @cindex Function definition, how to change
3240 @cindex Definition, how to change
3242 If you want to change the code in @code{multiply-by-seven}, just rewrite
3243 it.  To install the new version in place of the old one, evaluate the
3244 function definition again.  This is how you modify code in Emacs.  It is
3245 very simple.
3247 As an example, you can change the @code{multiply-by-seven} function to
3248 add the number to itself seven times instead of multiplying the number
3249 by seven.  It produces the same answer, but by a different path.  At
3250 the same time, we will add a comment to the code; a comment is text
3251 that the Lisp interpreter ignores, but that a human reader may find
3252 useful or enlightening.  The comment is that this is the second
3253 version.
3255 @smallexample
3256 @group
3257 (defun multiply-by-seven (number)       ; @r{Second version.}
3258   "Multiply NUMBER by seven."
3259   (+ number number number number number number number))
3260 @end group
3261 @end smallexample
3263 @cindex Comments in Lisp code
3264 The comment follows a semicolon, @samp{;}.  In Lisp, everything on a
3265 line that follows a semicolon is a comment.  The end of the line is the
3266 end of the comment.  To stretch a comment over two or more lines, begin
3267 each line with a semicolon.
3269 @xref{Beginning init File, , Beginning a @file{.emacs}
3270 File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3271 Reference Manual}, for more about comments.
3273 You can install this version of the @code{multiply-by-seven} function by
3274 evaluating it in the same way you evaluated the first function: place
3275 the cursor after the last parenthesis and type @kbd{C-x C-e}.
3277 In summary, this is how you write code in Emacs Lisp: you write a
3278 function; install it; test it; and then make fixes or enhancements and
3279 install it again.
3281 @node Interactive
3282 @section Make a Function Interactive
3283 @cindex Interactive functions
3284 @findex interactive
3286 You make a function interactive by placing a list that begins with
3287 the special form @code{interactive} immediately after the
3288 documentation.  A user can invoke an interactive function by typing
3289 @kbd{M-x} and then the name of the function; or by typing the keys to
3290 which it is bound, for example, by typing @kbd{C-n} for
3291 @code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3293 Interestingly, when you call an interactive function interactively,
3294 the value returned is not automatically displayed in the echo area.
3295 This is because you often call an interactive function for its side
3296 effects, such as moving forward by a word or line, and not for the
3297 value returned.  If the returned value were displayed in the echo area
3298 each time you typed a key, it would be very distracting.
3300 @menu
3301 * Interactive multiply-by-seven::  An overview.
3302 * multiply-by-seven in detail::    The interactive version.
3303 @end menu
3305 @ifnottex
3306 @node Interactive multiply-by-seven
3307 @unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3308 @end ifnottex
3310 Both the use of the special form @code{interactive} and one way to
3311 display a value in the echo area can be illustrated by creating an
3312 interactive version of @code{multiply-by-seven}.
3314 @need 1250
3315 Here is the code:
3317 @smallexample
3318 @group
3319 (defun multiply-by-seven (number)       ; @r{Interactive version.}
3320   "Multiply NUMBER by seven."
3321   (interactive "p")
3322   (message "The result is %d" (* 7 number)))
3323 @end group
3324 @end smallexample
3326 @noindent
3327 You can install this code by placing your cursor after it and typing
3328 @kbd{C-x C-e}.  The name of the function will appear in your echo area.
3329 Then, you can use this code by typing @kbd{C-u} and a number and then
3330 typing @kbd{M-x multiply-by-seven} and pressing @key{RET}.  The phrase
3331 @samp{The result is @dots{}} followed by the product will appear in the
3332 echo area.
3334 Speaking more generally, you invoke a function like this in either of two
3335 ways:
3337 @enumerate
3338 @item
3339 By typing a prefix argument that contains the number to be passed, and
3340 then typing @kbd{M-x} and the name of the function, as with
3341 @kbd{C-u 3 M-x forward-sentence}; or,
3343 @item
3344 By typing whatever key or keychord the function is bound to, as with
3345 @kbd{C-u 3 M-e}.
3346 @end enumerate
3348 @noindent
3349 Both the examples just mentioned work identically to move point forward
3350 three sentences.  (Since @code{multiply-by-seven} is not bound to a key,
3351 it could not be used as an example of key binding.)
3353 (@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3354 to a key.)
3356 A @dfn{prefix argument} is passed to an interactive function by typing the
3357 @key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3358 typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3359 type @kbd{C-u} without a number, it defaults to 4).
3361 @node multiply-by-seven in detail
3362 @subsection An Interactive @code{multiply-by-seven}
3364 Let's look at the use of the special form @code{interactive} and then at
3365 the function @code{message} in the interactive version of
3366 @code{multiply-by-seven}.  You will recall that the function definition
3367 looks like this:
3369 @smallexample
3370 @group
3371 (defun multiply-by-seven (number)       ; @r{Interactive version.}
3372   "Multiply NUMBER by seven."
3373   (interactive "p")
3374   (message "The result is %d" (* 7 number)))
3375 @end group
3376 @end smallexample
3378 In this function, the expression, @code{(interactive "p")}, is a list of
3379 two elements.  The @code{"p"} tells Emacs to pass the prefix argument to
3380 the function and use its value for the argument of the function.
3382 @need 1000
3383 The argument will be a number.  This means that the symbol
3384 @code{number} will be bound to a number in the line:
3386 @smallexample
3387 (message "The result is %d" (* 7 number))
3388 @end smallexample
3390 @need 1250
3391 @noindent
3392 For example, if your prefix argument is 5, the Lisp interpreter will
3393 evaluate the line as if it were:
3395 @smallexample
3396 (message "The result is %d" (* 7 5))
3397 @end smallexample
3399 @noindent
3400 (If you are reading this in GNU Emacs, you can evaluate this expression
3401 yourself.)  First, the interpreter will evaluate the inner list, which
3402 is @code{(* 7 5)}.  This returns a value of 35.  Next, it
3403 will evaluate the outer list, passing the values of the second and
3404 subsequent elements of the list to the function @code{message}.
3406 As we have seen, @code{message} is an Emacs Lisp function especially
3407 designed for sending a one line message to a user.  (@xref{message, ,
3408 The @code{message} function}.)  In summary, the @code{message}
3409 function prints its first argument in the echo area as is, except for
3410 occurrences of @samp{%d} or @samp{%s} (and various other %-sequences
3411 which we have not mentioned).  When it sees a control sequence, the
3412 function looks to the second or subsequent arguments and prints the
3413 value of the argument in the location in the string where the control
3414 sequence is located.
3416 In the interactive @code{multiply-by-seven} function, the control string
3417 is @samp{%d}, which requires a number, and the value returned by
3418 evaluating @code{(* 7 5)} is the number 35.  Consequently, the number 35
3419 is printed in place of the @samp{%d} and the message is @samp{The result
3420 is 35}.
3422 (Note that when you call the function @code{multiply-by-seven}, the
3423 message is printed without quotes, but when you call @code{message}, the
3424 text is printed in double quotes.  This is because the value returned by
3425 @code{message} is what appears in the echo area when you evaluate an
3426 expression whose first element is @code{message}; but when embedded in a
3427 function, @code{message} prints the text as a side effect without
3428 quotes.)
3430 @node Interactive Options
3431 @section Different Options for @code{interactive}
3432 @cindex Options for @code{interactive}
3433 @cindex Interactive options
3435 In the example, @code{multiply-by-seven} used @code{"p"} as the
3436 argument to @code{interactive}.  This argument told Emacs to interpret
3437 your typing either @kbd{C-u} followed by a number or @key{META}
3438 followed by a number as a command to pass that number to the function
3439 as its argument.  Emacs has more than twenty characters predefined for
3440 use with @code{interactive}.  In almost every case, one of these
3441 options will enable you to pass the right information interactively to
3442 a function.  (@xref{Interactive Codes, , Code Characters for
3443 @code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3445 @need 1250
3446 Consider the function @code{zap-to-char}.  Its interactive expression
3449 @c FIXME: the interactive expression of zap-to-char has been changed
3450 @c (in 2012-04-10).
3452 @smallexample
3453 (interactive "p\ncZap to char: ")
3454 @end smallexample
3456 The first part of the argument to @code{interactive} is @samp{p}, with
3457 which you are already familiar.  This argument tells Emacs to
3458 interpret a prefix, as a number to be passed to the function.  You
3459 can specify a prefix either by typing @kbd{C-u} followed by a number
3460 or by typing @key{META} followed by a number.  The prefix is the
3461 number of specified characters.  Thus, if your prefix is three and the
3462 specified character is @samp{x}, then you will delete all the text up
3463 to and including the third next @samp{x}.  If you do not set a prefix,
3464 then you delete all the text up to and including the specified
3465 character, but no more.
3467 The @samp{c} tells the function the name of the character to which to delete.
3469 More formally, a function with two or more arguments can have
3470 information passed to each argument by adding parts to the string that
3471 follows @code{interactive}.  When you do this, the information is
3472 passed to each argument in the same order it is specified in the
3473 @code{interactive} list.  In the string, each part is separated from
3474 the next part by a @samp{\n}, which is a newline.  For example, you
3475 can follow @samp{p} with a @samp{\n} and an @samp{cZap to char:@: }.
3476 This causes Emacs to pass the value of the prefix argument (if there
3477 is one) and the character.
3479 In this case, the function definition looks like the following, where
3480 @code{arg} and @code{char} are the symbols to which @code{interactive}
3481 binds the prefix argument and the specified character:
3483 @smallexample
3484 @group
3485 (defun @var{name-of-function} (arg char)
3486   "@var{documentation}@dots{}"
3487   (interactive "p\ncZap to char: ")
3488   @var{body-of-function}@dots{})
3489 @end group
3490 @end smallexample
3492 @noindent
3493 (The space after the colon in the prompt makes it look better when you
3494 are prompted.  @xref{copy-to-buffer, , The Definition of
3495 @code{copy-to-buffer}}, for an example.)
3497 When a function does not take arguments, @code{interactive} does not
3498 require any.  Such a function contains the simple expression
3499 @code{(interactive)}.  The @code{mark-whole-buffer} function is like
3500 this.
3502 Alternatively, if the special letter-codes are not right for your
3503 application, you can pass your own arguments to @code{interactive} as
3504 a list.
3506 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}},
3507 for an example.  @xref{Using Interactive, , Using @code{Interactive},
3508 elisp, The GNU Emacs Lisp Reference Manual}, for a more complete
3509 explanation about this technique.
3511 @node Permanent Installation
3512 @section Install Code Permanently
3513 @cindex Install code permanently
3514 @cindex Permanent code installation
3515 @cindex Code installation
3517 When you install a function definition by evaluating it, it will stay
3518 installed until you quit Emacs.  The next time you start a new session
3519 of Emacs, the function will not be installed unless you evaluate the
3520 function definition again.
3522 At some point, you may want to have code installed automatically
3523 whenever you start a new session of Emacs.  There are several ways of
3524 doing this:
3526 @itemize @bullet
3527 @item
3528 If you have code that is just for yourself, you can put the code for the
3529 function definition in your @file{.emacs} initialization file.  When you
3530 start Emacs, your @file{.emacs} file is automatically evaluated and all
3531 the function definitions within it are installed.
3532 @xref{Emacs Initialization, , Your @file{.emacs} File}.
3534 @item
3535 Alternatively, you can put the function definitions that you want
3536 installed in one or more files of their own and use the @code{load}
3537 function to cause Emacs to evaluate and thereby install each of the
3538 functions in the files.
3539 @xref{Loading Files, , Loading Files}.
3541 @item
3542 Thirdly, if you have code that your whole site will use, it is usual
3543 to put it in a file called @file{site-init.el} that is loaded when
3544 Emacs is built.  This makes the code available to everyone who uses
3545 your machine.  (See the @file{INSTALL} file that is part of the Emacs
3546 distribution.)
3547 @end itemize
3549 Finally, if you have code that everyone who uses Emacs may want, you
3550 can post it on a computer network or send a copy to the Free Software
3551 Foundation.  (When you do this, please license the code and its
3552 documentation under a license that permits other people to run, copy,
3553 study, modify, and redistribute the code and which protects you from
3554 having your work taken from you.)  If you send a copy of your code to
3555 the Free Software Foundation, and properly protect yourself and
3556 others, it may be included in the next release of Emacs.  In large
3557 part, this is how Emacs has grown over the past years, by donations.
3559 @node let
3560 @section @code{let}
3561 @findex let
3563 The @code{let} expression is a special form in Lisp that you will need
3564 to use in most function definitions.
3566 @code{let} is used to attach or bind a symbol to a value in such a way
3567 that the Lisp interpreter will not confuse the variable with a
3568 variable of the same name that is not part of the function.
3570 To understand why the @code{let} special form is necessary, consider
3571 the situation in which you own a home that you generally refer to as
3572 ``the house'', as in the sentence, ``The house needs painting.''  If you
3573 are visiting a friend and your host refers to ``the house'', he is
3574 likely to be referring to @emph{his} house, not yours, that is, to a
3575 different house.
3577 If your friend is referring to his house and you think he is referring
3578 to your house, you may be in for some confusion.  The same thing could
3579 happen in Lisp if a variable that is used inside of one function has
3580 the same name as a variable that is used inside of another function,
3581 and the two are not intended to refer to the same value.  The
3582 @code{let} special form prevents this kind of confusion.
3584 @menu
3585 * Prevent confusion::
3586 * Parts of let Expression::
3587 * Sample let Expression::
3588 * Uninitialized let Variables::
3589 @end menu
3591 @ifnottex
3592 @node Prevent confusion
3593 @unnumberedsubsec @code{let} Prevents Confusion
3594 @end ifnottex
3596 @cindex @samp{local variable} defined
3597 @cindex @samp{variable, local}, defined
3598 The @code{let} special form prevents confusion.  @code{let} creates a
3599 name for a @dfn{local variable} that overshadows any use of the same
3600 name outside the @code{let} expression.  This is like understanding
3601 that whenever your host refers to ``the house'', he means his house, not
3602 yours.  (Symbols used in argument lists work the same way.
3603 @xref{defun, , The @code{defun} Macro}.)
3605 Local variables created by a @code{let} expression retain their value
3606 @emph{only} within the @code{let} expression itself (and within
3607 expressions called within the @code{let} expression); the local
3608 variables have no effect outside the @code{let} expression.
3610 Another way to think about @code{let} is that it is like a @code{setq}
3611 that is temporary and local.  The values set by @code{let} are
3612 automatically undone when the @code{let} is finished.  The setting
3613 only affects expressions that are inside the bounds of the @code{let}
3614 expression.  In computer science jargon, we would say the binding of
3615 a symbol is visible only in functions called in the @code{let} form;
3616 in Emacs Lisp, scoping is dynamic, not lexical.
3618 @code{let} can create more than one variable at once.  Also,
3619 @code{let} gives each variable it creates an initial value, either a
3620 value specified by you, or @code{nil}.  (In the jargon, this is
3621 binding the variable to the value.)  After @code{let} has created
3622 and bound the variables, it executes the code in the body of the
3623 @code{let}, and returns the value of the last expression in the body,
3624 as the value of the whole @code{let} expression.  (``Execute'' is a jargon
3625 term that means to evaluate a list; it comes from the use of the word
3626 meaning ``to give practical effect to'' (@cite{Oxford English
3627 Dictionary}).  Since you evaluate an expression to perform an action,
3628 ``execute'' has evolved as a synonym to ``evaluate''.)
3630 @node Parts of let Expression
3631 @subsection The Parts of a @code{let} Expression
3632 @cindex @code{let} expression, parts of
3633 @cindex Parts of @code{let} expression
3635 @cindex @samp{varlist} defined
3636 A @code{let} expression is a list of three parts.  The first part is
3637 the symbol @code{let}.  The second part is a list, called a
3638 @dfn{varlist}, each element of which is either a symbol by itself or a
3639 two-element list, the first element of which is a symbol.  The third
3640 part of the @code{let} expression is the body of the @code{let}.  The
3641 body usually consists of one or more lists.
3643 @need 800
3644 A template for a @code{let} expression looks like this:
3646 @smallexample
3647 (let @var{varlist} @var{body}@dots{})
3648 @end smallexample
3650 @noindent
3651 The symbols in the varlist are the variables that are given initial
3652 values by the @code{let} special form.  Symbols by themselves are given
3653 the initial value of @code{nil}; and each symbol that is the first
3654 element of a two-element list is bound to the value that is returned
3655 when the Lisp interpreter evaluates the second element.
3657 Thus, a varlist might look like this: @code{(thread (needles 3))}.  In
3658 this case, in a @code{let} expression, Emacs binds the symbol
3659 @code{thread} to an initial value of @code{nil}, and binds the symbol
3660 @code{needles} to an initial value of 3.
3662 When you write a @code{let} expression, what you do is put the
3663 appropriate expressions in the slots of the @code{let} expression
3664 template.
3666 If the varlist is composed of two-element lists, as is often the case,
3667 the template for the @code{let} expression looks like this:
3669 @smallexample
3670 @group
3671 (let ((@var{variable} @var{value})
3672       (@var{variable} @var{value})
3673       @dots{})
3674   @var{body}@dots{})
3675 @end group
3676 @end smallexample
3678 @node Sample let Expression
3679 @subsection Sample @code{let} Expression
3680 @cindex Sample @code{let} expression
3681 @cindex @code{let} expression sample
3683 The following expression creates and gives initial values
3684 to the two variables @code{zebra} and @code{tiger}.  The body of the
3685 @code{let} expression is a list which calls the @code{message} function.
3687 @smallexample
3688 @group
3689 (let ((zebra "stripes")
3690       (tiger "fierce"))
3691   (message "One kind of animal has %s and another is %s."
3692            zebra tiger))
3693 @end group
3694 @end smallexample
3696 Here, the varlist is @code{((zebra "stripes") (tiger "fierce"))}.
3698 The two variables are @code{zebra} and @code{tiger}.  Each variable is
3699 the first element of a two-element list and each value is the second
3700 element of its two-element list.  In the varlist, Emacs binds the
3701 variable @code{zebra} to the value @code{"stripes"}@footnote{According
3702 to Jared Diamond in @cite{Guns, Germs, and Steel}, ``@dots{} zebras
3703 become impossibly dangerous as they grow older'' but the claim here is
3704 that they do not become fierce like a tiger.  (1997, W. W. Norton and
3705 Co., ISBN 0-393-03894-2, page 171)}, and binds the
3706 variable @code{tiger} to the value @code{"fierce"}.  In this example,
3707 both values are strings.  The values could just as well have been
3708 another list or a symbol.  The body of the @code{let}
3709 follows after the list holding the variables.  In this example, the
3710 body is a list that uses the @code{message} function to print a string
3711 in the echo area.
3713 @need 1500
3714 You may evaluate the example in the usual fashion, by placing the
3715 cursor after the last parenthesis and typing @kbd{C-x C-e}.  When you do
3716 this, the following will appear in the echo area:
3718 @smallexample
3719 "One kind of animal has stripes and another is fierce."
3720 @end smallexample
3722 As we have seen before, the @code{message} function prints its first
3723 argument, except for @samp{%s}.  In this example, the value of the variable
3724 @code{zebra} is printed at the location of the first @samp{%s} and the
3725 value of the variable @code{tiger} is printed at the location of the
3726 second @samp{%s}.
3728 @node Uninitialized let Variables
3729 @subsection Uninitialized Variables in a @code{let} Statement
3730 @cindex Uninitialized @code{let} variables
3731 @cindex @code{let} variables uninitialized
3733 If you do not bind the variables in a @code{let} statement to specific
3734 initial values, they will automatically be bound to an initial value of
3735 @code{nil}, as in the following expression:
3737 @smallexample
3738 @group
3739 (let ((birch 3)
3740       pine
3741       fir
3742       (oak 'some))
3743   (message
3744    "Here are %d variables with %s, %s, and %s value."
3745    birch pine fir oak))
3746 @end group
3747 @end smallexample
3749 @noindent
3750 Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3752 @need 1250
3753 If you evaluate this expression in the usual way, the following will
3754 appear in your echo area:
3756 @smallexample
3757 "Here are 3 variables with nil, nil, and some value."
3758 @end smallexample
3760 @noindent
3761 In this example, Emacs binds the symbol @code{birch} to the number 3,
3762 binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3763 the symbol @code{oak} to the value @code{some}.
3765 Note that in the first part of the @code{let}, the variables @code{pine}
3766 and @code{fir} stand alone as atoms that are not surrounded by
3767 parentheses; this is because they are being bound to @code{nil}, the
3768 empty list.  But @code{oak} is bound to @code{some} and so is a part of
3769 the list @code{(oak 'some)}.  Similarly, @code{birch} is bound to the
3770 number 3 and so is in a list with that number.  (Since a number
3771 evaluates to itself, the number does not need to be quoted.  Also, the
3772 number is printed in the message using a @samp{%d} rather than a
3773 @samp{%s}.)  The four variables as a group are put into a list to
3774 delimit them from the body of the @code{let}.
3776 @node if
3777 @section The @code{if} Special Form
3778 @findex if
3779 @cindex Conditional with @code{if}
3781 A third special form, in addition to @code{defun} and @code{let}, is the
3782 conditional @code{if}.  This form is used to instruct the computer to
3783 make decisions.  You can write function definitions without using
3784 @code{if}, but it is used often enough, and is important enough, to be
3785 included here.  It is used, for example, in the code for the
3786 function @code{beginning-of-buffer}.
3788 The basic idea behind an @code{if}, is that @emph{if} a test is true,
3789 @emph{then} an expression is evaluated.  If the test is not true, the
3790 expression is not evaluated.  For example, you might make a decision
3791 such as, ``if it is warm and sunny, then go to the beach!''
3793 @menu
3794 * if in more detail::
3795 * type-of-animal in detail::    An example of an @code{if} expression.
3796 @end menu
3798 @ifnottex
3799 @node if in more detail
3800 @unnumberedsubsec @code{if} in more detail
3801 @end ifnottex
3803 @cindex @samp{if-part} defined
3804 @cindex @samp{then-part} defined
3805 An @code{if} expression written in Lisp does not use the word ``then'';
3806 the test and the action are the second and third elements of the list
3807 whose first element is @code{if}.  Nonetheless, the test part of an
3808 @code{if} expression is often called the @dfn{if-part} and the second
3809 argument is often called the @dfn{then-part}.
3811 Also, when an @code{if} expression is written, the true-or-false-test
3812 is usually written on the same line as the symbol @code{if}, but the
3813 action to carry out if the test is true, the then-part, is written
3814 on the second and subsequent lines.  This makes the @code{if}
3815 expression easier to read.
3817 @smallexample
3818 @group
3819 (if @var{true-or-false-test}
3820     @var{action-to-carry-out-if-test-is-true})
3821 @end group
3822 @end smallexample
3824 @noindent
3825 The true-or-false-test will be an expression that
3826 is evaluated by the Lisp interpreter.
3828 Here is an example that you can evaluate in the usual manner.  The test
3829 is whether the number 5 is greater than the number 4.  Since it is, the
3830 message @samp{5 is greater than 4!} will be printed.
3832 @smallexample
3833 @group
3834 (if (> 5 4)                             ; @r{if-part}
3835     (message "5 is greater than 4!"))   ; @r{then-part}
3836 @end group
3837 @end smallexample
3839 @noindent
3840 (The function @code{>} tests whether its first argument is greater than
3841 its second argument and returns true if it is.)
3842 @findex > (greater than)
3844 Of course, in actual use, the test in an @code{if} expression will not
3845 be fixed for all time as it is by the expression @code{(> 5 4)}.
3846 Instead, at least one of the variables used in the test will be bound to
3847 a value that is not known ahead of time.  (If the value were known ahead
3848 of time, we would not need to run the test!)
3850 For example, the value may be bound to an argument of a function
3851 definition.  In the following function definition, the character of the
3852 animal is a value that is passed to the function.  If the value bound to
3853 @code{characteristic} is @code{"fierce"}, then the message, @samp{It is a
3854 tiger!} will be printed; otherwise, @code{nil} will be returned.
3856 @smallexample
3857 @group
3858 (defun type-of-animal (characteristic)
3859   "Print message in echo area depending on CHARACTERISTIC.
3860 If the CHARACTERISTIC is the string \"fierce\",
3861 then warn of a tiger."
3862   (if (equal characteristic "fierce")
3863       (message "It is a tiger!")))
3864 @end group
3865 @end smallexample
3867 @need 1500
3868 @noindent
3869 If you are reading this inside of GNU Emacs, you can evaluate the
3870 function definition in the usual way to install it in Emacs, and then you
3871 can evaluate the following two expressions to see the results:
3873 @smallexample
3874 @group
3875 (type-of-animal "fierce")
3877 (type-of-animal "striped")
3879 @end group
3880 @end smallexample
3882 @c Following sentences rewritten to prevent overfull hbox.
3883 @noindent
3884 When you evaluate @code{(type-of-animal "fierce")}, you will see the
3885 following message printed in the echo area: @code{"It is a tiger!"}; and
3886 when you evaluate @code{(type-of-animal "striped")} you will see @code{nil}
3887 printed in the echo area.
3889 @node type-of-animal in detail
3890 @subsection The @code{type-of-animal} Function in Detail
3892 Let's look at the @code{type-of-animal} function in detail.
3894 The function definition for @code{type-of-animal} was written by filling
3895 the slots of two templates, one for a function definition as a whole, and
3896 a second for an @code{if} expression.
3898 @need 1250
3899 The template for every function that is not interactive is:
3901 @smallexample
3902 @group
3903 (defun @var{name-of-function} (@var{argument-list})
3904   "@var{documentation}@dots{}"
3905   @var{body}@dots{})
3906 @end group
3907 @end smallexample
3909 @need 800
3910 The parts of the function that match this template look like this:
3912 @smallexample
3913 @group
3914 (defun type-of-animal (characteristic)
3915   "Print message in echo area depending on CHARACTERISTIC.
3916 If the CHARACTERISTIC is the string \"fierce\",
3917 then warn of a tiger."
3918   @var{body: the} @code{if} @var{expression})
3919 @end group
3920 @end smallexample
3922 The name of function is @code{type-of-animal}; it is passed the value
3923 of one argument.  The argument list is followed by a multi-line
3924 documentation string.  The documentation string is included in the
3925 example because it is a good habit to write documentation string for
3926 every function definition.  The body of the function definition
3927 consists of the @code{if} expression.
3929 @need 800
3930 The template for an @code{if} expression looks like this:
3932 @smallexample
3933 @group
3934 (if @var{true-or-false-test}
3935     @var{action-to-carry-out-if-the-test-returns-true})
3936 @end group
3937 @end smallexample
3939 @need 1250
3940 In the @code{type-of-animal} function, the code for the @code{if}
3941 looks like this:
3943 @smallexample
3944 @group
3945 (if (equal characteristic "fierce")
3946     (message "It is a tiger!")))
3947 @end group
3948 @end smallexample
3950 @need 800
3951 Here, the true-or-false-test is the expression:
3953 @smallexample
3954 (equal characteristic "fierce")
3955 @end smallexample
3957 @noindent
3958 In Lisp, @code{equal} is a function that determines whether its first
3959 argument is equal to its second argument.  The second argument is the
3960 string @code{"fierce"} and the first argument is the value of the
3961 symbol @code{characteristic}---in other words, the argument passed to
3962 this function.
3964 In the first exercise of @code{type-of-animal}, the argument
3965 @code{"fierce"} is passed to @code{type-of-animal}.  Since @code{"fierce"}
3966 is equal to @code{"fierce"}, the expression, @code{(equal characteristic
3967 "fierce")}, returns a value of true.  When this happens, the @code{if}
3968 evaluates the second argument or then-part of the @code{if}:
3969 @code{(message "It is a tiger!")}.
3971 On the other hand, in the second exercise of @code{type-of-animal}, the
3972 argument @code{"striped"} is passed to @code{type-of-animal}.  @code{"striped"}
3973 is not equal to @code{"fierce"}, so the then-part is not evaluated and
3974 @code{nil} is returned by the @code{if} expression.
3976 @node else
3977 @section If--then--else Expressions
3978 @cindex Else
3980 An @code{if} expression may have an optional third argument, called
3981 the @dfn{else-part}, for the case when the true-or-false-test returns
3982 false.  When this happens, the second argument or then-part of the
3983 overall @code{if} expression is @emph{not} evaluated, but the third or
3984 else-part @emph{is} evaluated.  You might think of this as the cloudy
3985 day alternative for the decision ``if it is warm and sunny, then go to
3986 the beach, else read a book!''.
3988 The word ``else'' is not written in the Lisp code; the else-part of an
3989 @code{if} expression comes after the then-part.  In the written Lisp, the
3990 else-part is usually written to start on a line of its own and is
3991 indented less than the then-part:
3993 @smallexample
3994 @group
3995 (if @var{true-or-false-test}
3996     @var{action-to-carry-out-if-the-test-returns-true}
3997   @var{action-to-carry-out-if-the-test-returns-false})
3998 @end group
3999 @end smallexample
4001 For example, the following @code{if} expression prints the message @samp{4
4002 is not greater than 5!} when you evaluate it in the usual way:
4004 @smallexample
4005 @group
4006 (if (> 4 5)                               ; @r{if-part}
4007     (message "4 falsely greater than 5!") ; @r{then-part}
4008   (message "4 is not greater than 5!"))   ; @r{else-part}
4009 @end group
4010 @end smallexample
4012 @noindent
4013 Note that the different levels of indentation make it easy to
4014 distinguish the then-part from the else-part.  (GNU Emacs has several
4015 commands that automatically indent @code{if} expressions correctly.
4016 @xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4018 We can extend the @code{type-of-animal} function to include an
4019 else-part by simply incorporating an additional part to the @code{if}
4020 expression.
4022 @need 1500
4023 You can see the consequences of doing this if you evaluate the following
4024 version of the @code{type-of-animal} function definition to install it
4025 and then evaluate the two subsequent expressions to pass different
4026 arguments to the function.
4028 @smallexample
4029 @group
4030 (defun type-of-animal (characteristic)  ; @r{Second version.}
4031   "Print message in echo area depending on CHARACTERISTIC.
4032 If the CHARACTERISTIC is the string \"fierce\",
4033 then warn of a tiger; else say it is not fierce."
4034   (if (equal characteristic "fierce")
4035       (message "It is a tiger!")
4036     (message "It is not fierce!")))
4037 @end group
4038 @end smallexample
4039 @sp 1
4041 @smallexample
4042 @group
4043 (type-of-animal "fierce")
4045 (type-of-animal "striped")
4047 @end group
4048 @end smallexample
4050 @c Following sentence rewritten to prevent overfull hbox.
4051 @noindent
4052 When you evaluate @code{(type-of-animal "fierce")}, you will see the
4053 following message printed in the echo area: @code{"It is a tiger!"}; but
4054 when you evaluate @code{(type-of-animal "striped")}, you will see
4055 @code{"It is not fierce!"}.
4057 (Of course, if the @var{characteristic} were @code{"ferocious"}, the
4058 message @code{"It is not fierce!"} would be printed; and it would be
4059 misleading!  When you write code, you need to take into account the
4060 possibility that some such argument will be tested by the @code{if}
4061 and write your program accordingly.)
4063 @node Truth & Falsehood
4064 @section Truth and Falsehood in Emacs Lisp
4065 @cindex Truth and falsehood in Emacs Lisp
4066 @cindex Falsehood and truth in Emacs Lisp
4067 @findex nil
4069 There is an important aspect to the truth test in an @code{if}
4070 expression.  So far, we have spoken of ``true'' and ``false'' as values of
4071 predicates as if they were new kinds of Emacs Lisp objects.  In fact,
4072 ``false'' is just our old friend @code{nil}.  Anything else---anything
4073 at all---is ``true''.
4075 The expression that tests for truth is interpreted as @dfn{true}
4076 if the result of evaluating it is a value that is not @code{nil}.  In
4077 other words, the result of the test is considered true if the value
4078 returned is a number such as 47, a string such as @code{"hello"}, or a
4079 symbol (other than @code{nil}) such as @code{flowers}, or a list (so
4080 long as it is not empty), or even a buffer!
4082 @menu
4083 * nil explained::               @code{nil} has two meanings.
4084 @end menu
4086 @ifnottex
4087 @node nil explained
4088 @unnumberedsubsec An explanation of @code{nil}
4089 @end ifnottex
4091 Before illustrating a test for truth, we need an explanation of @code{nil}.
4093 In Emacs Lisp, the symbol @code{nil} has two meanings.  First, it means the
4094 empty list.  Second, it means false and is the value returned when a
4095 true-or-false-test tests false.  @code{nil} can be written as an empty
4096 list, @code{()}, or as @code{nil}.  As far as the Lisp interpreter is
4097 concerned, @code{()} and @code{nil} are the same.  Humans, however, tend
4098 to use @code{nil} for false and @code{()} for the empty list.
4100 In Emacs Lisp, any value that is not @code{nil}---is not the empty
4101 list---is considered true.  This means that if an evaluation returns
4102 something that is not an empty list, an @code{if} expression will test
4103 true.  For example, if a number is put in the slot for the test, it
4104 will be evaluated and will return itself, since that is what numbers
4105 do when evaluated.  In this conditional, the @code{if} expression will
4106 test true.  The expression tests false only when @code{nil}, an empty
4107 list, is returned by evaluating the expression.
4109 You can see this by evaluating the two expressions in the following examples.
4111 In the first example, the number 4 is evaluated as the test in the
4112 @code{if} expression and returns itself; consequently, the then-part
4113 of the expression is evaluated and returned: @samp{true} appears in
4114 the echo area.  In the second example, the @code{nil} indicates false;
4115 consequently, the else-part of the expression is evaluated and
4116 returned: @samp{false} appears in the echo area.
4118 @smallexample
4119 @group
4120 (if 4
4121     'true
4122   'false)
4123 @end group
4125 @group
4126 (if nil
4127     'true
4128   'false)
4129 @end group
4130 @end smallexample
4132 @need 1250
4133 Incidentally, if some other useful value is not available for a test that
4134 returns true, then the Lisp interpreter will return the symbol @code{t}
4135 for true.  For example, the expression @code{(> 5 4)} returns @code{t}
4136 when evaluated, as you can see by evaluating it in the usual way:
4138 @smallexample
4139 (> 5 4)
4140 @end smallexample
4142 @need 1250
4143 @noindent
4144 On the other hand, this function returns @code{nil} if the test is false.
4146 @smallexample
4147 (> 4 5)
4148 @end smallexample
4150 @node save-excursion
4151 @section @code{save-excursion}
4152 @findex save-excursion
4153 @cindex Region, what it is
4154 @cindex Preserving point and buffer
4155 @cindex Point and buffer preservation
4156 @findex point
4157 @findex mark
4159 The @code{save-excursion} function is the third and final special form
4160 that we will discuss in this chapter.
4162 In Emacs Lisp programs used for editing, the @code{save-excursion}
4163 function is very common.  It saves the location of point,
4164 executes the body of the function, and then restores point to
4165 its previous position if its location was changed.  Its primary
4166 purpose is to keep the user from being surprised and disturbed by
4167 unexpected movement of point.
4169 @menu
4170 * Point and mark::              A review of various locations.
4171 * Template for save-excursion::
4172 @end menu
4174 @ifnottex
4175 @node Point and mark
4176 @unnumberedsubsec Point and Mark
4177 @end ifnottex
4179 Before discussing @code{save-excursion}, however, it may be useful
4180 first to review what point and mark are in GNU Emacs.  @dfn{Point} is
4181 the current location of the cursor.  Wherever the cursor
4182 is, that is point.  More precisely, on terminals where the cursor
4183 appears to be on top of a character, point is immediately before the
4184 character.  In Emacs Lisp, point is an integer.  The first character in
4185 a buffer is number one, the second is number two, and so on.  The
4186 function @code{point} returns the current position of the cursor as a
4187 number.  Each buffer has its own value for point.
4189 The @dfn{mark} is another position in the buffer; its value can be set
4190 with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}).  If
4191 a mark has been set, you can use the command @kbd{C-x C-x}
4192 (@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4193 and set the mark to be the previous position of point.  In addition, if
4194 you set another mark, the position of the previous mark is saved in the
4195 mark ring.  Many mark positions can be saved this way.  You can jump the
4196 cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4197 times.
4199 The part of the buffer between point and mark is called @dfn{the
4200 region}.  Numerous commands work on the region, including
4201 @code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4202 @code{print-region}.
4204 The @code{save-excursion} special form saves the location of point and
4205 restores this position after the code within the body of the
4206 special form is evaluated by the Lisp interpreter.  Thus, if point were
4207 in the beginning of a piece of text and some code moved point to the end
4208 of the buffer, the @code{save-excursion} would put point back to where
4209 it was before, after the expressions in the body of the function were
4210 evaluated.
4212 In Emacs, a function frequently moves point as part of its internal
4213 workings even though a user would not expect this.  For example,
4214 @code{count-lines-region} moves point.  To prevent the user from being
4215 bothered by jumps that are both unexpected and (from the user's point of
4216 view) unnecessary, @code{save-excursion} is often used to keep point in
4217 the location expected by the user.  The use of
4218 @code{save-excursion} is good housekeeping.
4220 To make sure the house stays clean, @code{save-excursion} restores the
4221 value of point even if something goes wrong in the code inside
4222 of it (or, to be more precise and to use the proper jargon, ``in case of
4223 abnormal exit'').  This feature is very helpful.
4225 In addition to recording the value of point,
4226 @code{save-excursion} keeps track of the current buffer, and restores
4227 it, too.  This means you can write code that will change the buffer and
4228 have @code{save-excursion} switch you back to the original buffer.
4229 This is how @code{save-excursion} is used in @code{append-to-buffer}.
4230 (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4232 @node Template for save-excursion
4233 @subsection Template for a @code{save-excursion} Expression
4235 @need 800
4236 The template for code using @code{save-excursion} is simple:
4238 @smallexample
4239 @group
4240 (save-excursion
4241   @var{body}@dots{})
4242 @end group
4243 @end smallexample
4245 @noindent
4246 The body of the function is one or more expressions that will be
4247 evaluated in sequence by the Lisp interpreter.  If there is more than
4248 one expression in the body, the value of the last one will be returned
4249 as the value of the @code{save-excursion} function.  The other
4250 expressions in the body are evaluated only for their side effects; and
4251 @code{save-excursion} itself is used only for its side effect (which
4252 is restoring the position of point).
4254 @need 1250
4255 In more detail, the template for a @code{save-excursion} expression
4256 looks like this:
4258 @smallexample
4259 @group
4260 (save-excursion
4261   @var{first-expression-in-body}
4262   @var{second-expression-in-body}
4263   @var{third-expression-in-body}
4264    @dots{}
4265   @var{last-expression-in-body})
4266 @end group
4267 @end smallexample
4269 @noindent
4270 An expression, of course, may be a symbol on its own or a list.
4272 In Emacs Lisp code, a @code{save-excursion} expression often occurs
4273 within the body of a @code{let} expression.  It looks like this:
4275 @smallexample
4276 @group
4277 (let @var{varlist}
4278   (save-excursion
4279     @var{body}@dots{}))
4280 @end group
4281 @end smallexample
4283 @node Review
4284 @section Review
4286 In the last few chapters we have introduced a macro and a fair number
4287 of functions and special forms.  Here they are described in brief,
4288 along with a few similar functions that have not been mentioned yet.
4290 @table @code
4291 @item eval-last-sexp
4292 Evaluate the last symbolic expression before the current location of
4293 point.  The value is printed in the echo area unless the function is
4294 invoked with an argument; in that case, the output is printed in the
4295 current buffer.  This command is normally bound to @kbd{C-x C-e}.
4297 @item defun
4298 Define function.  This macro has up to five parts: the name, a
4299 template for the arguments that will be passed to the function,
4300 documentation, an optional interactive declaration, and the body of
4301 the definition.
4303 @need 1250
4304 For example, in Emacs the function definition of
4305 @code{dired-unmark-all-marks} is as follows.
4307 @smallexample
4308 @group
4309 (defun dired-unmark-all-marks ()
4310   "Remove all marks from all files in the Dired buffer."
4311   (interactive)
4312   (dired-unmark-all-files ?\r))
4313 @end group
4314 @end smallexample
4316 @item interactive
4317 Declare to the interpreter that the function can be used
4318 interactively.  This special form may be followed by a string with one
4319 or more parts that pass the information to the arguments of the
4320 function, in sequence.  These parts may also tell the interpreter to
4321 prompt for information.  Parts of the string are separated by
4322 newlines, @samp{\n}.
4324 @need 1000
4325 Common code characters are:
4327 @table @code
4328 @item b
4329 The name of an existing buffer.
4331 @item f
4332 The name of an existing file.
4334 @item p
4335 The numeric prefix argument.  (Note that this @code{p} is lower case.)
4337 @item r
4338 Point and the mark, as two numeric arguments, smallest first.  This
4339 is the only code letter that specifies two successive arguments
4340 rather than one.
4341 @end table
4343 @xref{Interactive Codes, , Code Characters for @samp{interactive},
4344 elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4345 code characters.
4347 @item let
4348 Declare that a list of variables is for use within the body of the
4349 @code{let} and give them an initial value, either @code{nil} or a
4350 specified value; then evaluate the rest of the expressions in the body
4351 of the @code{let} and return the value of the last one.  Inside the
4352 body of the @code{let}, the Lisp interpreter does not see the values of
4353 the variables of the same names that are bound outside of the
4354 @code{let}.
4356 @need 1250
4357 For example,
4359 @smallexample
4360 @group
4361 (let ((foo (buffer-name))
4362       (bar (buffer-size)))
4363   (message
4364    "This buffer is %s and has %d characters."
4365    foo bar))
4366 @end group
4367 @end smallexample
4369 @item save-excursion
4370 Record the values of point and the current buffer before
4371 evaluating the body of this special form.  Restore the value of point and
4372 buffer afterward.
4374 @need 1250
4375 For example,
4377 @smallexample
4378 @group
4379 (message "We are %d characters into this buffer."
4380          (- (point)
4381             (save-excursion
4382               (goto-char (point-min)) (point))))
4383 @end group
4384 @end smallexample
4386 @item if
4387 Evaluate the first argument to the function; if it is true, evaluate
4388 the second argument; else evaluate the third argument, if there is one.
4390 The @code{if} special form is called a @dfn{conditional}.  There are
4391 other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4392 commonly used.
4394 @need 1250
4395 For example,
4397 @smallexample
4398 @group
4399 (if (= 22 emacs-major-version)
4400     (message "This is version 22 Emacs")
4401   (message "This is not version 22 Emacs"))
4402 @end group
4403 @end smallexample
4405 @need 1250
4406 @item <
4407 @itemx >
4408 @itemx <=
4409 @itemx >=
4410 The @code{<} function tests whether its first argument is smaller than
4411 its second argument.  A corresponding function, @code{>}, tests whether
4412 the first argument is greater than the second.  Likewise, @code{<=}
4413 tests whether the first argument is less than or equal to the second and
4414 @code{>=} tests whether the first argument is greater than or equal to
4415 the second.  In all cases, both arguments must be numbers or markers
4416 (markers indicate positions in buffers).
4418 @need 800
4419 @item =
4420 The @code{=} function tests whether two arguments, both numbers or
4421 markers, are equal.
4423 @need 1250
4424 @item equal
4425 @itemx eq
4426 Test whether two objects are the same.  @code{equal} uses one meaning
4427 of the word ``same'' and @code{eq} uses another:  @code{equal} returns
4428 true if the two objects have a similar structure and contents, such as
4429 two copies of the same book.  On the other hand, @code{eq}, returns
4430 true if both arguments are actually the same object.
4431 @findex equal
4432 @findex eq
4434 @need 1250
4435 @item string<
4436 @itemx string-lessp
4437 @itemx string=
4438 @itemx string-equal
4439 The @code{string-lessp} function tests whether its first argument is
4440 smaller than the second argument.  A shorter, alternative name for the
4441 same function (a @code{defalias}) is @code{string<}.
4443 The arguments to @code{string-lessp} must be strings or symbols; the
4444 ordering is lexicographic, so case is significant.  The print names of
4445 symbols are used instead of the symbols themselves.
4447 @cindex @samp{empty string} defined
4448 An empty string, @samp{""}, a string with no characters in it, is
4449 smaller than any string of characters.
4451 @code{string-equal} provides the corresponding test for equality.  Its
4452 shorter, alternative name is @code{string=}.  There are no string test
4453 functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4455 @item message
4456 Print a message in the echo area.  The first argument is a string that
4457 can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4458 arguments that follow the string.  The argument used by @samp{%s} must
4459 be a string or a symbol; the argument used by @samp{%d} must be a
4460 number.  The argument used by @samp{%c} must be an @sc{ascii} code
4461 number; it will be printed as the character with that @sc{ascii} code.
4462 (Various other %-sequences have not been mentioned.)
4464 @item setq
4465 @itemx set
4466 The @code{setq} function sets the value of its first argument to the
4467 value of the second argument.  The first argument is automatically
4468 quoted by @code{setq}.  It does the same for succeeding pairs of
4469 arguments.  Another function, @code{set}, takes only two arguments and
4470 evaluates both of them before setting the value returned by its first
4471 argument to the value returned by its second argument.
4473 @item buffer-name
4474 Without an argument, return the name of the buffer, as a string.
4476 @item buffer-file-name
4477 Without an argument, return the name of the file the buffer is
4478 visiting.
4480 @item current-buffer
4481 Return the buffer in which Emacs is active; it may not be
4482 the buffer that is visible on the screen.
4484 @item other-buffer
4485 Return the most recently selected buffer (other than the buffer passed
4486 to @code{other-buffer} as an argument and other than the current
4487 buffer).
4489 @item switch-to-buffer
4490 Select a buffer for Emacs to be active in and display it in the current
4491 window so users can look at it.  Usually bound to @kbd{C-x b}.
4493 @item set-buffer
4494 Switch Emacs's attention to a buffer on which programs will run.  Don't
4495 alter what the window is showing.
4497 @item buffer-size
4498 Return the number of characters in the current buffer.
4500 @item point
4501 Return the value of the current position of the cursor, as an
4502 integer counting the number of characters from the beginning of the
4503 buffer.
4505 @item point-min
4506 Return the minimum permissible value of point in
4507 the current buffer.  This is 1, unless narrowing is in effect.
4509 @item point-max
4510 Return the value of the maximum permissible value of point in the
4511 current buffer.  This is the end of the buffer, unless narrowing is in
4512 effect.
4513 @end table
4515 @need 1500
4516 @node defun Exercises
4517 @section Exercises
4519 @itemize @bullet
4520 @item
4521 Write a non-interactive function that doubles the value of its
4522 argument, a number.  Make that function interactive.
4524 @item
4525 Write a function that tests whether the current value of
4526 @code{fill-column} is greater than the argument passed to the function,
4527 and if so, prints an appropriate message.
4528 @end itemize
4530 @node Buffer Walk Through
4531 @chapter A Few Buffer-Related Functions
4533 In this chapter we study in detail several of the functions used in GNU
4534 Emacs.  This is called a ``walk-through''.  These functions are used as
4535 examples of Lisp code, but are not imaginary examples; with the
4536 exception of the first, simplified function definition, these functions
4537 show the actual code used in GNU Emacs.  You can learn a great deal from
4538 these definitions.  The functions described here are all related to
4539 buffers.  Later, we will study other functions.
4541 @menu
4542 * Finding More::                How to find more information.
4543 * simplified-beginning-of-buffer::  Shows @code{goto-char},
4544                                 @code{point-min}, and @code{push-mark}.
4545 * mark-whole-buffer::           Almost the same as @code{beginning-of-buffer}.
4546 * append-to-buffer::            Uses @code{save-excursion} and
4547                                 @code{insert-buffer-substring}.
4548 * Buffer Related Review::       Review.
4549 * Buffer Exercises::
4550 @end menu
4552 @node Finding More
4553 @section Finding More Information
4555 @findex describe-function, @r{introduced}
4556 @cindex Find function documentation
4557 In this walk-through, I will describe each new function as we come to
4558 it, sometimes in detail and sometimes briefly.  If you are interested,
4559 you can get the full documentation of any Emacs Lisp function at any
4560 time by typing @kbd{C-h f} and then the name of the function (and then
4561 @key{RET}).  Similarly, you can get the full documentation for a
4562 variable by typing @kbd{C-h v} and then the name of the variable (and
4563 then @key{RET}).
4565 @cindex Find source of function
4566 @c In version 22, tells location both of C and of Emacs Lisp
4567 Also, @code{describe-function} will tell you the location of the
4568 function definition.
4570 Put point into the name of the file that contains the function and
4571 press the @key{RET} key.  In this case, @key{RET} means
4572 @code{push-button} rather than ``return'' or ``enter''.  Emacs will take
4573 you directly to the function definition.
4575 @ignore
4576 Not In version 22
4578 If you move point over the file name and press
4579 the @key{RET} key, which in this case means @code{help-follow} rather
4580 than ``return'' or ``enter'', Emacs will take you directly to the function
4581 definition.
4582 @end ignore
4584 More generally, if you want to see a function in its original source
4585 file, you can use the @code{xref-find-definitions} function to jump to
4586 it.  @code{xref-find-definitions} works with a wide variety of
4587 languages, not just Lisp, and C, and it works with non-programming
4588 text as well.  For example, @code{xref-find-definitions} will jump to
4589 the various nodes in the Texinfo source file of this document.
4591 To use the @code{xref-find-definitions} command, type @kbd{M-.}
4592 (i.e., press the period key while holding down the @key{META} key, or
4593 else type the @key{ESC} key and then type the period key), and then,
4594 at the prompt, type in the name of the function whose source code you
4595 want to see, such as @code{mark-whole-buffer}, and then type
4596 @key{RET}.  Emacs will switch buffers and display the source code for
4597 the function on your screen.  To switch back to your current buffer,
4598 type @kbd{C-x b @key{RET}}.  (On some keyboards, the @key{META} key is
4599 labeled @key{ALT}.)
4601 @cindex Library, as term for ``file''
4602 Incidentally, the files that contain Lisp code are conventionally
4603 called @dfn{libraries}.  The metaphor is derived from that of a
4604 specialized library, such as a law library or an engineering library,
4605 rather than a general library.  Each library, or file, contains
4606 functions that relate to a particular topic or activity, such as
4607 @file{abbrev.el} for handling abbreviations and other typing
4608 shortcuts, and @file{help.el} for help.  (Sometimes several
4609 libraries provide code for a single activity, as the various
4610 @file{rmail@dots{}} files provide code for reading electronic mail.)
4611 In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4612 @kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4613 by topic keywords.''
4615 @node simplified-beginning-of-buffer
4616 @section A Simplified @code{beginning-of-buffer} Definition
4617 @findex simplified-beginning-of-buffer
4619 The @code{beginning-of-buffer} command is a good function to start with
4620 since you are likely to be familiar with it and it is easy to
4621 understand.  Used as an interactive command, @code{beginning-of-buffer}
4622 moves the cursor to the beginning of the buffer, leaving the mark at the
4623 previous position.  It is generally bound to @kbd{M-<}.
4625 In this section, we will discuss a shortened version of the function
4626 that shows how it is most frequently used.  This shortened function
4627 works as written, but it does not contain the code for a complex option.
4628 In another section, we will describe the entire function.
4629 (@xref{beginning-of-buffer, , Complete Definition of
4630 @code{beginning-of-buffer}}.)
4632 Before looking at the code, let's consider what the function
4633 definition has to contain: it must include an expression that makes
4634 the function interactive so it can be called by typing @kbd{M-x
4635 beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
4636 must include code to leave a mark at the original position in the
4637 buffer; and it must include code to move the cursor to the beginning
4638 of the buffer.
4640 @need 1250
4641 Here is the complete text of the shortened version of the function:
4643 @smallexample
4644 @group
4645 (defun simplified-beginning-of-buffer ()
4646   "Move point to the beginning of the buffer;
4647 leave mark at previous position."
4648   (interactive)
4649   (push-mark)
4650   (goto-char (point-min)))
4651 @end group
4652 @end smallexample
4654 Like all function definitions, this definition has five parts following
4655 the macro @code{defun}:
4657 @enumerate
4658 @item
4659 The name: in this example, @code{simplified-beginning-of-buffer}.
4661 @item
4662 A list of the arguments: in this example, an empty list, @code{()},
4664 @item
4665 The documentation string.
4667 @item
4668 The interactive expression.
4670 @item
4671 The body.
4672 @end enumerate
4674 @noindent
4675 In this function definition, the argument list is empty; this means that
4676 this function does not require any arguments.  (When we look at the
4677 definition for the complete function, we will see that it may be passed
4678 an optional argument.)
4680 The interactive expression tells Emacs that the function is intended to
4681 be used interactively.  In this example, @code{interactive} does not have
4682 an argument because @code{simplified-beginning-of-buffer} does not
4683 require one.
4685 @need 800
4686 The body of the function consists of the two lines:
4688 @smallexample
4689 @group
4690 (push-mark)
4691 (goto-char (point-min))
4692 @end group
4693 @end smallexample
4695 The first of these lines is the expression, @code{(push-mark)}.  When
4696 this expression is evaluated by the Lisp interpreter, it sets a mark at
4697 the current position of the cursor, wherever that may be.  The position
4698 of this mark is saved in the mark ring.
4700 The next line is @code{(goto-char (point-min))}.  This expression
4701 jumps the cursor to the minimum point in the buffer, that is, to the
4702 beginning of the buffer (or to the beginning of the accessible portion
4703 of the buffer if it is narrowed.  @xref{Narrowing & Widening, ,
4704 Narrowing and Widening}.)
4706 The @code{push-mark} command sets a mark at the place where the cursor
4707 was located before it was moved to the beginning of the buffer by the
4708 @code{(goto-char (point-min))} expression.  Consequently, you can, if
4709 you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4711 That is all there is to the function definition!
4713 @findex describe-function
4714 When you are reading code such as this and come upon an unfamiliar
4715 function, such as @code{goto-char}, you can find out what it does by
4716 using the @code{describe-function} command.  To use this command, type
4717 @kbd{C-h f} and then type in the name of the function and press
4718 @key{RET}.  The @code{describe-function} command will print the
4719 function's documentation string in a @file{*Help*} window.  For
4720 example, the documentation for @code{goto-char} is:
4722 @smallexample
4723 @group
4724 Set point to POSITION, a number or marker.
4725 Beginning of buffer is position (point-min), end is (point-max).
4726 @end group
4727 @end smallexample
4729 @noindent
4730 The function's one argument is the desired position.
4732 @noindent
4733 (The prompt for @code{describe-function} will offer you the symbol
4734 under or preceding the cursor, so you can save typing by positioning
4735 the cursor right over or after the function and then typing @kbd{C-h f
4736 @key{RET}}.)
4738 The @code{end-of-buffer} function definition is written in the same way as
4739 the @code{beginning-of-buffer} definition except that the body of the
4740 function contains the expression @code{(goto-char (point-max))} in place
4741 of @code{(goto-char (point-min))}.
4743 @node mark-whole-buffer
4744 @section The Definition of @code{mark-whole-buffer}
4745 @findex mark-whole-buffer
4747 The @code{mark-whole-buffer} function is no harder to understand than the
4748 @code{simplified-beginning-of-buffer} function.  In this case, however,
4749 we will look at the complete function, not a shortened version.
4751 The @code{mark-whole-buffer} function is not as commonly used as the
4752 @code{beginning-of-buffer} function, but is useful nonetheless: it
4753 marks a whole buffer as a region by putting point at the beginning and
4754 a mark at the end of the buffer.  It is generally bound to @kbd{C-x
4757 @menu
4758 * mark-whole-buffer overview::
4759 * Body of mark-whole-buffer::   Only three lines of code.
4760 @end menu
4762 @ifnottex
4763 @node mark-whole-buffer overview
4764 @unnumberedsubsec An overview of @code{mark-whole-buffer}
4765 @end ifnottex
4767 @need 1250
4768 In GNU Emacs 22, the code for the complete function looks like this:
4770 @smallexample
4771 @group
4772 (defun mark-whole-buffer ()
4773   "Put point at beginning and mark at end of buffer.
4774 You probably should not use this function in Lisp programs;
4775 it is usually a mistake for a Lisp function to use any subroutine
4776 that uses or sets the mark."
4777   (interactive)
4778   (push-mark (point))
4779   (push-mark (point-max) nil t)
4780   (goto-char (point-min)))
4781 @end group
4782 @end smallexample
4784 @need 1250
4785 Like all other functions, the @code{mark-whole-buffer} function fits
4786 into the template for a function definition.  The template looks like
4787 this:
4789 @smallexample
4790 @group
4791 (defun @var{name-of-function} (@var{argument-list})
4792   "@var{documentation}@dots{}"
4793   (@var{interactive-expression}@dots{})
4794   @var{body}@dots{})
4795 @end group
4796 @end smallexample
4798 Here is how the function works: the name of the function is
4799 @code{mark-whole-buffer}; it is followed by an empty argument list,
4800 @samp{()}, which means that the function does not require arguments.
4801 The documentation comes next.
4803 The next line is an @code{(interactive)} expression that tells Emacs
4804 that the function will be used interactively.  These details are similar
4805 to the @code{simplified-beginning-of-buffer} function described in the
4806 previous section.
4808 @need 1250
4809 @node Body of mark-whole-buffer
4810 @subsection Body of @code{mark-whole-buffer}
4812 The body of the @code{mark-whole-buffer} function consists of three
4813 lines of code:
4815 @c GNU Emacs 22
4816 @smallexample
4817 @group
4818 (push-mark (point))
4819 (push-mark (point-max) nil t)
4820 (goto-char (point-min))
4821 @end group
4822 @end smallexample
4824 The first of these lines is the expression, @code{(push-mark (point))}.
4826 This line does exactly the same job as the first line of the body of
4827 the @code{simplified-beginning-of-buffer} function, which is written
4828 @code{(push-mark)}.  In both cases, the Lisp interpreter sets a mark
4829 at the current position of the cursor.
4831 I don't know why the expression in @code{mark-whole-buffer} is written
4832 @code{(push-mark (point))} and the expression in
4833 @code{beginning-of-buffer} is written @code{(push-mark)}.  Perhaps
4834 whoever wrote the code did not know that the arguments for
4835 @code{push-mark} are optional and that if @code{push-mark} is not
4836 passed an argument, the function automatically sets mark at the
4837 location of point by default.  Or perhaps the expression was written
4838 so as to parallel the structure of the next line.  In any case, the
4839 line causes Emacs to determine the position of point and set a mark
4840 there.
4842 In earlier versions of GNU Emacs, the next line of
4843 @code{mark-whole-buffer} was @code{(push-mark (point-max))}.  This
4844 expression sets a mark at the point in the buffer that has the highest
4845 number.  This will be the end of the buffer (or, if the buffer is
4846 narrowed, the end of the accessible portion of the buffer.
4847 @xref{Narrowing & Widening, , Narrowing and Widening}, for more about
4848 narrowing.)  After this mark has been set, the previous mark, the one
4849 set at point, is no longer set, but Emacs remembers its position, just
4850 as all other recent marks are always remembered.  This means that you
4851 can, if you wish, go back to that position by typing @kbd{C-u
4852 C-@key{SPC}} twice.
4854 @need 1250
4855 In GNU Emacs 22, the @code{(point-max)} is slightly more complicated.
4856 The line reads
4858 @smallexample
4859 (push-mark (point-max) nil t)
4860 @end smallexample
4862 @noindent
4863 The expression works nearly the same as before.  It sets a mark at the
4864 highest numbered place in the buffer that it can.  However, in this
4865 version, @code{push-mark} has two additional arguments.  The second
4866 argument to @code{push-mark} is @code{nil}.  This tells the function
4867 it @emph{should} display a message that says ``Mark set'' when it pushes
4868 the mark.  The third argument is @code{t}.  This tells
4869 @code{push-mark} to activate the mark when Transient Mark mode is
4870 turned on.  Transient Mark mode highlights the currently active
4871 region.  It is often turned off.
4873 Finally, the last line of the function is @code{(goto-char
4874 (point-min)))}.  This is written exactly the same way as it is written
4875 in @code{beginning-of-buffer}.  The expression moves the cursor to
4876 the minimum point in the buffer, that is, to the beginning of the buffer
4877 (or to the beginning of the accessible portion of the buffer).  As a
4878 result of this, point is placed at the beginning of the buffer and mark
4879 is set at the end of the buffer.  The whole buffer is, therefore, the
4880 region.
4882 @c FIXME: the definition of append-to-buffer has been changed (in
4883 @c 2010-03-30).
4884 @node append-to-buffer
4885 @section The Definition of @code{append-to-buffer}
4886 @findex append-to-buffer
4888 The @code{append-to-buffer} command is more complex than the
4889 @code{mark-whole-buffer} command.  What it does is copy the region
4890 (that is, the part of the buffer between point and mark) from the
4891 current buffer to a specified buffer.
4893 @menu
4894 * append-to-buffer overview::
4895 * append interactive::          A two part interactive expression.
4896 * append-to-buffer body::       Incorporates a @code{let} expression.
4897 * append save-excursion::       How the @code{save-excursion} works.
4898 @end menu
4900 @ifnottex
4901 @node append-to-buffer overview
4902 @unnumberedsubsec An Overview of @code{append-to-buffer}
4903 @end ifnottex
4905 @findex insert-buffer-substring
4906 The @code{append-to-buffer} command uses the
4907 @code{insert-buffer-substring} function to copy the region.
4908 @code{insert-buffer-substring} is described by its name: it takes a
4909 substring from a buffer, and inserts it into another buffer.
4911 Most of @code{append-to-buffer} is
4912 concerned with setting up the conditions for
4913 @code{insert-buffer-substring} to work: the code must specify both the
4914 buffer to which the text will go, the window it comes from and goes
4915 to, and the region that will be copied.
4917 @need 1250
4918 Here is the complete text of the function:
4920 @smallexample
4921 @group
4922 (defun append-to-buffer (buffer start end)
4923   "Append to specified buffer the text of the region.
4924 It is inserted into that buffer before its point.
4925 @end group
4927 @group
4928 When calling from a program, give three arguments:
4929 BUFFER (or buffer name), START and END.
4930 START and END specify the portion of the current buffer to be copied."
4931   (interactive
4932    (list (read-buffer "Append to buffer: " (other-buffer
4933                                             (current-buffer) t))
4934          (region-beginning) (region-end)))
4935 @end group
4936 @group
4937   (let ((oldbuf (current-buffer)))
4938     (save-excursion
4939       (let* ((append-to (get-buffer-create buffer))
4940              (windows (get-buffer-window-list append-to t t))
4941              point)
4942         (set-buffer append-to)
4943         (setq point (point))
4944         (barf-if-buffer-read-only)
4945         (insert-buffer-substring oldbuf start end)
4946         (dolist (window windows)
4947           (when (= (window-point window) point)
4948             (set-window-point window (point))))))))
4949 @end group
4950 @end smallexample
4952 The function can be understood by looking at it as a series of
4953 filled-in templates.
4955 The outermost template is for the function definition.  In this
4956 function, it looks like this (with several slots filled in):
4958 @smallexample
4959 @group
4960 (defun append-to-buffer (buffer start end)
4961   "@var{documentation}@dots{}"
4962   (interactive @dots{})
4963   @var{body}@dots{})
4964 @end group
4965 @end smallexample
4967 The first line of the function includes its name and three arguments.
4968 The arguments are the @code{buffer} to which the text will be copied, and
4969 the @code{start} and @code{end} of the region in the current buffer that
4970 will be copied.
4972 The next part of the function is the documentation, which is clear and
4973 complete.  As is conventional, the three arguments are written in
4974 upper case so you will notice them easily.  Even better, they are
4975 described in the same order as in the argument list.
4977 Note that the documentation distinguishes between a buffer and its
4978 name.  (The function can handle either.)
4980 @node append interactive
4981 @subsection The @code{append-to-buffer} Interactive Expression
4983 Since the @code{append-to-buffer} function will be used interactively,
4984 the function must have an @code{interactive} expression.  (For a
4985 review of @code{interactive}, see @ref{Interactive, , Making a
4986 Function Interactive}.)  The expression reads as follows:
4988 @smallexample
4989 @group
4990 (interactive
4991  (list (read-buffer
4992         "Append to buffer: "
4993         (other-buffer (current-buffer) t))
4994        (region-beginning)
4995        (region-end)))
4996 @end group
4997 @end smallexample
4999 @noindent
5000 This expression is not one with letters standing for parts, as
5001 described earlier.  Instead, it starts a list with these parts:
5003 The first part of the list is an expression to read the name of a
5004 buffer and return it as a string.  That is @code{read-buffer}.  The
5005 function requires a prompt as its first argument, @samp{"Append to
5006 buffer: "}.  Its second argument tells the command what value to
5007 provide if you don't specify anything.
5009 In this case that second argument is an expression containing the
5010 function @code{other-buffer}, an exception, and a @samp{t}, standing
5011 for true.
5013 The first argument to @code{other-buffer}, the exception, is yet
5014 another function, @code{current-buffer}.  That is not going to be
5015 returned.  The second argument is the symbol for true, @code{t}. that
5016 tells @code{other-buffer} that it may show visible buffers (except in
5017 this case, it will not show the current buffer, which makes sense).
5019 @need 1250
5020 The expression looks like this:
5022 @smallexample
5023 (other-buffer (current-buffer) t)
5024 @end smallexample
5026 The second and third arguments to the @code{list} expression are
5027 @code{(region-beginning)} and @code{(region-end)}.  These two
5028 functions specify the beginning and end of the text to be appended.
5030 @need 1250
5031 Originally, the command used the letters @samp{B} and @samp{r}.
5032 The whole @code{interactive} expression looked like this:
5034 @smallexample
5035 (interactive "BAppend to buffer:@: \nr")
5036 @end smallexample
5038 @noindent
5039 But when that was done, the default value of the buffer switched to
5040 was invisible.  That was not wanted.
5042 (The prompt was separated from the second argument with a newline,
5043 @samp{\n}.  It was followed by an @samp{r} that told Emacs to bind the
5044 two arguments that follow the symbol @code{buffer} in the function's
5045 argument list (that is, @code{start} and @code{end}) to the values of
5046 point and mark.  That argument worked fine.)
5048 @node append-to-buffer body
5049 @subsection The Body of @code{append-to-buffer}
5051 @ignore
5052 in GNU Emacs 22   in    /usr/local/src/emacs/lisp/simple.el
5054 (defun append-to-buffer (buffer start end)
5055   "Append to specified buffer the text of the region.
5056 It is inserted into that buffer before its point.
5058 When calling from a program, give three arguments:
5059 BUFFER (or buffer name), START and END.
5060 START and END specify the portion of the current buffer to be copied."
5061   (interactive
5062    (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5063          (region-beginning) (region-end)))
5064   (let ((oldbuf (current-buffer)))
5065     (save-excursion
5066       (let* ((append-to (get-buffer-create buffer))
5067              (windows (get-buffer-window-list append-to t t))
5068              point)
5069         (set-buffer append-to)
5070         (setq point (point))
5071         (barf-if-buffer-read-only)
5072         (insert-buffer-substring oldbuf start end)
5073         (dolist (window windows)
5074           (when (= (window-point window) point)
5075             (set-window-point window (point))))))))
5076 @end ignore
5078 The body of the @code{append-to-buffer} function begins with @code{let}.
5080 As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5081 @code{let} expression is to create and give initial values to one or
5082 more variables that will only be used within the body of the
5083 @code{let}.  This means that such a variable will not be confused with
5084 any variable of the same name outside the @code{let} expression.
5086 We can see how the @code{let} expression fits into the function as a
5087 whole by showing a template for @code{append-to-buffer} with the
5088 @code{let} expression in outline:
5090 @smallexample
5091 @group
5092 (defun append-to-buffer (buffer start end)
5093   "@var{documentation}@dots{}"
5094   (interactive @dots{})
5095   (let ((@var{variable} @var{value}))
5096         @var{body}@dots{})
5097 @end group
5098 @end smallexample
5100 The @code{let} expression has three elements:
5102 @enumerate
5103 @item
5104 The symbol @code{let};
5106 @item
5107 A varlist containing, in this case, a single two-element list,
5108 @code{(@var{variable} @var{value})};
5110 @item
5111 The body of the @code{let} expression.
5112 @end enumerate
5114 @need 800
5115 In the @code{append-to-buffer} function, the varlist looks like this:
5117 @smallexample
5118 (oldbuf (current-buffer))
5119 @end smallexample
5121 @noindent
5122 In this part of the @code{let} expression, the one variable,
5123 @code{oldbuf}, is bound to the value returned by the
5124 @code{(current-buffer)} expression.  The variable, @code{oldbuf}, is
5125 used to keep track of the buffer in which you are working and from
5126 which you will copy.
5128 The element or elements of a varlist are surrounded by a set of
5129 parentheses so the Lisp interpreter can distinguish the varlist from
5130 the body of the @code{let}.  As a consequence, the two-element list
5131 within the varlist is surrounded by a circumscribing set of parentheses.
5132 The line looks like this:
5134 @smallexample
5135 @group
5136 (let ((oldbuf (current-buffer)))
5137   @dots{} )
5138 @end group
5139 @end smallexample
5141 @noindent
5142 The two parentheses before @code{oldbuf} might surprise you if you did
5143 not realize that the first parenthesis before @code{oldbuf} marks the
5144 boundary of the varlist and the second parenthesis marks the beginning
5145 of the two-element list, @code{(oldbuf (current-buffer))}.
5147 @node append save-excursion
5148 @subsection @code{save-excursion} in @code{append-to-buffer}
5150 The body of the @code{let} expression in @code{append-to-buffer}
5151 consists of a @code{save-excursion} expression.
5153 The @code{save-excursion} function saves the location of point, and restores it
5154 to that position after the expressions in the
5155 body of the @code{save-excursion} complete execution.  In addition,
5156 @code{save-excursion} keeps track of the original buffer, and
5157 restores it.  This is how @code{save-excursion} is used in
5158 @code{append-to-buffer}.
5160 @need 1500
5161 @cindex Indentation for formatting
5162 @cindex Formatting convention
5163 Incidentally, it is worth noting here that a Lisp function is normally
5164 formatted so that everything that is enclosed in a multi-line spread is
5165 indented more to the right than the first symbol.  In this function
5166 definition, the @code{let} is indented more than the @code{defun}, and
5167 the @code{save-excursion} is indented more than the @code{let}, like
5168 this:
5170 @smallexample
5171 @group
5172 (defun @dots{}
5173   @dots{}
5174   @dots{}
5175   (let@dots{}
5176     (save-excursion
5177       @dots{}
5178 @end group
5179 @end smallexample
5181 @need 1500
5182 @noindent
5183 This formatting convention makes it easy to see that the lines in
5184 the body of the @code{save-excursion} are enclosed by the parentheses
5185 associated with @code{save-excursion}, just as the
5186 @code{save-excursion} itself is enclosed by the parentheses associated
5187 with the @code{let}:
5189 @smallexample
5190 @group
5191 (let ((oldbuf (current-buffer)))
5192   (save-excursion
5193     @dots{}
5194     (set-buffer @dots{})
5195     (insert-buffer-substring oldbuf start end)
5196     @dots{}))
5197 @end group
5198 @end smallexample
5200 @need 1200
5201 The use of the @code{save-excursion} function can be viewed as a process
5202 of filling in the slots of a template:
5204 @smallexample
5205 @group
5206 (save-excursion
5207   @var{first-expression-in-body}
5208   @var{second-expression-in-body}
5209    @dots{}
5210   @var{last-expression-in-body})
5211 @end group
5212 @end smallexample
5214 @need 1200
5215 @noindent
5216 In this function, the body of the @code{save-excursion} contains only
5217 one expression, the @code{let*} expression.  You know about a
5218 @code{let} function.  The @code{let*} function is different.  It has a
5219 @samp{*} in its name.  It enables Emacs to set each variable in its
5220 varlist in sequence, one after another.
5222 Its critical feature is that variables later in the varlist can make
5223 use of the values to which Emacs set variables earlier in the varlist.
5224 @xref{fwd-para let, , The @code{let*} expression}.
5226 We will skip functions like @code{let*} and focus on two: the
5227 @code{set-buffer} function and the @code{insert-buffer-substring}
5228 function.
5230 @need 1250
5231 In the old days, the @code{set-buffer} expression was simply
5233 @smallexample
5234 (set-buffer (get-buffer-create buffer))
5235 @end smallexample
5237 @need 1250
5238 @noindent
5239 but now it is
5241 @smallexample
5242 (set-buffer append-to)
5243 @end smallexample
5245 @noindent
5246 @code{append-to} is bound to @code{(get-buffer-create buffer)} earlier
5247 on in the @code{let*} expression.  That extra binding would not be
5248 necessary except for that @code{append-to} is used later in the
5249 varlist as an argument to @code{get-buffer-window-list}.
5251 @ignore
5252 in GNU Emacs 22
5254   (let ((oldbuf (current-buffer)))
5255     (save-excursion
5256       (let* ((append-to (get-buffer-create buffer))
5257              (windows (get-buffer-window-list append-to t t))
5258              point)
5259         (set-buffer append-to)
5260         (setq point (point))
5261         (barf-if-buffer-read-only)
5262         (insert-buffer-substring oldbuf start end)
5263         (dolist (window windows)
5264           (when (= (window-point window) point)
5265             (set-window-point window (point))))))))
5266 @end ignore
5268 The @code{append-to-buffer} function definition inserts text from the
5269 buffer in which you are currently to a named buffer.  It happens that
5270 @code{insert-buffer-substring} copies text from another buffer to the
5271 current buffer, just the reverse---that is why the
5272 @code{append-to-buffer} definition starts out with a @code{let} that
5273 binds the local symbol @code{oldbuf} to the value returned by
5274 @code{current-buffer}.
5276 @need 1250
5277 The @code{insert-buffer-substring} expression looks like this:
5279 @smallexample
5280 (insert-buffer-substring oldbuf start end)
5281 @end smallexample
5283 @noindent
5284 The @code{insert-buffer-substring} function copies a string
5285 @emph{from} the buffer specified as its first argument and inserts the
5286 string into the present buffer.  In this case, the argument to
5287 @code{insert-buffer-substring} is the value of the variable created
5288 and bound by the @code{let}, namely the value of @code{oldbuf}, which
5289 was the current buffer when you gave the @code{append-to-buffer}
5290 command.
5292 After @code{insert-buffer-substring} has done its work,
5293 @code{save-excursion} will restore the action to the original buffer
5294 and @code{append-to-buffer} will have done its job.
5296 @need 800
5297 Written in skeletal form, the workings of the body look like this:
5299 @smallexample
5300 @group
5301 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5302   (save-excursion                       ; @r{Keep track of buffer.}
5303     @var{change-buffer}
5304     @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5306   @var{change-back-to-original-buffer-when-finished}
5307 @var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5308 @end group
5309 @end smallexample
5311 In summary, @code{append-to-buffer} works as follows: it saves the
5312 value of the current buffer in the variable called @code{oldbuf}.  It
5313 gets the new buffer (creating one if need be) and switches Emacs's
5314 attention to it.  Using the value of @code{oldbuf}, it inserts the
5315 region of text from the old buffer into the new buffer; and then using
5316 @code{save-excursion}, it brings you back to your original buffer.
5318 In looking at @code{append-to-buffer}, you have explored a fairly
5319 complex function.  It shows how to use @code{let} and
5320 @code{save-excursion}, and how to change to and come back from another
5321 buffer.  Many function definitions use @code{let},
5322 @code{save-excursion}, and @code{set-buffer} this way.
5324 @node Buffer Related Review
5325 @section Review
5327 Here is a brief summary of the various functions discussed in this chapter.
5329 @table @code
5330 @item describe-function
5331 @itemx describe-variable
5332 Print the documentation for a function or variable.
5333 Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5335 @item find-tag
5336 Find the file containing the source for a function or variable and
5337 switch buffers to it, positioning point at the beginning of the item.
5338 Conventionally bound to @kbd{M-.} (that's a period following the
5339 @key{META} key).
5341 @item save-excursion
5342 Save the location of point and restore its value after the
5343 arguments to @code{save-excursion} have been evaluated.  Also, remember
5344 the current buffer and return to it.
5346 @item push-mark
5347 Set mark at a location and record the value of the previous mark on the
5348 mark ring.  The mark is a location in the buffer that will keep its
5349 relative position even if text is added to or removed from the buffer.
5351 @item goto-char
5352 Set point to the location specified by the value of the argument, which
5353 can be a number, a marker,  or an expression that returns the number of
5354 a position, such as @code{(point-min)}.
5356 @item insert-buffer-substring
5357 Copy a region of text from a buffer that is passed to the function as
5358 an argument and insert the region into the current buffer.
5360 @item mark-whole-buffer
5361 Mark the whole buffer as a region.  Normally bound to @kbd{C-x h}.
5363 @item set-buffer
5364 Switch the attention of Emacs to another buffer, but do not change the
5365 window being displayed.  Used when the program rather than a human is
5366 to work on a different buffer.
5368 @item get-buffer-create
5369 @itemx get-buffer
5370 Find a named buffer or create one if a buffer of that name does not
5371 exist.  The @code{get-buffer} function returns @code{nil} if the named
5372 buffer does not exist.
5373 @end table
5375 @need 1500
5376 @node Buffer Exercises
5377 @section Exercises
5379 @itemize @bullet
5380 @item
5381 Write your own @code{simplified-end-of-buffer} function definition;
5382 then test it to see whether it works.
5384 @item
5385 Use @code{if} and @code{get-buffer} to write a function that prints a
5386 message telling you whether a buffer exists.
5388 @item
5389 Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5390 function.
5391 @end itemize
5393 @node More Complex
5394 @chapter A Few More Complex Functions
5396 In this chapter, we build on what we have learned in previous chapters
5397 by looking at more complex functions.  The @code{copy-to-buffer}
5398 function illustrates use of two @code{save-excursion} expressions in
5399 one definition, while the @code{insert-buffer} function illustrates
5400 use of an asterisk in an @code{interactive} expression, use of
5401 @code{or}, and the important distinction between a name and the object
5402 to which the name refers.
5404 @menu
5405 * copy-to-buffer::              With @code{set-buffer}, @code{get-buffer-create}.
5406 * insert-buffer::               Read-only, and with @code{or}.
5407 * beginning-of-buffer::         Shows @code{goto-char},
5408                                 @code{point-min}, and @code{push-mark}.
5409 * Second Buffer Related Review::
5410 * optional Exercise::
5411 @end menu
5413 @node copy-to-buffer
5414 @section The Definition of @code{copy-to-buffer}
5415 @findex copy-to-buffer
5417 After understanding how @code{append-to-buffer} works, it is easy to
5418 understand @code{copy-to-buffer}.  This function copies text into a
5419 buffer, but instead of adding to the second buffer, it replaces all the
5420 previous text in the second buffer.
5422 @need 800
5423 The body of @code{copy-to-buffer} looks like this,
5425 @smallexample
5426 @group
5427 @dots{}
5428 (interactive "BCopy to buffer: \nr")
5429 (let ((oldbuf (current-buffer)))
5430   (with-current-buffer (get-buffer-create buffer)
5431     (barf-if-buffer-read-only)
5432     (erase-buffer)
5433     (save-excursion
5434       (insert-buffer-substring oldbuf start end)))))
5435 @end group
5436 @end smallexample
5438 The @code{copy-to-buffer} function has a simpler @code{interactive}
5439 expression than @code{append-to-buffer}.
5441 @need 800
5442 The definition then says
5444 @smallexample
5445 (with-current-buffer (get-buffer-create buffer) @dots{}
5446 @end smallexample
5448 First, look at the earliest inner expression; that is evaluated first.
5449 That expression starts with @code{get-buffer-create buffer}.  The
5450 function tells the computer to use the buffer with the name specified
5451 as the one to which you are copying, or if such a buffer does not
5452 exist, to create it.  Then, the @code{with-current-buffer} function
5453 evaluates its body with that buffer temporarily current.
5455 (This demonstrates another way to shift the computer's attention but
5456 not the user's.  The @code{append-to-buffer} function showed how to do
5457 the same with @code{save-excursion} and @code{set-buffer}.
5458 @code{with-current-buffer} is a newer, and arguably easier,
5459 mechanism.)
5461 The @code{barf-if-buffer-read-only} function sends you an error
5462 message saying the buffer is read-only if you cannot modify it.
5464 The next line has the @code{erase-buffer} function as its sole
5465 contents.  That function erases the buffer.
5467 Finally, the last two lines contain the @code{save-excursion}
5468 expression with @code{insert-buffer-substring} as its body.
5469 The  @code{insert-buffer-substring} expression copies the text from
5470 the buffer you are in (and you have not seen the computer shift its
5471 attention, so you don't know that that buffer is now called
5472 @code{oldbuf}).
5474 Incidentally, this is what is meant by ``replacement''.  To replace text,
5475 Emacs erases the previous text and then inserts new text.
5477 @need 1250
5478 In outline, the body of @code{copy-to-buffer} looks like this:
5480 @smallexample
5481 @group
5482 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5483     (@var{with-the-buffer-you-are-copying-to}
5484       (@var{but-do-not-erase-or-copy-to-a-read-only-buffer})
5485       (erase-buffer)
5486       (save-excursion
5487         @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5488 @end group
5489 @end smallexample
5491 @node insert-buffer
5492 @section The Definition of @code{insert-buffer}
5493 @findex insert-buffer
5495 @code{insert-buffer} is yet another buffer-related function.  This
5496 command copies another buffer @emph{into} the current buffer.  It is the
5497 reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5498 copy a region of text @emph{from} the current buffer to another buffer.
5500 Here is a discussion based on the original code.  The code was
5501 simplified in 2003 and is harder to understand.
5503 (@xref{New insert-buffer, , New Body for @code{insert-buffer}}, to see
5504 a discussion of the new body.)
5506 In addition, this code illustrates the use of @code{interactive} with a
5507 buffer that might be @dfn{read-only} and the important distinction
5508 between the name of an object and the object actually referred to.
5510 @menu
5511 * insert-buffer code::
5512 * insert-buffer interactive::   When you can read, but not write.
5513 * insert-buffer body::          The body has an @code{or} and a @code{let}.
5514 * if & or::                     Using an @code{if} instead of an @code{or}.
5515 * Insert or::                   How the @code{or} expression works.
5516 * Insert let::                  Two @code{save-excursion} expressions.
5517 * New insert-buffer::
5518 @end menu
5520 @ifnottex
5521 @node insert-buffer code
5522 @unnumberedsubsec The Code for @code{insert-buffer}
5523 @end ifnottex
5525 @need 800
5526 Here is the earlier code:
5528 @smallexample
5529 @group
5530 (defun insert-buffer (buffer)
5531   "Insert after point the contents of BUFFER.
5532 Puts mark after the inserted text.
5533 BUFFER may be a buffer or a buffer name."
5534   (interactive "*bInsert buffer:@: ")
5535 @end group
5536 @group
5537   (or (bufferp buffer)
5538       (setq buffer (get-buffer buffer)))
5539   (let (start end newmark)
5540     (save-excursion
5541       (save-excursion
5542         (set-buffer buffer)
5543         (setq start (point-min) end (point-max)))
5544 @end group
5545 @group
5546       (insert-buffer-substring buffer start end)
5547       (setq newmark (point)))
5548     (push-mark newmark)))
5549 @end group
5550 @end smallexample
5552 @need 1200
5553 As with other function definitions, you can use a template to see an
5554 outline of the function:
5556 @smallexample
5557 @group
5558 (defun insert-buffer (buffer)
5559   "@var{documentation}@dots{}"
5560   (interactive "*bInsert buffer:@: ")
5561   @var{body}@dots{})
5562 @end group
5563 @end smallexample
5565 @node insert-buffer interactive
5566 @subsection The Interactive Expression in @code{insert-buffer}
5567 @findex interactive, @r{example use of}
5569 In @code{insert-buffer}, the argument to the @code{interactive}
5570 declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5571 buffer:@: }.
5573 @menu
5574 * Read-only buffer::            When a buffer cannot be modified.
5575 * b for interactive::           An existing buffer or else its name.
5576 @end menu
5578 @node Read-only buffer
5579 @unnumberedsubsubsec A Read-only Buffer
5580 @cindex Read-only buffer
5581 @cindex Asterisk for read-only buffer
5582 @findex * @r{for read-only buffer}
5584 The asterisk is for the situation when the current buffer is a
5585 read-only buffer---a buffer that cannot be modified.  If
5586 @code{insert-buffer} is called when the current buffer is read-only, a
5587 message to this effect is printed in the echo area and the terminal
5588 may beep or blink at you; you will not be permitted to insert anything
5589 into current buffer.  The asterisk does not need to be followed by a
5590 newline to separate it from the next argument.
5592 @node b for interactive
5593 @unnumberedsubsubsec @samp{b} in an Interactive Expression
5595 The next argument in the interactive expression starts with a lower
5596 case @samp{b}.  (This is different from the code for
5597 @code{append-to-buffer}, which uses an upper-case @samp{B}.
5598 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5599 The lower-case @samp{b} tells the Lisp interpreter that the argument
5600 for @code{insert-buffer} should be an existing buffer or else its
5601 name.  (The upper-case @samp{B} option provides for the possibility
5602 that the buffer does not exist.)  Emacs will prompt you for the name
5603 of the buffer, offering you a default buffer, with name completion
5604 enabled.  If the buffer does not exist, you receive a message that
5605 says ``No match''; your terminal may beep at you as well.
5607 The new and simplified code generates a list for @code{interactive}.
5608 It uses the @code{barf-if-buffer-read-only} and @code{read-buffer}
5609 functions with which we are already familiar and the @code{progn}
5610 special form with which we are not.  (It will be described later.)
5612 @node insert-buffer body
5613 @subsection The Body of the @code{insert-buffer} Function
5615 The body of the @code{insert-buffer} function has two major parts: an
5616 @code{or} expression and a @code{let} expression.  The purpose of the
5617 @code{or} expression is to ensure that the argument @code{buffer} is
5618 bound to a buffer and not just the name of a buffer.  The body of the
5619 @code{let} expression contains the code which copies the other buffer
5620 into the current buffer.
5622 @need 1250
5623 In outline, the two expressions fit into the @code{insert-buffer}
5624 function like this:
5626 @smallexample
5627 @group
5628 (defun insert-buffer (buffer)
5629   "@var{documentation}@dots{}"
5630   (interactive "*bInsert buffer:@: ")
5631   (or @dots{}
5632       @dots{}
5633 @end group
5634 @group
5635   (let (@var{varlist})
5636       @var{body-of-}@code{let}@dots{} )
5637 @end group
5638 @end smallexample
5640 To understand how the @code{or} expression ensures that the argument
5641 @code{buffer} is bound to a buffer and not to the name of a buffer, it
5642 is first necessary to understand the @code{or} function.
5644 Before doing this, let me rewrite this part of the function using
5645 @code{if} so that you can see what is done in a manner that will be familiar.
5647 @node if & or
5648 @subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5650 The job to be done is to make sure the value of @code{buffer} is a
5651 buffer itself and not the name of a buffer.  If the value is the name,
5652 then the buffer itself must be got.
5654 You can imagine yourself at a conference where an usher is wandering
5655 around holding a list with your name on it and looking for you: the
5656 usher is bound to your name, not to you; but when the usher finds
5657 you and takes your arm, the usher becomes bound to you.
5659 @need 800
5660 In Lisp, you might describe this situation like this:
5662 @smallexample
5663 @group
5664 (if (not (holding-on-to-guest))
5665     (find-and-take-arm-of-guest))
5666 @end group
5667 @end smallexample
5669 We want to do the same thing with a buffer---if we do not have the
5670 buffer itself, we want to get it.
5672 @need 1200
5673 Using a predicate called @code{bufferp} that tells us whether we have a
5674 buffer (rather than its name), we can write the code like this:
5676 @smallexample
5677 @group
5678 (if (not (bufferp buffer))              ; @r{if-part}
5679     (setq buffer (get-buffer buffer)))  ; @r{then-part}
5680 @end group
5681 @end smallexample
5683 @noindent
5684 Here, the true-or-false-test of the @code{if} expression is
5685 @w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5686 @w{@code{(setq buffer (get-buffer buffer))}}.
5688 In the test, the function @code{bufferp} returns true if its argument is
5689 a buffer---but false if its argument is the name of the buffer.  (The
5690 last character of the function name @code{bufferp} is the character
5691 @samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5692 indicates that the function is a predicate, which is a term that means
5693 that the function will determine whether some property is true or false.
5694 @xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5695 Argument}.)
5697 @need 1200
5698 The function @code{not} precedes the expression @code{(bufferp buffer)},
5699 so the true-or-false-test looks like this:
5701 @smallexample
5702 (not (bufferp buffer))
5703 @end smallexample
5705 @noindent
5706 @code{not} is a function that returns true if its argument is false
5707 and false if its argument is true.  So if @code{(bufferp buffer)}
5708 returns true, the @code{not} expression returns false and vice versa.
5710 Using this test, the @code{if} expression works as follows: when the
5711 value of the variable @code{buffer} is actually a buffer rather than
5712 its name, the true-or-false-test returns false and the @code{if}
5713 expression does not evaluate the then-part.  This is fine, since we do
5714 not need to do anything to the variable @code{buffer} if it really is
5715 a buffer.
5717 On the other hand, when the value of @code{buffer} is not a buffer
5718 itself, but the name of a buffer, the true-or-false-test returns true
5719 and the then-part of the expression is evaluated.  In this case, the
5720 then-part is @code{(setq buffer (get-buffer buffer))}.  This
5721 expression uses the @code{get-buffer} function to return an actual
5722 buffer itself, given its name.  The @code{setq} then sets the variable
5723 @code{buffer} to the value of the buffer itself, replacing its previous
5724 value (which was the name of the buffer).
5726 @node Insert or
5727 @subsection The @code{or} in the Body
5729 The purpose of the @code{or} expression in the @code{insert-buffer}
5730 function is to ensure that the argument @code{buffer} is bound to a
5731 buffer and not just to the name of a buffer.  The previous section shows
5732 how the job could have been done using an @code{if} expression.
5733 However, the @code{insert-buffer} function actually uses @code{or}.
5734 To understand this, it is necessary to understand how @code{or} works.
5736 @findex or
5737 An @code{or} function can have any number of arguments.  It evaluates
5738 each argument in turn and returns the value of the first of its
5739 arguments that is not @code{nil}.  Also, and this is a crucial feature
5740 of @code{or}, it does not evaluate any subsequent arguments after
5741 returning the first non-@code{nil} value.
5743 @need 800
5744 The @code{or} expression looks like this:
5746 @smallexample
5747 @group
5748 (or (bufferp buffer)
5749     (setq buffer (get-buffer buffer)))
5750 @end group
5751 @end smallexample
5753 @noindent
5754 The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5755 This expression returns true (a non-@code{nil} value) if the buffer is
5756 actually a buffer, and not just the name of a buffer.  In the @code{or}
5757 expression, if this is the case, the @code{or} expression returns this
5758 true value and does not evaluate the next expression---and this is fine
5759 with us, since we do not want to do anything to the value of
5760 @code{buffer} if it really is a buffer.
5762 On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5763 which it will be if the value of @code{buffer} is the name of a buffer,
5764 the Lisp interpreter evaluates the next element of the @code{or}
5765 expression.  This is the expression @code{(setq buffer (get-buffer
5766 buffer))}.  This expression returns a non-@code{nil} value, which
5767 is the value to which it sets the variable @code{buffer}---and this
5768 value is a buffer itself, not the name of a buffer.
5770 The result of all this is that the symbol @code{buffer} is always
5771 bound to a buffer itself rather than to the name of a buffer.  All
5772 this is necessary because the @code{set-buffer} function in a
5773 following line only works with a buffer itself, not with the name to a
5774 buffer.
5776 @need 1250
5777 Incidentally, using @code{or}, the situation with the usher would be
5778 written like this:
5780 @smallexample
5781 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
5782 @end smallexample
5784 @node Insert let
5785 @subsection The @code{let} Expression in @code{insert-buffer}
5787 After ensuring that the variable @code{buffer} refers to a buffer itself
5788 and not just to the name of a buffer, the @code{insert-buffer function}
5789 continues with a @code{let} expression.  This specifies three local
5790 variables, @code{start}, @code{end}, and @code{newmark} and binds them
5791 to the initial value @code{nil}.  These variables are used inside the
5792 remainder of the @code{let} and temporarily hide any other occurrence of
5793 variables of the same name in Emacs until the end of the @code{let}.
5795 @need 1200
5796 The body of the @code{let} contains two @code{save-excursion}
5797 expressions.  First, we will look at the inner @code{save-excursion}
5798 expression in detail.  The expression looks like this:
5800 @smallexample
5801 @group
5802 (save-excursion
5803   (set-buffer buffer)
5804   (setq start (point-min) end (point-max)))
5805 @end group
5806 @end smallexample
5808 @noindent
5809 The expression @code{(set-buffer buffer)} changes Emacs's attention
5810 from the current buffer to the one from which the text will copied.
5811 In that buffer, the variables @code{start} and @code{end} are set to
5812 the beginning and end of the buffer, using the commands
5813 @code{point-min} and @code{point-max}.  Note that we have here an
5814 illustration of how @code{setq} is able to set two variables in the
5815 same expression.  The first argument of @code{setq} is set to the
5816 value of its second, and its third argument is set to the value of its
5817 fourth.
5819 After the body of the inner @code{save-excursion} is evaluated, the
5820 @code{save-excursion} restores the original buffer, but @code{start} and
5821 @code{end} remain set to the values of the beginning and end of the
5822 buffer from which the text will be copied.
5824 @need 1250
5825 The outer @code{save-excursion} expression looks like this:
5827 @smallexample
5828 @group
5829 (save-excursion
5830   (@var{inner-}@code{save-excursion}@var{-expression}
5831      (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5832   (insert-buffer-substring buffer start end)
5833   (setq newmark (point)))
5834 @end group
5835 @end smallexample
5837 @noindent
5838 The @code{insert-buffer-substring} function copies the text
5839 @emph{into} the current buffer @emph{from} the region indicated by
5840 @code{start} and @code{end} in @code{buffer}.  Since the whole of the
5841 second buffer lies between @code{start} and @code{end}, the whole of
5842 the second buffer is copied into the buffer you are editing.  Next,
5843 the value of point, which will be at the end of the inserted text, is
5844 recorded in the variable @code{newmark}.
5846 After the body of the outer @code{save-excursion} is evaluated, point
5847 is relocated to its original place.
5849 However, it is convenient to locate a mark at the end of the newly
5850 inserted text and locate point at its beginning.  The @code{newmark}
5851 variable records the end of the inserted text.  In the last line of
5852 the @code{let} expression, the @code{(push-mark newmark)} expression
5853 function sets a mark to this location.  (The previous location of the
5854 mark is still accessible; it is recorded on the mark ring and you can
5855 go back to it with @kbd{C-u C-@key{SPC}}.)  Meanwhile, point is
5856 located at the beginning of the inserted text, which is where it was
5857 before you called the insert function, the position of which was saved
5858 by the first @code{save-excursion}.
5860 @need 1250
5861 The whole @code{let} expression looks like this:
5863 @smallexample
5864 @group
5865 (let (start end newmark)
5866   (save-excursion
5867     (save-excursion
5868       (set-buffer buffer)
5869       (setq start (point-min) end (point-max)))
5870     (insert-buffer-substring buffer start end)
5871     (setq newmark (point)))
5872   (push-mark newmark))
5873 @end group
5874 @end smallexample
5876 Like the @code{append-to-buffer} function, the @code{insert-buffer}
5877 function uses @code{let}, @code{save-excursion}, and
5878 @code{set-buffer}.  In addition, the function illustrates one way to
5879 use @code{or}.  All these functions are building blocks that we will
5880 find and use again and again.
5882 @node New insert-buffer
5883 @subsection New Body for @code{insert-buffer}
5884 @findex insert-buffer, new version body
5885 @findex new version body for insert-buffer
5887 The body in the GNU Emacs 22 version is more confusing than the original.
5889 @need 1250
5890 It consists of two expressions,
5892 @smallexample
5893 @group
5894   (push-mark
5895    (save-excursion
5896      (insert-buffer-substring (get-buffer buffer))
5897      (point)))
5899    nil
5900 @end group
5901 @end smallexample
5903 @noindent
5904 except, and this is what confuses novices, very important work is done
5905 inside the @code{push-mark} expression.
5907 The @code{get-buffer} function returns a buffer with the name
5908 provided.  You will note that the function is @emph{not} called
5909 @code{get-buffer-create}; it does not create a buffer if one does not
5910 already exist.  The buffer returned by @code{get-buffer}, an existing
5911 buffer, is passed to @code{insert-buffer-substring}, which inserts the
5912 whole of the buffer (since you did not specify anything else).
5914 The location into which the buffer is inserted is recorded by
5915 @code{push-mark}.  Then the function returns @code{nil}, the value of
5916 its last command.  Put another way, the @code{insert-buffer} function
5917 exists only to produce a side effect, inserting another buffer, not to
5918 return any value.
5920 @node beginning-of-buffer
5921 @section Complete Definition of @code{beginning-of-buffer}
5922 @findex beginning-of-buffer
5924 The basic structure of the @code{beginning-of-buffer} function has
5925 already been discussed.  (@xref{simplified-beginning-of-buffer, , A
5926 Simplified @code{beginning-of-buffer} Definition}.)
5927 This section describes the complex part of the definition.
5929 As previously described, when invoked without an argument,
5930 @code{beginning-of-buffer} moves the cursor to the beginning of the
5931 buffer (in truth, the beginning of the accessible portion of the
5932 buffer), leaving the mark at the previous position.  However, when the
5933 command is invoked with a number between one and ten, the function
5934 considers that number to be a fraction of the length of the buffer,
5935 measured in tenths, and Emacs moves the cursor that fraction of the
5936 way from the beginning of the buffer.  Thus, you can either call this
5937 function with the key command @kbd{M-<}, which will move the cursor to
5938 the beginning of the buffer, or with a key command such as @kbd{C-u 7
5939 M-<} which will move the cursor to a point 70% of the way through the
5940 buffer.  If a number bigger than ten is used for the argument, it
5941 moves to the end of the buffer.
5943 The @code{beginning-of-buffer} function can be called with or without an
5944 argument.  The use of the argument is optional.
5946 @menu
5947 * Optional Arguments::
5948 * beginning-of-buffer opt arg::  Example with optional argument.
5949 * beginning-of-buffer complete::
5950 @end menu
5952 @node Optional Arguments
5953 @subsection Optional Arguments
5955 Unless told otherwise, Lisp expects that a function with an argument in
5956 its function definition will be called with a value for that argument.
5957 If that does not happen, you get an error and a message that says
5958 @samp{Wrong number of arguments}.
5960 @cindex Optional arguments
5961 @cindex Keyword
5962 @findex optional
5963 However, optional arguments are a feature of Lisp: a particular
5964 @dfn{keyword} is used to tell the Lisp interpreter that an argument is
5965 optional.  The keyword is @code{&optional}.  (The @samp{&} in front of
5966 @samp{optional} is part of the keyword.)  In a function definition, if
5967 an argument follows the keyword @code{&optional}, no value need be
5968 passed to that argument when the function is called.
5970 @need 1200
5971 The first line of the function definition of @code{beginning-of-buffer}
5972 therefore looks like this:
5974 @smallexample
5975 (defun beginning-of-buffer (&optional arg)
5976 @end smallexample
5978 @need 1250
5979 In outline, the whole function looks like this:
5981 @smallexample
5982 @group
5983 (defun beginning-of-buffer (&optional arg)
5984   "@var{documentation}@dots{}"
5985   (interactive "P")
5986   (or (@var{is-the-argument-a-cons-cell} arg)
5987       (and @var{are-both-transient-mark-mode-and-mark-active-true})
5988       (push-mark))
5989   (let (@var{determine-size-and-set-it})
5990   (goto-char
5991     (@var{if-there-is-an-argument}
5992         @var{figure-out-where-to-go}
5993       @var{else-go-to}
5994       (point-min))))
5995    @var{do-nicety}
5996 @end group
5997 @end smallexample
5999 The function is similar to the @code{simplified-beginning-of-buffer}
6000 function except that the @code{interactive} expression has @code{"P"}
6001 as an argument and the @code{goto-char} function is followed by an
6002 if-then-else expression that figures out where to put the cursor if
6003 there is an argument that is not a cons cell.
6005 (Since I do not explain a cons cell for many more chapters, please
6006 consider ignoring the function @code{consp}.  @xref{List
6007 Implementation, , How Lists are Implemented}, and @ref{Cons Cell Type,
6008 , Cons Cell and List Types, elisp, The GNU Emacs Lisp Reference
6009 Manual}.)
6011 The @code{"P"} in the @code{interactive} expression tells Emacs to
6012 pass a prefix argument, if there is one, to the function in raw form.
6013 A prefix argument is made by typing the @key{META} key followed by a
6014 number, or by typing @kbd{C-u} and then a number.  (If you don't type
6015 a number, @kbd{C-u} defaults to a cons cell with a 4.  A lowercase
6016 @code{"p"} in the @code{interactive} expression causes the function to
6017 convert a prefix arg to a number.)
6019 The true-or-false-test of the @code{if} expression looks complex, but
6020 it is not: it checks whether @code{arg} has a value that is not
6021 @code{nil} and whether it is a cons cell.  (That is what @code{consp}
6022 does; it checks whether its argument is a cons cell.)  If @code{arg}
6023 has a value that is not @code{nil} (and is not a cons cell), which
6024 will be the case if @code{beginning-of-buffer} is called with a
6025 numeric argument, then this true-or-false-test will return true and
6026 the then-part of the @code{if} expression will be evaluated.  On the
6027 other hand, if @code{beginning-of-buffer} is not called with an
6028 argument, the value of @code{arg} will be @code{nil} and the else-part
6029 of the @code{if} expression will be evaluated.  The else-part is
6030 simply @code{point-min}, and when this is the outcome, the whole
6031 @code{goto-char} expression is @code{(goto-char (point-min))}, which
6032 is how we saw the @code{beginning-of-buffer} function in its
6033 simplified form.
6035 @node beginning-of-buffer opt arg
6036 @subsection @code{beginning-of-buffer} with an Argument
6038 When @code{beginning-of-buffer} is called with an argument, an
6039 expression is evaluated which calculates what value to pass to
6040 @code{goto-char}.  This expression is rather complicated at first sight.
6041 It includes an inner @code{if} expression and much arithmetic.  It looks
6042 like this:
6044 @smallexample
6045 @group
6046 (if (> (buffer-size) 10000)
6047     ;; @r{Avoid overflow for large buffer sizes!}
6048                           (* (prefix-numeric-value arg)
6049                              (/ size 10))
6050   (/
6051    (+ 10
6052       (*
6053        size (prefix-numeric-value arg))) 10)))
6054 @end group
6055 @end smallexample
6057 @menu
6058 * Disentangle beginning-of-buffer::
6059 * Large buffer case::
6060 * Small buffer case::
6061 @end menu
6063 @ifnottex
6064 @node Disentangle beginning-of-buffer
6065 @unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
6066 @end ifnottex
6068 Like other complex-looking expressions, the conditional expression
6069 within @code{beginning-of-buffer} can be disentangled by looking at it
6070 as parts of a template, in this case, the template for an if-then-else
6071 expression.  In skeletal form, the expression looks like this:
6073 @smallexample
6074 @group
6075 (if (@var{buffer-is-large}
6076     @var{divide-buffer-size-by-10-and-multiply-by-arg}
6077   @var{else-use-alternate-calculation}
6078 @end group
6079 @end smallexample
6081 The true-or-false-test of this inner @code{if} expression checks the
6082 size of the buffer.  The reason for this is that the old version 18
6083 Emacs used numbers that are no bigger than eight million or so and in
6084 the computation that followed, the programmer feared that Emacs might
6085 try to use over-large numbers if the buffer were large.  The term
6086 ``overflow'', mentioned in the comment, means numbers that are over
6087 large.  More recent versions of Emacs use larger numbers, but this
6088 code has not been touched, if only because people now look at buffers
6089 that are far, far larger than ever before.
6091 There are two cases:  if the buffer is large and if it is not.
6093 @node Large buffer case
6094 @unnumberedsubsubsec What happens in a large buffer
6096 In @code{beginning-of-buffer}, the inner @code{if} expression tests
6097 whether the size of the buffer is greater than 10,000 characters.  To do
6098 this, it uses the @code{>} function and the computation of @code{size}
6099 that comes from the let expression.
6101 In the old days, the function @code{buffer-size} was used.  Not only
6102 was that function called several times, it gave the size of the whole
6103 buffer, not the accessible part.  The computation makes much more
6104 sense when it handles just the accessible part.  (@xref{Narrowing &
6105 Widening, , Narrowing and Widening}, for more information on focusing
6106 attention to an accessible part.)
6108 @need 800
6109 The line looks like this:
6111 @smallexample
6112 (if (> size 10000)
6113 @end smallexample
6115 @need 1200
6116 @noindent
6117 When the buffer is large, the then-part of the @code{if} expression is
6118 evaluated.  It reads like this (after formatting for easy reading):
6120 @smallexample
6121 @group
6123   (prefix-numeric-value arg)
6124   (/ size 10))
6125 @end group
6126 @end smallexample
6128 @noindent
6129 This expression is a multiplication, with two arguments to the function
6130 @code{*}.
6132 The first argument is @code{(prefix-numeric-value arg)}.  When
6133 @code{"P"} is used as the argument for @code{interactive}, the value
6134 passed to the function as its argument is passed a @dfn{raw prefix
6135 argument}, and not a number.  (It is a number in a list.)  To perform
6136 the arithmetic, a conversion is necessary, and
6137 @code{prefix-numeric-value} does the job.
6139 @findex / @r{(division)}
6140 @cindex Division
6141 The second argument is @code{(/ size 10)}.  This expression divides
6142 the numeric value by ten---the numeric value of the size of the
6143 accessible portion of the buffer.  This produces a number that tells
6144 how many characters make up one tenth of the buffer size.  (In Lisp,
6145 @code{/} is used for division, just as @code{*} is used for
6146 multiplication.)
6148 @need 1200
6149 In the multiplication expression as a whole, this amount is multiplied
6150 by the value of the prefix argument---the multiplication looks like this:
6152 @smallexample
6153 @group
6154 (* @var{numeric-value-of-prefix-arg}
6155    @var{number-of-characters-in-one-tenth-of-the-accessible-buffer})
6156 @end group
6157 @end smallexample
6159 @noindent
6160 If, for example, the prefix argument is @samp{7}, the one-tenth value
6161 will be multiplied by 7 to give a position 70% of the way through.
6163 @need 1200
6164 The result of all this is that if the accessible portion of the buffer
6165 is large, the @code{goto-char} expression reads like this:
6167 @smallexample
6168 @group
6169 (goto-char (* (prefix-numeric-value arg)
6170               (/ size 10)))
6171 @end group
6172 @end smallexample
6174 This puts the cursor where we want it.
6176 @node Small buffer case
6177 @unnumberedsubsubsec What happens in a small buffer
6179 If the buffer contains fewer than 10,000 characters, a slightly
6180 different computation is performed.  You might think this is not
6181 necessary, since the first computation could do the job.  However, in
6182 a small buffer, the first method may not put the cursor on exactly the
6183 desired line; the second method does a better job.
6185 @need 800
6186 The code looks like this:
6188 @c Keep this on one line.
6189 @smallexample
6190 (/ (+ 10 (* size (prefix-numeric-value arg))) 10))
6191 @end smallexample
6193 @need 1200
6194 @noindent
6195 This is code in which you figure out what happens by discovering how the
6196 functions are embedded in parentheses.  It is easier to read if you
6197 reformat it with each expression indented more deeply than its
6198 enclosing expression:
6200 @smallexample
6201 @group
6202   (/
6203    (+ 10
6204       (*
6205        size
6206        (prefix-numeric-value arg)))
6207    10))
6208 @end group
6209 @end smallexample
6211 @need 1200
6212 @noindent
6213 Looking at parentheses, we see that the innermost operation is
6214 @code{(prefix-numeric-value arg)}, which converts the raw argument to
6215 a number.  In the following expression, this number is multiplied by
6216 the size of the accessible portion of the buffer:
6218 @smallexample
6219 (* size (prefix-numeric-value arg))
6220 @end smallexample
6222 @noindent
6223 This multiplication creates a number that may be larger than the size of
6224 the buffer---seven times larger if the argument is 7, for example.  Ten
6225 is then added to this number and finally the large number is divided by
6226 ten to provide a value that is one character larger than the percentage
6227 position in the buffer.
6229 The number that results from all this is passed to @code{goto-char} and
6230 the cursor is moved to that point.
6232 @need 1500
6233 @node beginning-of-buffer complete
6234 @subsection The Complete @code{beginning-of-buffer}
6236 @need 1000
6237 Here is the complete text of the @code{beginning-of-buffer} function:
6238 @sp 1
6240 @c In GNU Emacs 22
6241 @smallexample
6242 @group
6243 (defun beginning-of-buffer (&optional arg)
6244   "Move point to the beginning of the buffer;
6245 leave mark at previous position.
6246 With \\[universal-argument] prefix,
6247 do not set mark at previous position.
6248 With numeric arg N,
6249 put point N/10 of the way from the beginning.
6251 If the buffer is narrowed,
6252 this command uses the beginning and size
6253 of the accessible part of the buffer.
6254 @end group
6256 @group
6257 Don't use this command in Lisp programs!
6258 \(goto-char (point-min)) is faster
6259 and avoids clobbering the mark."
6260   (interactive "P")
6261   (or (consp arg)
6262       (and transient-mark-mode mark-active)
6263       (push-mark))
6264 @end group
6265 @group
6266   (let ((size (- (point-max) (point-min))))
6267     (goto-char (if (and arg (not (consp arg)))
6268                    (+ (point-min)
6269                       (if (> size 10000)
6270                           ;; Avoid overflow for large buffer sizes!
6271                           (* (prefix-numeric-value arg)
6272                              (/ size 10))
6273                         (/ (+ 10 (* size (prefix-numeric-value arg)))
6274                            10)))
6275                  (point-min))))
6276   (if (and arg (not (consp arg))) (forward-line 1)))
6277 @end group
6278 @end smallexample
6280 @ignore
6281 From before GNU Emacs 22
6282 @smallexample
6283 @group
6284 (defun beginning-of-buffer (&optional arg)
6285   "Move point to the beginning of the buffer;
6286 leave mark at previous position.
6287 With arg N, put point N/10 of the way
6288 from the true beginning.
6289 @end group
6290 @group
6291 Don't use this in Lisp programs!
6292 \(goto-char (point-min)) is faster
6293 and does not set the mark."
6294   (interactive "P")
6295   (push-mark)
6296 @end group
6297 @group
6298   (goto-char
6299    (if arg
6300        (if (> (buffer-size) 10000)
6301            ;; @r{Avoid overflow for large buffer sizes!}
6302            (* (prefix-numeric-value arg)
6303               (/ (buffer-size) 10))
6304 @end group
6305 @group
6306          (/ (+ 10 (* (buffer-size)
6307                      (prefix-numeric-value arg)))
6308             10))
6309      (point-min)))
6310   (if arg (forward-line 1)))
6311 @end group
6312 @end smallexample
6313 @end ignore
6315 @noindent
6316 Except for two small points, the previous discussion shows how this
6317 function works.  The first point deals with a detail in the
6318 documentation string, and the second point concerns the last line of
6319 the function.
6321 @need 800
6322 In the documentation string, there is reference to an expression:
6324 @smallexample
6325 \\[universal-argument]
6326 @end smallexample
6328 @noindent
6329 A @samp{\\} is used before the first square bracket of this
6330 expression.  This @samp{\\} tells the Lisp interpreter to substitute
6331 whatever key is currently bound to the @samp{[@dots{}]}.  In the case
6332 of @code{universal-argument}, that is usually @kbd{C-u}, but it might
6333 be different.  (@xref{Documentation Tips, , Tips for Documentation
6334 Strings, elisp, The GNU Emacs Lisp Reference Manual}, for more
6335 information.)
6337 @need 1200
6338 Finally, the last line of the @code{beginning-of-buffer} command says
6339 to move point to the beginning of the next line if the command is
6340 invoked with an argument:
6342 @smallexample
6343 (if (and arg (not (consp arg))) (forward-line 1))
6344 @end smallexample
6346 @noindent
6347 This puts the cursor at the beginning of the first line after the
6348 appropriate tenths position in the buffer.  This is a flourish that
6349 means that the cursor is always located @emph{at least} the requested
6350 tenths of the way through the buffer, which is a nicety that is,
6351 perhaps, not necessary, but which, if it did not occur, would be sure
6352 to draw complaints.  (The @code{(not (consp arg))} portion is so that
6353 if you specify the command with a @kbd{C-u}, but without a number,
6354 that is to say, if the raw prefix argument is simply a cons cell,
6355 the command does not put you at the beginning of the second line.)
6357 @node Second Buffer Related Review
6358 @section Review
6360 Here is a brief summary of some of the topics covered in this chapter.
6362 @table @code
6363 @item or
6364 Evaluate each argument in sequence, and return the value of the first
6365 argument that is not @code{nil}; if none return a value that is not
6366 @code{nil}, return @code{nil}.  In brief, return the first true value
6367 of the arguments; return a true value if one @emph{or} any of the
6368 others are true.
6370 @item and
6371 Evaluate each argument in sequence, and if any are @code{nil}, return
6372 @code{nil}; if none are @code{nil}, return the value of the last
6373 argument.  In brief, return a true value only if all the arguments are
6374 true; return a true value if one @emph{and} each of the others is
6375 true.
6377 @item &optional
6378 A keyword used to indicate that an argument to a function definition
6379 is optional; this means that the function can be evaluated without the
6380 argument, if desired.
6382 @item prefix-numeric-value
6383 Convert the raw prefix argument produced by @code{(interactive
6384 "P")} to a numeric value.
6386 @item forward-line
6387 Move point forward to the beginning of the next line, or if the argument
6388 is greater than one, forward that many lines.  If it can't move as far
6389 forward as it is supposed to, @code{forward-line} goes forward as far as
6390 it can and then returns a count of the number of additional lines it was
6391 supposed to move but couldn't.
6393 @item erase-buffer
6394 Delete the entire contents of the current buffer.
6396 @item bufferp
6397 Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6398 @end table
6400 @node optional Exercise
6401 @section @code{optional} Argument Exercise
6403 Write an interactive function with an optional argument that tests
6404 whether its argument, a number, is greater than or equal to, or else,
6405 less than the value of @code{fill-column}, and tells you which, in a
6406 message.  However, if you do not pass an argument to the function, use
6407 56 as a default value.
6409 @node Narrowing & Widening
6410 @chapter Narrowing and Widening
6411 @cindex Focusing attention (narrowing)
6412 @cindex Narrowing
6413 @cindex Widening
6415 Narrowing is a feature of Emacs that makes it possible for you to focus
6416 on a specific part of a buffer, and work without accidentally changing
6417 other parts.  Narrowing is normally disabled since it can confuse
6418 novices.
6420 @menu
6421 * Narrowing advantages::        The advantages of narrowing
6422 * save-restriction::            The @code{save-restriction} special form.
6423 * what-line::                   The number of the line that point is on.
6424 * narrow Exercise::
6425 @end menu
6427 @ifnottex
6428 @node Narrowing advantages
6429 @unnumberedsec The Advantages of Narrowing
6430 @end ifnottex
6432 With narrowing, the rest of a buffer is made invisible, as if it weren't
6433 there.  This is an advantage if, for example, you want to replace a word
6434 in one part of a buffer but not in another: you narrow to the part you want
6435 and the replacement is carried out only in that section, not in the rest
6436 of the buffer.  Searches will only work within a narrowed region, not
6437 outside of one, so if you are fixing a part of a document, you can keep
6438 yourself from accidentally finding parts you do not need to fix by
6439 narrowing just to the region you want.
6440 (The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6442 However, narrowing does make the rest of the buffer invisible, which
6443 can scare people who inadvertently invoke narrowing and think they
6444 have deleted a part of their file.  Moreover, the @code{undo} command
6445 (which is usually bound to @kbd{C-x u}) does not turn off narrowing
6446 (nor should it), so people can become quite desperate if they do not
6447 know that they can return the rest of a buffer to visibility with the
6448 @code{widen} command.
6449 (The key binding for @code{widen} is @kbd{C-x n w}.)
6451 Narrowing is just as useful to the Lisp interpreter as to a human.
6452 Often, an Emacs Lisp function is designed to work on just part of a
6453 buffer; or conversely, an Emacs Lisp function needs to work on all of a
6454 buffer that has been narrowed.  The @code{what-line} function, for
6455 example, removes the narrowing from a buffer, if it has any narrowing
6456 and when it has finished its job, restores the narrowing to what it was.
6457 On the other hand, the @code{count-lines} function
6458 uses narrowing to restrict itself to just that portion
6459 of the buffer in which it is interested and then restores the previous
6460 situation.
6462 @node save-restriction
6463 @section The @code{save-restriction} Special Form
6464 @findex save-restriction
6466 In Emacs Lisp, you can use the @code{save-restriction} special form to
6467 keep track of whatever narrowing is in effect, if any.  When the Lisp
6468 interpreter meets with @code{save-restriction}, it executes the code
6469 in the body of the @code{save-restriction} expression, and then undoes
6470 any changes to narrowing that the code caused.  If, for example, the
6471 buffer is narrowed and the code that follows @code{save-restriction}
6472 gets rid of the narrowing, @code{save-restriction} returns the buffer
6473 to its narrowed region afterwards.  In the @code{what-line} command,
6474 any narrowing the buffer may have is undone by the @code{widen}
6475 command that immediately follows the @code{save-restriction} command.
6476 Any original narrowing is restored just before the completion of the
6477 function.
6479 @need 1250
6480 The template for a @code{save-restriction} expression is simple:
6482 @smallexample
6483 @group
6484 (save-restriction
6485   @var{body}@dots{} )
6486 @end group
6487 @end smallexample
6489 @noindent
6490 The body of the @code{save-restriction} is one or more expressions that
6491 will be evaluated in sequence by the Lisp interpreter.
6493 Finally, a point to note: when you use both @code{save-excursion} and
6494 @code{save-restriction}, one right after the other, you should use
6495 @code{save-excursion} outermost.  If you write them in reverse order,
6496 you may fail to record narrowing in the buffer to which Emacs switches
6497 after calling @code{save-excursion}.  Thus, when written together,
6498 @code{save-excursion} and @code{save-restriction} should be written
6499 like this:
6501 @smallexample
6502 @group
6503 (save-excursion
6504   (save-restriction
6505     @var{body}@dots{}))
6506 @end group
6507 @end smallexample
6509 In other circumstances, when not written together, the
6510 @code{save-excursion} and @code{save-restriction} special forms must
6511 be written in the order appropriate to the function.
6513 @need 1250
6514 For example,
6516 @smallexample
6517 @group
6518   (save-restriction
6519     (widen)
6520     (save-excursion
6521     @var{body}@dots{}))
6522 @end group
6523 @end smallexample
6525 @ignore
6526 Emacs 22
6527 /usr/local/src/emacs/lisp/simple.el
6529 (defun what-line ()
6530   "Print the current buffer line number and narrowed line number of point."
6531   (interactive)
6532   (let ((start (point-min))
6533         (n (line-number-at-pos)))
6534     (if (= start 1)
6535         (message "Line %d" n)
6536       (save-excursion
6537         (save-restriction
6538           (widen)
6539           (message "line %d (narrowed line %d)"
6540                    (+ n (line-number-at-pos start) -1) n))))))
6542 (defun line-number-at-pos (&optional pos)
6543   "Return (narrowed) buffer line number at position POS.
6544 If POS is nil, use current buffer location.
6545 Counting starts at (point-min), so the value refers
6546 to the contents of the accessible portion of the buffer."
6547   (let ((opoint (or pos (point))) start)
6548     (save-excursion
6549       (goto-char (point-min))
6550       (setq start (point))
6551       (goto-char opoint)
6552       (forward-line 0)
6553       (1+ (count-lines start (point))))))
6555 (defun count-lines (start end)
6556   "Return number of lines between START and END.
6557 This is usually the number of newlines between them,
6558 but can be one more if START is not equal to END
6559 and the greater of them is not at the start of a line."
6560   (save-excursion
6561     (save-restriction
6562       (narrow-to-region start end)
6563       (goto-char (point-min))
6564       (if (eq selective-display t)
6565           (save-match-data
6566             (let ((done 0))
6567               (while (re-search-forward "[\n\C-m]" nil t 40)
6568                 (setq done (+ 40 done)))
6569               (while (re-search-forward "[\n\C-m]" nil t 1)
6570                 (setq done (+ 1 done)))
6571               (goto-char (point-max))
6572               (if (and (/= start end)
6573                        (not (bolp)))
6574                   (1+ done)
6575                 done)))
6576         (- (buffer-size) (forward-line (buffer-size)))))))
6577 @end ignore
6579 @node what-line
6580 @section @code{what-line}
6581 @findex what-line
6582 @cindex Widening, example of
6584 The @code{what-line} command tells you the number of the line in which
6585 the cursor is located.  The function illustrates the use of the
6586 @code{save-restriction} and @code{save-excursion} commands.  Here is the
6587 original text of the function:
6589 @smallexample
6590 @group
6591 (defun what-line ()
6592   "Print the current line number (in the buffer) of point."
6593   (interactive)
6594   (save-restriction
6595     (widen)
6596     (save-excursion
6597       (beginning-of-line)
6598       (message "Line %d"
6599                (1+ (count-lines 1 (point)))))))
6600 @end group
6601 @end smallexample
6603 (In recent versions of GNU Emacs, the @code{what-line} function has
6604 been expanded to tell you your line number in a narrowed buffer as
6605 well as your line number in a widened buffer.  The recent version is
6606 more complex than the version shown here.  If you feel adventurous,
6607 you might want to look at it after figuring out how this version
6608 works.  You will probably need to use @kbd{C-h f}
6609 (@code{describe-function}).  The newer version uses a conditional to
6610 determine whether the buffer has been narrowed.
6612 (Also, it uses @code{line-number-at-pos}, which among other simple
6613 expressions, such as @code{(goto-char (point-min))}, moves point to
6614 the beginning of the current line with @code{(forward-line 0)} rather
6615 than @code{beginning-of-line}.)
6617 The @code{what-line} function as shown here has a documentation line
6618 and is interactive, as you would expect.  The next two lines use the
6619 functions @code{save-restriction} and @code{widen}.
6621 The @code{save-restriction} special form notes whatever narrowing is in
6622 effect, if any, in the current buffer and restores that narrowing after
6623 the code in the body of the @code{save-restriction} has been evaluated.
6625 The @code{save-restriction} special form is followed by @code{widen}.
6626 This function undoes any narrowing the current buffer may have had
6627 when @code{what-line} was called.  (The narrowing that was there is
6628 the narrowing that @code{save-restriction} remembers.)  This widening
6629 makes it possible for the line counting commands to count from the
6630 beginning of the buffer.  Otherwise, they would have been limited to
6631 counting within the accessible region.  Any original narrowing is
6632 restored just before the completion of the function by the
6633 @code{save-restriction} special form.
6635 The call to @code{widen} is followed by @code{save-excursion}, which
6636 saves the location of the cursor (i.e., of point), and
6637 restores it after the code in the body of the @code{save-excursion}
6638 uses the @code{beginning-of-line} function to move point.
6640 (Note that the @code{(widen)} expression comes between the
6641 @code{save-restriction} and @code{save-excursion} special forms.  When
6642 you write the two @code{save- @dots{}} expressions in sequence, write
6643 @code{save-excursion} outermost.)
6645 @need 1200
6646 The last two lines of the @code{what-line} function are functions to
6647 count the number of lines in the buffer and then print the number in the
6648 echo area.
6650 @smallexample
6651 @group
6652 (message "Line %d"
6653          (1+ (count-lines 1 (point)))))))
6654 @end group
6655 @end smallexample
6657 The @code{message} function prints a one-line message at the bottom of
6658 the Emacs screen.  The first argument is inside of quotation marks and
6659 is printed as a string of characters.  However, it may contain a
6660 @samp{%d} expression to print a following argument.  @samp{%d} prints
6661 the argument as a decimal, so the message will say something such as
6662 @samp{Line 243}.
6664 @need 1200
6665 The number that is printed in place of the @samp{%d} is computed by the
6666 last line of the function:
6668 @smallexample
6669 (1+ (count-lines 1 (point)))
6670 @end smallexample
6672 @ignore
6673 GNU Emacs 22
6675 (defun count-lines (start end)
6676   "Return number of lines between START and END.
6677 This is usually the number of newlines between them,
6678 but can be one more if START is not equal to END
6679 and the greater of them is not at the start of a line."
6680   (save-excursion
6681     (save-restriction
6682       (narrow-to-region start end)
6683       (goto-char (point-min))
6684       (if (eq selective-display t)
6685           (save-match-data
6686             (let ((done 0))
6687               (while (re-search-forward "[\n\C-m]" nil t 40)
6688                 (setq done (+ 40 done)))
6689               (while (re-search-forward "[\n\C-m]" nil t 1)
6690                 (setq done (+ 1 done)))
6691               (goto-char (point-max))
6692               (if (and (/= start end)
6693                        (not (bolp)))
6694                   (1+ done)
6695                 done)))
6696         (- (buffer-size) (forward-line (buffer-size)))))))
6697 @end ignore
6699 @noindent
6700 What this does is count the lines from the first position of the
6701 buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6702 one to that number.  (The @code{1+} function adds one to its
6703 argument.)  We add one to it because line 2 has only one line before
6704 it, and @code{count-lines} counts only the lines @emph{before} the
6705 current line.
6707 After @code{count-lines} has done its job, and the message has been
6708 printed in the echo area, the @code{save-excursion} restores point to
6709 its original position; and @code{save-restriction} restores
6710 the original narrowing, if any.
6712 @node narrow Exercise
6713 @section Exercise with Narrowing
6715 Write a function that will display the first 60 characters of the
6716 current buffer, even if you have narrowed the buffer to its latter
6717 half so that the first line is inaccessible.  Restore point, mark, and
6718 narrowing.  For this exercise, you need to use a whole potpourri of
6719 functions, including @code{save-restriction}, @code{widen},
6720 @code{goto-char}, @code{point-min}, @code{message}, and
6721 @code{buffer-substring}.
6723 @cindex Properties, mention of @code{buffer-substring-no-properties}
6724 (@code{buffer-substring} is a previously unmentioned function you will
6725 have to investigate yourself; or perhaps you will have to use
6726 @code{buffer-substring-no-properties} or
6727 @code{filter-buffer-substring} @dots{}, yet other functions.  Text
6728 properties are a feature otherwise not discussed here.  @xref{Text
6729 Properties, , Text Properties, elisp, The GNU Emacs Lisp Reference
6730 Manual}.)
6732 Additionally, do you really need @code{goto-char} or @code{point-min}?
6733 Or can you write the function without them?
6735 @node car cdr & cons
6736 @chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6737 @findex car, @r{introduced}
6738 @findex cdr, @r{introduced}
6740 In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6741 functions.  The @code{cons} function is used to construct lists, and
6742 the @code{car} and @code{cdr} functions are used to take them apart.
6744 In the walk through of the @code{copy-region-as-kill} function, we
6745 will see @code{cons} as well as two variants on @code{cdr},
6746 namely, @code{setcdr} and @code{nthcdr}.  (@xref{copy-region-as-kill}.)
6748 @menu
6749 * Strange Names::               An historical aside: why the strange names?
6750 * car & cdr::                   Functions for extracting part of a list.
6751 * cons::                        Constructing a list.
6752 * nthcdr::                      Calling @code{cdr} repeatedly.
6753 * nth::
6754 * setcar::                      Changing the first element of a list.
6755 * setcdr::                      Changing the rest of a list.
6756 * cons Exercise::
6757 @end menu
6759 @ifnottex
6760 @node Strange Names
6761 @unnumberedsec Strange Names
6762 @end ifnottex
6764 The name of the @code{cons} function is not unreasonable: it is an
6765 abbreviation of the word ``construct''.  The origins of the names for
6766 @code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6767 is an acronym from the phrase ``Contents of the Address part of the
6768 Register''; and @code{cdr} (pronounced ``could-er'') is an acronym from
6769 the phrase ``Contents of the Decrement part of the Register''.  These
6770 phrases refer to specific pieces of hardware on the very early
6771 computer on which the original Lisp was developed.  Besides being
6772 obsolete, the phrases have been completely irrelevant for more than 25
6773 years to anyone thinking about Lisp.  Nonetheless, although a few
6774 brave scholars have begun to use more reasonable names for these
6775 functions, the old terms are still in use.  In particular, since the
6776 terms are used in the Emacs Lisp source code, we will use them in this
6777 introduction.
6779 @node car & cdr
6780 @section @code{car} and @code{cdr}
6782 The @sc{car} of a list is, quite simply, the first item in the list.
6783 Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6784 @code{rose}.
6786 @need 1200
6787 If you are reading this in Info in GNU Emacs, you can see this by
6788 evaluating the following:
6790 @smallexample
6791 (car '(rose violet daisy buttercup))
6792 @end smallexample
6794 @noindent
6795 After evaluating the expression, @code{rose} will appear in the echo
6796 area.
6798 Clearly, a more reasonable name for the @code{car} function would be
6799 @code{first} and this is often suggested.
6801 @code{car} does not remove the first item from the list; it only reports
6802 what it is.  After @code{car} has been applied to a list, the list is
6803 still the same as it was.  In the jargon, @code{car} is
6804 ``non-destructive''.  This feature turns out to be important.
6806 The @sc{cdr} of a list is the rest of the list, that is, the
6807 @code{cdr} function returns the part of the list that follows the
6808 first item.  Thus, while the @sc{car} of the list @code{'(rose violet
6809 daisy buttercup)} is @code{rose}, the rest of the list, the value
6810 returned by the @code{cdr} function, is @code{(violet daisy
6811 buttercup)}.
6813 @need 800
6814 You can see this by evaluating the following in the usual way:
6816 @smallexample
6817 (cdr '(rose violet daisy buttercup))
6818 @end smallexample
6820 @noindent
6821 When you evaluate this, @code{(violet daisy buttercup)} will appear in
6822 the echo area.
6824 Like @code{car}, @code{cdr} does not remove any elements from the
6825 list---it just returns a report of what the second and subsequent
6826 elements are.
6828 Incidentally, in the example, the list of flowers is quoted.  If it were
6829 not, the Lisp interpreter would try to evaluate the list by calling
6830 @code{rose} as a function.  In this example, we do not want to do that.
6832 Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6834 (There is a lesson here: when you name new functions, consider very
6835 carefully what you are doing, since you may be stuck with the names
6836 for far longer than you expect.  The reason this document perpetuates
6837 these names is that the Emacs Lisp source code uses them, and if I did
6838 not use them, you would have a hard time reading the code; but do,
6839 please, try to avoid using these terms yourself.  The people who come
6840 after you will be grateful to you.)
6842 When @code{car} and @code{cdr} are applied to a list made up of symbols,
6843 such as the list @code{(pine fir oak maple)}, the element of the list
6844 returned by the function @code{car} is the symbol @code{pine} without
6845 any parentheses around it.  @code{pine} is the first element in the
6846 list.  However, the @sc{cdr} of the list is a list itself, @code{(fir
6847 oak maple)}, as you can see by evaluating the following expressions in
6848 the usual way:
6850 @smallexample
6851 @group
6852 (car '(pine fir oak maple))
6854 (cdr '(pine fir oak maple))
6855 @end group
6856 @end smallexample
6858 On the other hand, in a list of lists, the first element is itself a
6859 list.  @code{car} returns this first element as a list.  For example,
6860 the following list contains three sub-lists, a list of carnivores, a
6861 list of herbivores and a list of sea mammals:
6863 @smallexample
6864 @group
6865 (car '((lion tiger cheetah)
6866        (gazelle antelope zebra)
6867        (whale dolphin seal)))
6868 @end group
6869 @end smallexample
6871 @noindent
6872 In this example, the first element or @sc{car} of the list is the list of
6873 carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
6874 @code{((gazelle antelope zebra) (whale dolphin seal))}.
6876 @smallexample
6877 @group
6878 (cdr '((lion tiger cheetah)
6879        (gazelle antelope zebra)
6880        (whale dolphin seal)))
6881 @end group
6882 @end smallexample
6884 It is worth saying again that @code{car} and @code{cdr} are
6885 non-destructive---that is, they do not modify or change lists to which
6886 they are applied.  This is very important for how they are used.
6888 Also, in the first chapter, in the discussion about atoms, I said that
6889 in Lisp, certain kinds of atom, such as an array, can be separated
6890 into parts; but the mechanism for doing this is different from the
6891 mechanism for splitting a list.  As far as Lisp is concerned, the
6892 atoms of a list are unsplittable.  (@xref{Lisp Atoms}.)  The
6893 @code{car} and @code{cdr} functions are used for splitting lists and
6894 are considered fundamental to Lisp.  Since they cannot split or gain
6895 access to the parts of an array, an array is considered an atom.
6896 Conversely, the other fundamental function, @code{cons}, can put
6897 together or construct a list, but not an array.  (Arrays are handled
6898 by array-specific functions.  @xref{Arrays, , Arrays, elisp, The GNU
6899 Emacs Lisp Reference Manual}.)
6901 @node cons
6902 @section @code{cons}
6903 @findex cons, @r{introduced}
6905 The @code{cons} function constructs lists; it is the inverse of
6906 @code{car} and @code{cdr}.  For example, @code{cons} can be used to make
6907 a four element list from the three element list, @code{(fir oak maple)}:
6909 @smallexample
6910 (cons 'pine '(fir oak maple))
6911 @end smallexample
6913 @need 800
6914 @noindent
6915 After evaluating this list, you will see
6917 @smallexample
6918 (pine fir oak maple)
6919 @end smallexample
6921 @noindent
6922 appear in the echo area.  @code{cons} causes the creation of a new
6923 list in which the element is followed by the elements of the original
6924 list.
6926 We often say that @code{cons} puts a new element at the beginning of
6927 a list, or that it attaches or pushes elements onto the list, but this
6928 phrasing can be misleading, since @code{cons} does not change an
6929 existing list, but creates a new one.
6931 Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
6933 @menu
6934 * Build a list::
6935 * length::                      How to find the length of a list.
6936 @end menu
6938 @ifnottex
6939 @node Build a list
6940 @unnumberedsubsec Build a list
6941 @end ifnottex
6943 @code{cons} must have a list to attach to.@footnote{Actually, you can
6944 @code{cons} an element to an atom to produce a dotted pair.  Dotted
6945 pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
6946 Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.}  You
6947 cannot start from absolutely nothing.  If you are building a list, you
6948 need to provide at least an empty list at the beginning.  Here is a
6949 series of @code{cons} expressions that build up a list of flowers.  If
6950 you are reading this in Info in GNU Emacs, you can evaluate each of
6951 the expressions in the usual way; the value is printed in this text
6952 after @samp{@result{}}, which you may read as ``evaluates to''.
6954 @smallexample
6955 @group
6956 (cons 'buttercup ())
6957      @result{} (buttercup)
6958 @end group
6960 @group
6961 (cons 'daisy '(buttercup))
6962      @result{} (daisy buttercup)
6963 @end group
6965 @group
6966 (cons 'violet '(daisy buttercup))
6967      @result{} (violet daisy buttercup)
6968 @end group
6970 @group
6971 (cons 'rose '(violet daisy buttercup))
6972      @result{} (rose violet daisy buttercup)
6973 @end group
6974 @end smallexample
6976 @noindent
6977 In the first example, the empty list is shown as @code{()} and a list
6978 made up of @code{buttercup} followed by the empty list is constructed.
6979 As you can see, the empty list is not shown in the list that was
6980 constructed.  All that you see is @code{(buttercup)}.  The empty list is
6981 not counted as an element of a list because there is nothing in an empty
6982 list.  Generally speaking, an empty list is invisible.
6984 The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
6985 two element list by putting @code{daisy} in front of @code{buttercup};
6986 and the third example constructs a three element list by putting
6987 @code{violet} in front of @code{daisy} and @code{buttercup}.
6989 @node length
6990 @subsection Find the Length of a List: @code{length}
6991 @findex length
6993 You can find out how many elements there are in a list by using the Lisp
6994 function @code{length}, as in the following examples:
6996 @smallexample
6997 @group
6998 (length '(buttercup))
6999      @result{} 1
7000 @end group
7002 @group
7003 (length '(daisy buttercup))
7004      @result{} 2
7005 @end group
7007 @group
7008 (length (cons 'violet '(daisy buttercup)))
7009      @result{} 3
7010 @end group
7011 @end smallexample
7013 @noindent
7014 In the third example, the @code{cons} function is used to construct a
7015 three element list which is then passed to the @code{length} function as
7016 its argument.
7018 @need 1200
7019 We can also use @code{length} to count the number of elements in an
7020 empty list:
7022 @smallexample
7023 @group
7024 (length ())
7025      @result{} 0
7026 @end group
7027 @end smallexample
7029 @noindent
7030 As you would expect, the number of elements in an empty list is zero.
7032 An interesting experiment is to find out what happens if you try to find
7033 the length of no list at all; that is, if you try to call @code{length}
7034 without giving it an argument, not even an empty list:
7036 @smallexample
7037 (length )
7038 @end smallexample
7040 @need 800
7041 @noindent
7042 What you see, if you evaluate this, is the error message
7044 @smallexample
7045 Lisp error: (wrong-number-of-arguments length 0)
7046 @end smallexample
7048 @noindent
7049 This means that the function receives the wrong number of
7050 arguments, zero, when it expects some other number of arguments.  In
7051 this case, one argument is expected, the argument being a list whose
7052 length the function is measuring.  (Note that @emph{one} list is
7053 @emph{one} argument, even if the list has many elements inside it.)
7055 The part of the error message that says @samp{length} is the name of
7056 the function.
7058 @ignore
7059 @code{length} is still a subroutine, but you need C-h f to discover that.
7061 In an earlier version:
7062     This is written with a special notation, @samp{#<subr},
7063     that indicates that the function @code{length} is one of the primitive
7064     functions written in C rather than in Emacs Lisp.  (@samp{subr} is an
7065     abbreviation for ``subroutine''.)  @xref{What Is a Function, , What Is a
7066     Function?, elisp , The GNU Emacs Lisp Reference Manual}, for more
7067     about subroutines.
7068 @end ignore
7070 @node nthcdr
7071 @section @code{nthcdr}
7072 @findex nthcdr
7074 The @code{nthcdr} function is associated with the @code{cdr} function.
7075 What it does is take the @sc{cdr} of a list repeatedly.
7077 If you take the @sc{cdr} of the list @code{(pine fir
7078 oak maple)}, you will be returned the list @code{(fir oak maple)}.  If you
7079 repeat this on what was returned, you will be returned the list
7080 @code{(oak maple)}.  (Of course, repeated @sc{cdr}ing on the original
7081 list will just give you the original @sc{cdr} since the function does
7082 not change the list.  You need to evaluate the @sc{cdr} of the
7083 @sc{cdr} and so on.)  If you continue this, eventually you will be
7084 returned an empty list, which in this case, instead of being shown as
7085 @code{()} is shown as @code{nil}.
7087 @need 1200
7088 For review, here is a series of repeated @sc{cdr}s, the text following
7089 the @samp{@result{}} shows what is returned.
7091 @smallexample
7092 @group
7093 (cdr '(pine fir oak maple))
7094      @result{}(fir oak maple)
7095 @end group
7097 @group
7098 (cdr '(fir oak maple))
7099      @result{} (oak maple)
7100 @end group
7102 @group
7103 (cdr '(oak maple))
7104      @result{}(maple)
7105 @end group
7107 @group
7108 (cdr '(maple))
7109      @result{} nil
7110 @end group
7112 @group
7113 (cdr 'nil)
7114      @result{} nil
7115 @end group
7117 @group
7118 (cdr ())
7119      @result{} nil
7120 @end group
7121 @end smallexample
7123 @need 1200
7124 You can also do several @sc{cdr}s without printing the values in
7125 between, like this:
7127 @smallexample
7128 @group
7129 (cdr (cdr '(pine fir oak maple)))
7130      @result{} (oak maple)
7131 @end group
7132 @end smallexample
7134 @noindent
7135 In this example, the Lisp interpreter evaluates the innermost list first.
7136 The innermost list is quoted, so it just passes the list as it is to the
7137 innermost @code{cdr}.  This @code{cdr} passes a list made up of the
7138 second and subsequent elements of the list to the outermost @code{cdr},
7139 which produces a list composed of the third and subsequent elements of
7140 the original list.  In this example, the @code{cdr} function is repeated
7141 and returns a list that consists of the original list without its
7142 first two elements.
7144 The @code{nthcdr} function does the same as repeating the call to
7145 @code{cdr}.  In the following example, the argument 2 is passed to the
7146 function @code{nthcdr}, along with the list, and the value returned is
7147 the list without its first two items, which is exactly the same
7148 as repeating @code{cdr} twice on the list:
7150 @smallexample
7151 @group
7152 (nthcdr 2 '(pine fir oak maple))
7153      @result{} (oak maple)
7154 @end group
7155 @end smallexample
7157 @need 1200
7158 Using the original four element list, we can see what happens when
7159 various numeric arguments are passed to @code{nthcdr}, including 0, 1,
7160 and 5:
7162 @smallexample
7163 @group
7164 ;; @r{Leave the list as it was.}
7165 (nthcdr 0 '(pine fir oak maple))
7166      @result{} (pine fir oak maple)
7167 @end group
7169 @group
7170 ;; @r{Return a copy without the first element.}
7171 (nthcdr 1 '(pine fir oak maple))
7172      @result{} (fir oak maple)
7173 @end group
7175 @group
7176 ;; @r{Return a copy of the list without three elements.}
7177 (nthcdr 3 '(pine fir oak maple))
7178      @result{} (maple)
7179 @end group
7181 @group
7182 ;; @r{Return a copy lacking all four elements.}
7183 (nthcdr 4 '(pine fir oak maple))
7184      @result{} nil
7185 @end group
7187 @group
7188 ;; @r{Return a copy lacking all elements.}
7189 (nthcdr 5 '(pine fir oak maple))
7190      @result{} nil
7191 @end group
7192 @end smallexample
7194 @node nth
7195 @section @code{nth}
7196 @findex nth
7198 The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
7199 The @code{nth} function takes the @sc{car} of the result returned by
7200 @code{nthcdr}.  It returns the Nth element of the list.
7202 @need 1500
7203 Thus, if it were not defined in C for speed, the definition of
7204 @code{nth} would be:
7206 @smallexample
7207 @group
7208 (defun nth (n list)
7209   "Returns the Nth element of LIST.
7210 N counts from zero.  If LIST is not that long, nil is returned."
7211   (car (nthcdr n list)))
7212 @end group
7213 @end smallexample
7215 @noindent
7216 (Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
7217 but its definition was redone in C in the 1980s.)
7219 The @code{nth} function returns a single element of a list.
7220 This can be very convenient.
7222 Note that the elements are numbered from zero, not one.  That is to
7223 say, the first element of a list, its @sc{car} is the zeroth element.
7224 This zero-based counting often bothers people who
7225 are accustomed to the first element in a list being number one, which
7226 is one-based.
7228 @need 1250
7229 For example:
7231 @smallexample
7232 @group
7233 (nth 0 '("one" "two" "three"))
7234     @result{} "one"
7236 (nth 1 '("one" "two" "three"))
7237     @result{} "two"
7238 @end group
7239 @end smallexample
7241 It is worth mentioning that @code{nth}, like @code{nthcdr} and
7242 @code{cdr}, does not change the original list---the function is
7243 non-destructive.  This is in sharp contrast to the @code{setcar} and
7244 @code{setcdr} functions.
7246 @node setcar
7247 @section @code{setcar}
7248 @findex setcar
7250 As you might guess from their names, the @code{setcar} and @code{setcdr}
7251 functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7252 They actually change the original list, unlike @code{car} and @code{cdr}
7253 which leave the original list as it was.  One way to find out how this
7254 works is to experiment.  We will start with the @code{setcar} function.
7256 @need 1200
7257 First, we can make a list and then set the value of a variable to the
7258 list, using the @code{setq} function.  Here is a list of animals:
7260 @smallexample
7261 (setq animals '(antelope giraffe lion tiger))
7262 @end smallexample
7264 @noindent
7265 If you are reading this in Info inside of GNU Emacs, you can evaluate
7266 this expression in the usual fashion, by positioning the cursor after
7267 the expression and typing @kbd{C-x C-e}.  (I'm doing this right here
7268 as I write this.  This is one of the advantages of having the
7269 interpreter built into the computing environment.  Incidentally, when
7270 there is nothing on the line after the final parentheses, such as a
7271 comment, point can be on the next line.  Thus, if your cursor is in
7272 the first column of the next line, you do not need to move it.
7273 Indeed, Emacs permits any amount of white space after the final
7274 parenthesis.)
7276 @need 1200
7277 When we evaluate the variable @code{animals}, we see that it is bound to
7278 the list @code{(antelope giraffe lion tiger)}:
7280 @smallexample
7281 @group
7282 animals
7283      @result{} (antelope giraffe lion tiger)
7284 @end group
7285 @end smallexample
7287 @noindent
7288 Put another way, the variable @code{animals} points to the list
7289 @code{(antelope giraffe lion tiger)}.
7291 Next, evaluate the function @code{setcar} while passing it two
7292 arguments, the variable @code{animals} and the quoted symbol
7293 @code{hippopotamus}; this is done by writing the three element list
7294 @code{(setcar animals 'hippopotamus)} and then evaluating it in the
7295 usual fashion:
7297 @smallexample
7298 (setcar animals 'hippopotamus)
7299 @end smallexample
7301 @need 1200
7302 @noindent
7303 After evaluating this expression, evaluate the variable @code{animals}
7304 again.  You will see that the list of animals has changed:
7306 @smallexample
7307 @group
7308 animals
7309      @result{} (hippopotamus giraffe lion tiger)
7310 @end group
7311 @end smallexample
7313 @noindent
7314 The first element on the list, @code{antelope} is replaced by
7315 @code{hippopotamus}.
7317 So we can see that @code{setcar} did not add a new element to the list
7318 as @code{cons} would have; it replaced @code{antelope} with
7319 @code{hippopotamus}; it @emph{changed} the list.
7321 @node setcdr
7322 @section @code{setcdr}
7323 @findex setcdr
7325 The @code{setcdr} function is similar to the @code{setcar} function,
7326 except that the function replaces the second and subsequent elements of
7327 a list rather than the first element.
7329 (To see how to change the last element of a list, look ahead to
7330 @ref{kill-new function, , The @code{kill-new} function}, which uses
7331 the @code{nthcdr} and @code{setcdr} functions.)
7333 @need 1200
7334 To see how this works, set the value of the variable to a list of
7335 domesticated animals by evaluating the following expression:
7337 @smallexample
7338 (setq domesticated-animals '(horse cow sheep goat))
7339 @end smallexample
7341 @need 1200
7342 @noindent
7343 If you now evaluate the list, you will be returned the list
7344 @code{(horse cow sheep goat)}:
7346 @smallexample
7347 @group
7348 domesticated-animals
7349      @result{} (horse cow sheep goat)
7350 @end group
7351 @end smallexample
7353 @need 1200
7354 Next, evaluate @code{setcdr} with two arguments, the name of the
7355 variable which has a list as its value, and the list to which the
7356 @sc{cdr} of the first list will be set;
7358 @smallexample
7359 (setcdr domesticated-animals '(cat dog))
7360 @end smallexample
7362 @noindent
7363 If you evaluate this expression, the list @code{(cat dog)} will appear
7364 in the echo area.  This is the value returned by the function.  The
7365 result we are interested in is the side effect, which we can see by
7366 evaluating the variable @code{domesticated-animals}:
7368 @smallexample
7369 @group
7370 domesticated-animals
7371      @result{} (horse cat dog)
7372 @end group
7373 @end smallexample
7375 @noindent
7376 Indeed, the list is changed from @code{(horse cow sheep goat)} to
7377 @code{(horse cat dog)}.  The @sc{cdr} of the list is changed from
7378 @code{(cow sheep goat)} to @code{(cat dog)}.
7380 @node cons Exercise
7381 @section Exercise
7383 Construct a list of four birds by evaluating several expressions with
7384 @code{cons}.  Find out what happens when you @code{cons} a list onto
7385 itself.  Replace the first element of the list of four birds with a
7386 fish.  Replace the rest of that list with a list of other fish.
7388 @node Cutting & Storing Text
7389 @chapter Cutting and Storing Text
7390 @cindex Cutting and storing text
7391 @cindex Storing and cutting text
7392 @cindex Killing text
7393 @cindex Clipping text
7394 @cindex Erasing text
7395 @cindex Deleting text
7397 Whenever you cut or clip text out of a buffer with a @dfn{kill} command in
7398 GNU Emacs, it is stored in a list and you can bring it back with a
7399 @dfn{yank} command.
7401 (The use of the word ``kill'' in Emacs for processes which specifically
7402 @emph{do not} destroy the values of the entities is an unfortunate
7403 historical accident.  A much more appropriate word would be ``clip'' since
7404 that is what the kill commands do; they clip text out of a buffer and
7405 put it into storage from which it can be brought back.  I have often
7406 been tempted to replace globally all occurrences of ``kill'' in the Emacs
7407 sources with ``clip'' and all occurrences of ``killed'' with ``clipped''.)
7409 @menu
7410 * Storing Text::                Text is stored in a list.
7411 * zap-to-char::                 Cutting out text up to a character.
7412 * kill-region::                 Cutting text out of a region.
7413 * copy-region-as-kill::         A definition for copying text.
7414 * Digression into C::           Minor note on C programming language macros.
7415 * defvar::                      How to give a variable an initial value.
7416 * cons & search-fwd Review::
7417 * search Exercises::
7418 @end menu
7420 @ifnottex
7421 @node Storing Text
7422 @unnumberedsec Storing Text in a List
7423 @end ifnottex
7425 When text is cut out of a buffer, it is stored on a list.  Successive
7426 pieces of text are stored on the list successively, so the list might
7427 look like this:
7429 @smallexample
7430 ("a piece of text" "previous piece")
7431 @end smallexample
7433 @need 1200
7434 @noindent
7435 The function @code{cons} can be used to create a new list from a piece
7436 of text (an ``atom'', to use the jargon) and an existing list, like
7437 this:
7439 @smallexample
7440 @group
7441 (cons "another piece"
7442       '("a piece of text" "previous piece"))
7443 @end group
7444 @end smallexample
7446 @need 1200
7447 @noindent
7448 If you evaluate this expression, a list of three elements will appear in
7449 the echo area:
7451 @smallexample
7452 ("another piece" "a piece of text" "previous piece")
7453 @end smallexample
7455 With the @code{car} and @code{nthcdr} functions, you can retrieve
7456 whichever piece of text you want.  For example, in the following code,
7457 @code{nthcdr 1 @dots{}} returns the list with the first item removed;
7458 and the @code{car} returns the first element of that remainder---the
7459 second element of the original list:
7461 @smallexample
7462 @group
7463 (car (nthcdr 1 '("another piece"
7464                  "a piece of text"
7465                  "previous piece")))
7466      @result{} "a piece of text"
7467 @end group
7468 @end smallexample
7470 The actual functions in Emacs are more complex than this, of course.
7471 The code for cutting and retrieving text has to be written so that
7472 Emacs can figure out which element in the list you want---the first,
7473 second, third, or whatever.  In addition, when you get to the end of
7474 the list, Emacs should give you the first element of the list, rather
7475 than nothing at all.
7477 The list that holds the pieces of text is called the @dfn{kill ring}.
7478 This chapter leads up to a description of the kill ring and how it is
7479 used by first tracing how the @code{zap-to-char} function works.  This
7480 function calls a function that invokes a function that
7481 manipulates the kill ring.  Thus, before reaching the mountains, we
7482 climb the foothills.
7484 A subsequent chapter describes how text that is cut from the buffer is
7485 retrieved.  @xref{Yanking, , Yanking Text Back}.
7487 @node zap-to-char
7488 @section @code{zap-to-char}
7489 @findex zap-to-char
7491 Let us look at the interactive @code{zap-to-char} function.
7493 @menu
7494 * Complete zap-to-char::        The complete implementation.
7495 * zap-to-char interactive::     A three part interactive expression.
7496 * zap-to-char body::            A short overview.
7497 * search-forward::              How to search for a string.
7498 * progn::                       The @code{progn} special form.
7499 * Summing up zap-to-char::      Using @code{point} and @code{search-forward}.
7500 @end menu
7502 @ifnottex
7503 @node Complete zap-to-char
7504 @unnumberedsubsec The Complete @code{zap-to-char} Implementation
7505 @end ifnottex
7507 The @code{zap-to-char} function removes the text in the region between
7508 the location of the cursor (i.e., of point) up to and including the
7509 next occurrence of a specified character.  The text that
7510 @code{zap-to-char} removes is put in the kill ring; and it can be
7511 retrieved from the kill ring by typing @kbd{C-y} (@code{yank}).  If
7512 the command is given an argument, it removes text through that number
7513 of occurrences.  Thus, if the cursor were at the beginning of this
7514 sentence and the character were @samp{s}, @samp{Thus} would be
7515 removed.  If the argument were two, @samp{Thus, if the curs} would be
7516 removed, up to and including the @samp{s} in @samp{cursor}.
7518 If the specified character is not found, @code{zap-to-char} will say
7519 ``Search failed'', tell you the character you typed, and not remove
7520 any text.
7522 In order to determine how much text to remove, @code{zap-to-char} uses
7523 a search function.  Searches are used extensively in code that
7524 manipulates text, and we will focus attention on them as well as on the
7525 deletion command.
7527 @ignore
7528 @c GNU Emacs version 19
7529 (defun zap-to-char (arg char)  ; version 19 implementation
7530   "Kill up to and including ARG'th occurrence of CHAR.
7531 Goes backward if ARG is negative; error if CHAR not found."
7532   (interactive "*p\ncZap to char: ")
7533   (kill-region (point)
7534                (progn
7535                  (search-forward
7536                   (char-to-string char) nil nil arg)
7537                  (point))))
7538 @end ignore
7540 @need 1250
7541 Here is the complete text of the version 22 implementation of the function:
7543 @c GNU Emacs 22
7544 @smallexample
7545 @group
7546 (defun zap-to-char (arg char)
7547   "Kill up to and including ARG'th occurrence of CHAR.
7548 Case is ignored if `case-fold-search' is non-nil in the current buffer.
7549 Goes backward if ARG is negative; error if CHAR not found."
7550   (interactive "p\ncZap to char: ")
7551   (if (char-table-p translation-table-for-input)
7552       (setq char (or (aref translation-table-for-input char) char)))
7553   (kill-region (point) (progn
7554                          (search-forward (char-to-string char)
7555                                          nil nil arg)
7556                          (point))))
7557 @end group
7558 @end smallexample
7560 The documentation is thorough.  You do need to know the jargon meaning
7561 of the word ``kill''.
7563 @cindex curved quotes
7564 @cindex curly quotes
7565 The version 22 documentation string for @code{zap-to-char} uses ASCII
7566 grave accent and apostrophe to quote a symbol, so it appears as
7567 @t{`case-fold-search'}.  This quoting style was inspired by 1970s-era
7568 displays in which grave accent and apostrophe were often mirror images
7569 suitable for use as quotes.  On most modern displays this is no longer
7570 true, and when these two ASCII characters appear in documentation
7571 strings or diagnostic message formats, Emacs typically transliterates
7572 them to @dfn{curved quotes} (left and right single quotation marks),
7573 so that the abovequoted symbol appears
7574 as @t{‘case-fold-search’}.  Source-code strings can also simply use
7575 curved quotes directly.
7577 @node zap-to-char interactive
7578 @subsection The @code{interactive} Expression
7580 @need 800
7581 The interactive expression in the @code{zap-to-char} command looks like
7582 this:
7584 @smallexample
7585 (interactive "p\ncZap to char: ")
7586 @end smallexample
7588 The part within quotation marks, @code{"p\ncZap to char:@: "}, specifies
7589 two different things.  First, and most simply, is the @samp{p}.
7590 This part is separated from the next part by a newline, @samp{\n}.
7591 The @samp{p} means that the first argument to the function will be
7592 passed the value of a @dfn{processed prefix}.  The prefix argument is
7593 passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number.  If
7594 the function is called interactively without a prefix, 1 is passed to
7595 this argument.
7597 The second part of @code{"p\ncZap to char:@: "} is
7598 @samp{cZap to char:@:  }.  In this part, the lower case @samp{c}
7599 indicates that @code{interactive} expects a prompt and that the
7600 argument will be a character.  The prompt follows the @samp{c} and is
7601 the string @samp{Zap to char:@: } (with a space after the colon to
7602 make it look good).
7604 What all this does is prepare the arguments to @code{zap-to-char} so they
7605 are of the right type, and give the user a prompt.
7607 In a read-only buffer, the @code{zap-to-char} function copies the text
7608 to the kill ring, but does not remove it.  The echo area displays a
7609 message saying that the buffer is read-only.  Also, the terminal may
7610 beep or blink at you.
7612 @node zap-to-char body
7613 @subsection The Body of @code{zap-to-char}
7615 The body of the @code{zap-to-char} function contains the code that
7616 kills (that is, removes) the text in the region from the current
7617 position of the cursor up to and including the specified character.
7619 The first part of the code looks like this:
7621 @smallexample
7622 (if (char-table-p translation-table-for-input)
7623     (setq char (or (aref translation-table-for-input char) char)))
7624 (kill-region (point) (progn
7625                        (search-forward (char-to-string char) nil nil arg)
7626                        (point)))
7627 @end smallexample
7629 @noindent
7630 @code{char-table-p} is an hitherto unseen function.  It determines
7631 whether its argument is a character table.  When it is, it sets the
7632 character passed to @code{zap-to-char} to one of them, if that
7633 character exists, or to the character itself.  (This becomes important
7634 for certain characters in non-European languages.  The @code{aref}
7635 function extracts an element from an array.  It is an array-specific
7636 function that is not described in this document.  @xref{Arrays, ,
7637 Arrays, elisp, The GNU Emacs Lisp Reference Manual}.)
7639 @noindent
7640 @code{(point)} is the current position of the cursor.
7642 The next part of the code is an expression using @code{progn}.  The body
7643 of the @code{progn} consists of calls to @code{search-forward} and
7644 @code{point}.
7646 It is easier to understand how @code{progn} works after learning about
7647 @code{search-forward}, so we will look at @code{search-forward} and
7648 then at @code{progn}.
7650 @node search-forward
7651 @subsection The @code{search-forward} Function
7652 @findex search-forward
7654 The @code{search-forward} function is used to locate the
7655 zapped-for-character in @code{zap-to-char}.  If the search is
7656 successful, @code{search-forward} leaves point immediately after the
7657 last character in the target string.  (In @code{zap-to-char}, the
7658 target string is just one character long.  @code{zap-to-char} uses the
7659 function @code{char-to-string} to ensure that the computer treats that
7660 character as a string.)  If the search is backwards,
7661 @code{search-forward} leaves point just before the first character in
7662 the target.  Also, @code{search-forward} returns @code{t} for true.
7663 (Moving point is therefore a side effect.)
7665 @need 1250
7666 In @code{zap-to-char}, the @code{search-forward} function looks like this:
7668 @smallexample
7669 (search-forward (char-to-string char) nil nil arg)
7670 @end smallexample
7672 The @code{search-forward} function takes four arguments:
7674 @enumerate
7675 @item
7676 The first argument is the target, what is searched for.  This must be a
7677 string, such as @samp{"z"}.
7679 As it happens, the argument passed to @code{zap-to-char} is a single
7680 character.  Because of the way computers are built, the Lisp
7681 interpreter may treat a single character as being different from a
7682 string of characters.  Inside the computer, a single character has a
7683 different electronic format than a string of one character.  (A single
7684 character can often be recorded in the computer using exactly one
7685 byte; but a string may be longer, and the computer needs to be ready
7686 for this.)  Since the @code{search-forward} function searches for a
7687 string, the character that the @code{zap-to-char} function receives as
7688 its argument must be converted inside the computer from one format to
7689 the other; otherwise the @code{search-forward} function will fail.
7690 The @code{char-to-string} function is used to make this conversion.
7692 @item
7693 The second argument bounds the search; it is specified as a position in
7694 the buffer.  In this case, the search can go to the end of the buffer,
7695 so no bound is set and the second argument is @code{nil}.
7697 @item
7698 The third argument tells the function what it should do if the search
7699 fails---it can signal an error (and print a message) or it can return
7700 @code{nil}.  A @code{nil} as the third argument causes the function to
7701 signal an error when the search fails.
7703 @item
7704 The fourth argument to @code{search-forward} is the repeat count---how
7705 many occurrences of the string to look for.  This argument is optional
7706 and if the function is called without a repeat count, this argument is
7707 passed the value 1.  If this argument is negative, the search goes
7708 backwards.
7709 @end enumerate
7711 @need 800
7712 In template form, a @code{search-forward} expression looks like this:
7714 @smallexample
7715 @group
7716 (search-forward "@var{target-string}"
7717                 @var{limit-of-search}
7718                 @var{what-to-do-if-search-fails}
7719                 @var{repeat-count})
7720 @end group
7721 @end smallexample
7723 We will look at @code{progn} next.
7725 @node progn
7726 @subsection The @code{progn} Special Form
7727 @findex progn
7729 @code{progn} is a special form that causes each of its arguments to be
7730 evaluated in sequence and then returns the value of the last one.  The
7731 preceding expressions are evaluated only for the side effects they
7732 perform.  The values produced by them are discarded.
7734 @need 800
7735 The template for a @code{progn} expression is very simple:
7737 @smallexample
7738 @group
7739 (progn
7740   @var{body}@dots{})
7741 @end group
7742 @end smallexample
7744 In @code{zap-to-char}, the @code{progn} expression has to do two things:
7745 put point in exactly the right position; and return the location of
7746 point so that @code{kill-region} will know how far to kill to.
7748 The first argument to the @code{progn} is @code{search-forward}.  When
7749 @code{search-forward} finds the string, the function leaves point
7750 immediately after the last character in the target string.  (In this
7751 case the target string is just one character long.)  If the search is
7752 backwards, @code{search-forward} leaves point just before the first
7753 character in the target.  The movement of point is a side effect.
7755 The second and last argument to @code{progn} is the expression
7756 @code{(point)}.  This expression returns the value of point, which in
7757 this case will be the location to which it has been moved by
7758 @code{search-forward}.  (In the source, a line that tells the function
7759 to go to the previous character, if it is going forward, was commented
7760 out in 1999; I don't remember whether that feature or mis-feature was
7761 ever a part of the distributed source.)  The value of @code{point} is
7762 returned by the @code{progn} expression and is passed to
7763 @code{kill-region} as @code{kill-region}'s second argument.
7765 @node Summing up zap-to-char
7766 @subsection Summing up @code{zap-to-char}
7768 Now that we have seen how @code{search-forward} and @code{progn} work,
7769 we can see how the @code{zap-to-char} function works as a whole.
7771 The first argument to @code{kill-region} is the position of the cursor
7772 when the @code{zap-to-char} command is given---the value of point at
7773 that time.  Within the @code{progn}, the search function then moves
7774 point to just after the zapped-to-character and @code{point} returns the
7775 value of this location.  The @code{kill-region} function puts together
7776 these two values of point, the first one as the beginning of the region
7777 and the second one as the end of the region, and removes the region.
7779 The @code{progn} special form is necessary because the
7780 @code{kill-region} command takes two arguments; and it would fail if
7781 @code{search-forward} and @code{point} expressions were written in
7782 sequence as two additional arguments.  The @code{progn} expression is
7783 a single argument to @code{kill-region} and returns the one value that
7784 @code{kill-region} needs for its second argument.
7786 @node kill-region
7787 @section @code{kill-region}
7788 @findex kill-region
7790 The @code{zap-to-char} function uses the @code{kill-region} function.
7791 This function clips text from a region and copies that text to
7792 the kill ring, from which it may be retrieved.
7794 @ignore
7795 GNU Emacs 22:
7797 (defun kill-region (beg end &optional yank-handler)
7798   "Kill (\"cut\") text between point and mark.
7799 This deletes the text from the buffer and saves it in the kill ring.
7800 The command \\[yank] can retrieve it from there.
7801 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
7803 If you want to append the killed region to the last killed text,
7804 use \\[append-next-kill] before \\[kill-region].
7806 If the buffer is read-only, Emacs will beep and refrain from deleting
7807 the text, but put the text in the kill ring anyway.  This means that
7808 you can use the killing commands to copy text from a read-only buffer.
7810 This is the primitive for programs to kill text (as opposed to deleting it).
7811 Supply two arguments, character positions indicating the stretch of text
7812  to be killed.
7813 Any command that calls this function is a \"kill command\".
7814 If the previous command was also a kill command,
7815 the text killed this time appends to the text killed last time
7816 to make one entry in the kill ring.
7818 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
7819 specifies the yank-handler text property to be set on the killed
7820 text.  See `insert-for-yank'."
7821   ;; Pass point first, then mark, because the order matters
7822   ;; when calling kill-append.
7823   (interactive (list (point) (mark)))
7824   (unless (and beg end)
7825     (error "The mark is not set now, so there is no region"))
7826   (condition-case nil
7827       (let ((string (filter-buffer-substring beg end t)))
7828         (when string                        ;STRING is nil if BEG = END
7829           ;; Add that string to the kill ring, one way or another.
7830           (if (eq last-command 'kill-region)
7831               (kill-append string (< end beg) yank-handler)
7832             (kill-new string nil yank-handler)))
7833         (when (or string (eq last-command 'kill-region))
7834           (setq this-command 'kill-region))
7835         nil)
7836     ((buffer-read-only text-read-only)
7837      ;; The code above failed because the buffer, or some of the characters
7838      ;; in the region, are read-only.
7839      ;; We should beep, in case the user just isn't aware of this.
7840      ;; However, there's no harm in putting
7841      ;; the region's text in the kill ring, anyway.
7842      (copy-region-as-kill beg end)
7843      ;; Set this-command now, so it will be set even if we get an error.
7844      (setq this-command 'kill-region)
7845      ;; This should barf, if appropriate, and give us the correct error.
7846      (if kill-read-only-ok
7847          (progn (message "Read only text copied to kill ring") nil)
7848        ;; Signal an error if the buffer is read-only.
7849        (barf-if-buffer-read-only)
7850        ;; If the buffer isn't read-only, the text is.
7851        (signal 'text-read-only (list (current-buffer)))))))
7852 @end ignore
7854 The Emacs 22 version of that function uses @code{condition-case} and
7855 @code{copy-region-as-kill}, both of which we will explain.
7856 @code{condition-case} is an important special form.
7858 In essence, the @code{kill-region} function calls
7859 @code{condition-case}, which takes three arguments.  In this function,
7860 the first argument does nothing.  The second argument contains the
7861 code that does the work when all goes well.  The third argument
7862 contains the code that is called in the event of an error.
7864 @menu
7865 * Complete kill-region::        The function definition.
7866 * condition-case::              Dealing with a problem.
7867 * Lisp macro::
7868 @end menu
7870 @ifnottex
7871 @node Complete kill-region
7872 @unnumberedsubsec The Complete @code{kill-region} Definition
7873 @end ifnottex
7875 @need 1200
7876 We will go through the @code{condition-case} code in a moment.  First,
7877 let us look at the definition of @code{kill-region}, with comments
7878 added:
7880 @c GNU Emacs 22:
7881 @smallexample
7882 @group
7883 (defun kill-region (beg end)
7884   "Kill (\"cut\") text between point and mark.
7885 This deletes the text from the buffer and saves it in the kill ring.
7886 The command \\[yank] can retrieve it from there. @dots{} "
7887 @end group
7889 @group
7890   ;; @bullet{} Since order matters, pass point first.
7891   (interactive (list (point) (mark)))
7892   ;; @bullet{} And tell us if we cannot cut the text.
7893   ;; 'unless' is an 'if' without a then-part.
7894   (unless (and beg end)
7895     (error "The mark is not set now, so there is no region"))
7896 @end group
7898 @group
7899   ;; @bullet{} 'condition-case' takes three arguments.
7900   ;;    If the first argument is nil, as it is here,
7901   ;;    information about the error signal is not
7902   ;;    stored for use by another function.
7903   (condition-case nil
7904 @end group
7906 @group
7907       ;; @bullet{} The second argument to 'condition-case' tells the
7908       ;;    Lisp interpreter what to do when all goes well.
7909 @end group
7911 @group
7912       ;;    It starts with a 'let' function that extracts the string
7913       ;;    and tests whether it exists.  If so (that is what the
7914       ;;    'when' checks), it calls an 'if' function that determines
7915       ;;    whether the previous command was another call to
7916       ;;    'kill-region'; if it was, then the new text is appended to
7917       ;;    the previous text; if not, then a different function,
7918       ;;    'kill-new', is called.
7919 @end group
7921 @group
7922       ;;    The 'kill-append' function concatenates the new string and
7923       ;;    the old.  The 'kill-new' function inserts text into a new
7924       ;;    item in the kill ring.
7925 @end group
7927 @group
7928       ;;    'when' is an 'if' without an else-part.  The second 'when'
7929       ;;    again checks whether the current string exists; in
7930       ;;    addition, it checks whether the previous command was
7931       ;;    another call to 'kill-region'.  If one or the other
7932       ;;    condition is true, then it sets the current command to
7933       ;;    be 'kill-region'.
7934 @end group
7935 @group
7936       (let ((string (filter-buffer-substring beg end t)))
7937         (when string                    ;STRING is nil if BEG = END
7938           ;; Add that string to the kill ring, one way or another.
7939           (if (eq last-command 'kill-region)
7940 @end group
7941 @group
7942               ;;    @minus{} 'yank-handler' is an optional argument to
7943               ;;    'kill-region' that tells the 'kill-append' and
7944               ;;    'kill-new' functions how deal with properties
7945               ;;    added to the text, such as 'bold' or 'italics'.
7946               (kill-append string (< end beg) yank-handler)
7947             (kill-new string nil yank-handler)))
7948         (when (or string (eq last-command 'kill-region))
7949           (setq this-command 'kill-region))
7950         nil)
7951 @end group
7953 @group
7954     ;;  @bullet{} The third argument to 'condition-case' tells the interpreter
7955     ;;    what to do with an error.
7956 @end group
7957 @group
7958     ;;    The third argument has a conditions part and a body part.
7959     ;;    If the conditions are met (in this case,
7960     ;;             if text or buffer are read-only)
7961     ;;    then the body is executed.
7962 @end group
7963 @group
7964     ;;    The first part of the third argument is the following:
7965     ((buffer-read-only text-read-only) ;; the if-part
7966      ;; @dots{}  the then-part
7967      (copy-region-as-kill beg end)
7968 @end group
7969 @group
7970      ;;    Next, also as part of the then-part, set this-command, so
7971      ;;    it will be set in an error
7972      (setq this-command 'kill-region)
7973      ;;    Finally, in the then-part, send a message if you may copy
7974      ;;    the text to the kill ring without signaling an error, but
7975      ;;    don't if you may not.
7976 @end group
7977 @group
7978      (if kill-read-only-ok
7979          (progn (message "Read only text copied to kill ring") nil)
7980        (barf-if-buffer-read-only)
7981        ;; If the buffer isn't read-only, the text is.
7982        (signal 'text-read-only (list (current-buffer)))))
7983 @end group
7984 @end smallexample
7986 @ignore
7987 @c v 21
7988 @smallexample
7989 @group
7990 (defun kill-region (beg end)
7991   "Kill between point and mark.
7992 The text is deleted but saved in the kill ring."
7993   (interactive "r")
7994 @end group
7996 @group
7997   ;; 1. 'condition-case' takes three arguments.
7998   ;;    If the first argument is nil, as it is here,
7999   ;;    information about the error signal is not
8000   ;;    stored for use by another function.
8001   (condition-case nil
8002 @end group
8004 @group
8005       ;; 2. The second argument to 'condition-case'
8006       ;;    tells the Lisp interpreter what to do when all goes well.
8007 @end group
8009 @group
8010       ;;    The 'delete-and-extract-region' function usually does the
8011       ;;    work.  If the beginning and ending of the region are both
8012       ;;    the same, then the variable 'string' will be empty, or nil
8013       (let ((string (delete-and-extract-region beg end)))
8014 @end group
8016 @group
8017         ;; 'when' is an 'if' clause that cannot take an 'else-part'.
8018         ;; Emacs normally sets the value of 'last-command' to the
8019         ;; previous command.
8020 @end group
8021 @group
8022         ;; 'kill-append' concatenates the new string and the old.
8023         ;; 'kill-new' inserts text into a new item in the kill ring.
8024         (when string
8025           (if (eq last-command 'kill-region)
8026               ;; if true, prepend string
8027               (kill-append string (< end beg))
8028             (kill-new string)))
8029         (setq this-command 'kill-region))
8030 @end group
8032 @group
8033     ;; 3. The third argument to 'condition-case' tells the interpreter
8034     ;;    what to do with an error.
8035 @end group
8036 @group
8037     ;;    The third argument has a conditions part and a body part.
8038     ;;    If the conditions are met (in this case,
8039     ;;             if text or buffer are read-only)
8040     ;;    then the body is executed.
8041 @end group
8042 @group
8043     ((buffer-read-only text-read-only) ;; this is the if-part
8044      ;; then...
8045      (copy-region-as-kill beg end)
8046 @end group
8047 @group
8048      (if kill-read-only-ok            ;; usually this variable is nil
8049          (message "Read only text copied to kill ring")
8050        ;; or else, signal an error if the buffer is read-only;
8051        (barf-if-buffer-read-only)
8052        ;; and, in any case, signal that the text is read-only.
8053        (signal 'text-read-only (list (current-buffer)))))))
8054 @end group
8055 @end smallexample
8056 @end ignore
8058 @node condition-case
8059 @subsection @code{condition-case}
8060 @findex condition-case
8062 As we have seen earlier (@pxref{Making Errors, , Generate an Error
8063 Message}), when the Emacs Lisp interpreter has trouble evaluating an
8064 expression, it provides you with help; in the jargon, this is called
8065 ``signaling an error''.  Usually, the computer stops the program and
8066 shows you a message.
8068 However, some programs undertake complicated actions.  They should not
8069 simply stop on an error.  In the @code{kill-region} function, the most
8070 likely error is that you will try to kill text that is read-only and
8071 cannot be removed.  So the @code{kill-region} function contains code
8072 to handle this circumstance.  This code, which makes up the body of
8073 the @code{kill-region} function, is inside of a @code{condition-case}
8074 special form.
8076 @need 800
8077 The template for @code{condition-case} looks like this:
8079 @smallexample
8080 @group
8081 (condition-case
8082   @var{var}
8083   @var{bodyform}
8084   @var{error-handler}@dots{})
8085 @end group
8086 @end smallexample
8088 The second argument, @var{bodyform}, is straightforward.  The
8089 @code{condition-case} special form causes the Lisp interpreter to
8090 evaluate the code in @var{bodyform}.  If no error occurs, the special
8091 form returns the code's value and produces the side-effects, if any.
8093 In short, the @var{bodyform} part of a @code{condition-case}
8094 expression determines what should happen when everything works
8095 correctly.
8097 However, if an error occurs, among its other actions, the function
8098 generating the error signal will define one or more error condition
8099 names.
8101 An error handler is the third argument to @code{condition-case}.
8102 An error handler has two parts, a @var{condition-name} and a
8103 @var{body}.  If the @var{condition-name} part of an error handler
8104 matches a condition name generated by an error, then the @var{body}
8105 part of the error handler is run.
8107 As you will expect, the @var{condition-name} part of an error handler
8108 may be either a single condition name or a list of condition names.
8110 Also, a complete @code{condition-case} expression may contain more
8111 than one error handler.  When an error occurs, the first applicable
8112 handler is run.
8114 Lastly, the first argument to the @code{condition-case} expression,
8115 the @var{var} argument, is sometimes bound to a variable that
8116 contains information about the error.  However, if that argument is
8117 nil, as is the case in @code{kill-region}, that information is
8118 discarded.
8120 @need 1200
8121 In brief, in the @code{kill-region} function, the code
8122 @code{condition-case} works like this:
8124 @smallexample
8125 @group
8126 @var{If no errors}, @var{run only this code}
8127     @var{but}, @var{if errors}, @var{run this other code}.
8128 @end group
8129 @end smallexample
8131 @ignore
8132 2006 Oct 24
8133 In Emacs 22,
8134 copy-region-as-kill is short, 12 lines, and uses
8135 filter-buffer-substring, which is longer, 39 lines
8136 and has delete-and-extract-region in it.
8137 delete-and-extract-region is written in C.
8139 see Initializing a Variable with @code{defvar}
8140 this is line 8054
8141 Initializing a Variable with @code{defvar} includes line 8350
8142 @end ignore
8144 @node Lisp macro
8145 @subsection Lisp macro
8146 @cindex Macro, lisp
8147 @cindex Lisp macro
8149 The part of the @code{condition-case} expression that is evaluated in
8150 the expectation that all goes well has a @code{when}.  The code uses
8151 @code{when} to determine whether the @code{string} variable points to
8152 text that exists.
8154 A @code{when} expression is simply a programmers' convenience.  It is
8155 an @code{if} without the possibility of an else clause.  In your mind,
8156 you can replace @code{when} with @code{if} and understand what goes
8157 on.  That is what the Lisp interpreter does.
8159 Technically speaking, @code{when} is a Lisp macro.  A Lisp macro
8160 enables you to define new control constructs and other language
8161 features.  It tells the interpreter how to compute another Lisp
8162 expression which will in turn compute the value.  In this case, the
8163 other expression is an @code{if} expression.
8165 The @code{kill-region} function definition also has an @code{unless}
8166 macro; it is the converse of @code{when}.  The @code{unless} macro is
8167 an @code{if} without a then clause
8169 For more about Lisp macros, see @ref{Macros, , Macros, elisp, The GNU
8170 Emacs Lisp Reference Manual}.  The C programming language also
8171 provides macros.  These are different, but also useful.
8173 @ignore
8174 We will briefly look at C macros in
8175 @ref{Digression into C}.
8176 @end ignore
8178 @need 1200
8179 Regarding the @code{when} macro, in the @code{condition-case}
8180 expression, when the string has content, then another conditional
8181 expression is executed.  This is an @code{if} with both a then-part
8182 and an else-part.
8184 @smallexample
8185 @group
8186 (if (eq last-command 'kill-region)
8187     (kill-append string (< end beg) yank-handler)
8188   (kill-new string nil yank-handler))
8189 @end group
8190 @end smallexample
8192 The then-part is evaluated if the previous command was another call to
8193 @code{kill-region}; if not, the else-part is evaluated.
8195 @code{yank-handler} is an optional argument to @code{kill-region} that
8196 tells the @code{kill-append} and @code{kill-new} functions how deal
8197 with properties added to the text, such as bold or italics.
8199 @code{last-command} is a variable that comes with Emacs that we have
8200 not seen before.  Normally, whenever a function is executed, Emacs
8201 sets the value of @code{last-command} to the previous command.
8203 @need 1200
8204 In this segment of the definition, the @code{if} expression checks
8205 whether the previous command was @code{kill-region}.  If it was,
8207 @smallexample
8208 (kill-append string (< end beg) yank-handler)
8209 @end smallexample
8211 @noindent
8212 concatenates a copy of the newly clipped text to the just previously
8213 clipped text in the kill ring.
8215 @node copy-region-as-kill
8216 @section @code{copy-region-as-kill}
8217 @findex copy-region-as-kill
8218 @findex nthcdr
8220 The @code{copy-region-as-kill} function copies a region of text from a
8221 buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8222 in the @code{kill-ring}.
8224 If you call @code{copy-region-as-kill} immediately after a
8225 @code{kill-region} command, Emacs appends the newly copied text to the
8226 previously copied text.  This means that if you yank back the text, you
8227 get it all, from both this and the previous operation.  On the other
8228 hand, if some other command precedes the @code{copy-region-as-kill},
8229 the function copies the text into a separate entry in the kill ring.
8231 @menu
8232 * Complete copy-region-as-kill::  The complete function definition.
8233 * copy-region-as-kill body::      The body of @code{copy-region-as-kill}.
8234 @end menu
8236 @ifnottex
8237 @node Complete copy-region-as-kill
8238 @unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8239 @end ifnottex
8241 @need 1200
8242 Here is the complete text of the version 22 @code{copy-region-as-kill}
8243 function:
8245 @smallexample
8246 @group
8247 (defun copy-region-as-kill (beg end)
8248   "Save the region as if killed, but don't kill it.
8249 In Transient Mark mode, deactivate the mark.
8250 If `interprogram-cut-function' is non-nil, also save the text for a window
8251 system cut and paste."
8252   (interactive "r")
8253 @end group
8254 @group
8255   (if (eq last-command 'kill-region)
8256       (kill-append (filter-buffer-substring beg end) (< end beg))
8257     (kill-new (filter-buffer-substring beg end)))
8258 @end group
8259 @group
8260   (if transient-mark-mode
8261       (setq deactivate-mark t))
8262   nil)
8263 @end group
8264 @end smallexample
8266 @need 800
8267 As usual, this function can be divided into its component parts:
8269 @smallexample
8270 @group
8271 (defun copy-region-as-kill (@var{argument-list})
8272   "@var{documentation}@dots{}"
8273   (interactive "r")
8274   @var{body}@dots{})
8275 @end group
8276 @end smallexample
8278 The arguments are @code{beg} and @code{end} and the function is
8279 interactive with @code{"r"}, so the two arguments must refer to the
8280 beginning and end of the region.  If you have been reading through this
8281 document from the beginning, understanding these parts of a function is
8282 almost becoming routine.
8284 The documentation is somewhat confusing unless you remember that the
8285 word ``kill'' has a meaning different from usual.  The Transient Mark
8286 and @code{interprogram-cut-function} comments explain certain
8287 side-effects.
8289 After you once set a mark, a buffer always contains a region.  If you
8290 wish, you can use Transient Mark mode to highlight the region
8291 temporarily.  (No one wants to highlight the region all the time, so
8292 Transient Mark mode highlights it only at appropriate times.  Many
8293 people turn off Transient Mark mode, so the region is never
8294 highlighted.)
8296 Also, a windowing system allows you to copy, cut, and paste among
8297 different programs.  In the X windowing system, for example, the
8298 @code{interprogram-cut-function} function is @code{x-select-text},
8299 which works with the windowing system's equivalent of the Emacs kill
8300 ring.
8302 The body of the @code{copy-region-as-kill} function starts with an
8303 @code{if} clause.  What this clause does is distinguish between two
8304 different situations: whether or not this command is executed
8305 immediately after a previous @code{kill-region} command.  In the first
8306 case, the new region is appended to the previously copied text.
8307 Otherwise, it is inserted into the beginning of the kill ring as a
8308 separate piece of text from the previous piece.
8310 The last two lines of the function prevent the region from lighting up
8311 if Transient Mark mode is turned on.
8313 The body of @code{copy-region-as-kill} merits discussion in detail.
8315 @node copy-region-as-kill body
8316 @subsection The Body of @code{copy-region-as-kill}
8318 The @code{copy-region-as-kill} function works in much the same way as
8319 the @code{kill-region} function.  Both are written so that two or more
8320 kills in a row combine their text into a single entry.  If you yank
8321 back the text from the kill ring, you get it all in one piece.
8322 Moreover, kills that kill forward from the current position of the
8323 cursor are added to the end of the previously copied text and commands
8324 that copy text backwards add it to the beginning of the previously
8325 copied text.  This way, the words in the text stay in the proper
8326 order.
8328 Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8329 use of the @code{last-command} variable that keeps track of the
8330 previous Emacs command.
8332 @menu
8333 * last-command & this-command::
8334 * kill-append function::
8335 * kill-new function::
8336 @end menu
8338 @ifnottex
8339 @node last-command & this-command
8340 @unnumberedsubsubsec @code{last-command} and @code{this-command}
8341 @end ifnottex
8343 Normally, whenever a function is executed, Emacs sets the value of
8344 @code{this-command} to the function being executed (which in this case
8345 would be @code{copy-region-as-kill}).  At the same time, Emacs sets
8346 the value of @code{last-command} to the previous value of
8347 @code{this-command}.
8349 In the first part of the body of the @code{copy-region-as-kill}
8350 function, an @code{if} expression determines whether the value of
8351 @code{last-command} is @code{kill-region}.  If so, the then-part of
8352 the @code{if} expression is evaluated; it uses the @code{kill-append}
8353 function to concatenate the text copied at this call to the function
8354 with the text already in the first element (the @sc{car}) of the kill
8355 ring.  On the other hand, if the value of @code{last-command} is not
8356 @code{kill-region}, then the @code{copy-region-as-kill} function
8357 attaches a new element to the kill ring using the @code{kill-new}
8358 function.
8360 @need 1250
8361 The @code{if} expression reads as follows; it uses @code{eq}:
8363 @smallexample
8364 @group
8365   (if (eq last-command 'kill-region)
8366       ;; @r{then-part}
8367       (kill-append  (filter-buffer-substring beg end) (< end beg))
8368     ;; @r{else-part}
8369     (kill-new  (filter-buffer-substring beg end)))
8370 @end group
8371 @end smallexample
8373 @findex filter-buffer-substring
8374 (The @code{filter-buffer-substring} function returns a filtered
8375 substring of the buffer, if any.  Optionally---the arguments are not
8376 here, so neither is done---the function may delete the initial text or
8377 return the text without its properties; this function is a replacement
8378 for the older @code{buffer-substring} function, which came before text
8379 properties were implemented.)
8381 @findex eq @r{(example of use)}
8382 @noindent
8383 The @code{eq} function tests whether its first argument is the same Lisp
8384 object as its second argument.  The @code{eq} function is similar to the
8385 @code{equal} function in that it is used to test for equality, but
8386 differs in that it determines whether two representations are actually
8387 the same object inside the computer, but with different names.
8388 @code{equal} determines whether the structure and contents of two
8389 expressions are the same.
8391 If the previous command was @code{kill-region}, then the Emacs Lisp
8392 interpreter calls the @code{kill-append} function
8394 @node kill-append function
8395 @unnumberedsubsubsec The @code{kill-append} function
8396 @findex kill-append
8398 @need 800
8399 The @code{kill-append} function looks like this:
8401 @c in GNU Emacs 22
8402 @smallexample
8403 @group
8404 (defun kill-append (string before-p &optional yank-handler)
8405   "Append STRING to the end of the latest kill in the kill ring.
8406 If BEFORE-P is non-nil, prepend STRING to the kill.
8407 @dots{} "
8408   (let* ((cur (car kill-ring)))
8409     (kill-new (if before-p (concat string cur) (concat cur string))
8410               (or (= (length cur) 0)
8411                   (equal yank-handler
8412                          (get-text-property 0 'yank-handler cur)))
8413               yank-handler)))
8414 @end group
8415 @end smallexample
8417 @ignore
8418 was:
8419 (defun kill-append (string before-p)
8420   "Append STRING to the end of the latest kill in the kill ring.
8421 If BEFORE-P is non-nil, prepend STRING to the kill.
8422 If `interprogram-cut-function' is set, pass the resulting kill to
8423 it."
8424   (kill-new (if before-p
8425                 (concat string (car kill-ring))
8426               (concat (car kill-ring) string))
8427             t))
8428 @end ignore
8430 @noindent
8431 The @code{kill-append} function is fairly straightforward.  It uses
8432 the @code{kill-new} function, which we will discuss in more detail in
8433 a moment.
8435 (Also, the function provides an optional argument called
8436 @code{yank-handler}; when invoked, this argument tells the function
8437 how to deal with properties added to the text, such as bold or
8438 italics.)
8440 @c !!! bug in GNU Emacs 22 version of  kill-append ?
8441 It has a @code{let*} function to set the value of the first element of
8442 the kill ring to @code{cur}.  (I do not know why the function does not
8443 use @code{let} instead; only one value is set in the expression.
8444 Perhaps this is a bug that produces no problems?)
8446 Consider the conditional that is one of the two arguments to
8447 @code{kill-new}.  It uses @code{concat} to concatenate the new text to
8448 the @sc{car} of the kill ring.  Whether it prepends or appends the
8449 text depends on the results of an @code{if} expression:
8451 @smallexample
8452 @group
8453 (if before-p                            ; @r{if-part}
8454     (concat string cur)                 ; @r{then-part}
8455   (concat cur string))                  ; @r{else-part}
8456 @end group
8457 @end smallexample
8459 @noindent
8460 If the region being killed is before the region that was killed in the
8461 last command, then it should be prepended before the material that was
8462 saved in the previous kill; and conversely, if the killed text follows
8463 what was just killed, it should be appended after the previous text.
8464 The @code{if} expression depends on the predicate @code{before-p} to
8465 decide whether the newly saved text should be put before or after the
8466 previously saved text.
8468 The symbol @code{before-p} is the name of one of the arguments to
8469 @code{kill-append}.  When the @code{kill-append} function is
8470 evaluated, it is bound to the value returned by evaluating the actual
8471 argument.  In this case, this is the expression @code{(< end beg)}.
8472 This expression does not directly determine whether the killed text in
8473 this command is located before or after the kill text of the last
8474 command; what it does is determine whether the value of the variable
8475 @code{end} is less than the value of the variable @code{beg}.  If it
8476 is, it means that the user is most likely heading towards the
8477 beginning of the buffer.  Also, the result of evaluating the predicate
8478 expression, @code{(< end beg)}, will be true and the text will be
8479 prepended before the previous text.  On the other hand, if the value of
8480 the variable @code{end} is greater than the value of the variable
8481 @code{beg}, the text will be appended after the previous text.
8483 @need 800
8484 When the newly saved text will be prepended, then the string with the new
8485 text will be concatenated before the old text:
8487 @smallexample
8488 (concat string cur)
8489 @end smallexample
8491 @need 1200
8492 @noindent
8493 But if the text will be appended, it will be concatenated
8494 after the old text:
8496 @smallexample
8497 (concat cur string))
8498 @end smallexample
8500 To understand how this works, we first need to review the
8501 @code{concat} function.  The @code{concat} function links together or
8502 unites two strings of text.  The result is a string.  For example:
8504 @smallexample
8505 @group
8506 (concat "abc" "def")
8507      @result{} "abcdef"
8508 @end group
8510 @group
8511 (concat "new "
8512         (car '("first element" "second element")))
8513      @result{} "new first element"
8515 (concat (car
8516         '("first element" "second element")) " modified")
8517      @result{} "first element modified"
8518 @end group
8519 @end smallexample
8521 We can now make sense of @code{kill-append}: it modifies the contents
8522 of the kill ring.  The kill ring is a list, each element of which is
8523 saved text.  The @code{kill-append} function uses the @code{kill-new}
8524 function which in turn uses the @code{setcar} function.
8526 @node kill-new function
8527 @unnumberedsubsubsec The @code{kill-new} function
8528 @findex kill-new
8530 @need 1200
8531 In version 22 the @code{kill-new} function looks like this:
8533 @smallexample
8534 @group
8535 (defun kill-new (string &optional replace yank-handler)
8536   "Make STRING the latest kill in the kill ring.
8537 Set `kill-ring-yank-pointer' to point to it.
8539 If `interprogram-cut-function' is non-nil, apply it to STRING.
8540 Optional second argument REPLACE non-nil means that STRING will replace
8541 the front of the kill ring, rather than being added to the list.
8542 @dots{}"
8543 @end group
8544 @group
8545   (if (> (length string) 0)
8546       (if yank-handler
8547           (put-text-property 0 (length string)
8548                              'yank-handler yank-handler string))
8549     (if yank-handler
8550         (signal 'args-out-of-range
8551                 (list string "yank-handler specified for empty string"))))
8552 @end group
8553 @group
8554   (if (fboundp 'menu-bar-update-yank-menu)
8555       (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8556 @end group
8557 @group
8558   (if (and replace kill-ring)
8559       (setcar kill-ring string)
8560     (push string kill-ring)
8561     (if (> (length kill-ring) kill-ring-max)
8562         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8563 @end group
8564 @group
8565   (setq kill-ring-yank-pointer kill-ring)
8566   (if interprogram-cut-function
8567       (funcall interprogram-cut-function string (not replace))))
8568 @end group
8569 @end smallexample
8570 @ignore
8571 was:
8572 (defun kill-new (string &optional replace)
8573   "Make STRING the latest kill in the kill ring.
8574 Set the kill-ring-yank pointer to point to it.
8575 If `interprogram-cut-function' is non-nil, apply it to STRING.
8576 Optional second argument REPLACE non-nil means that STRING will replace
8577 the front of the kill ring, rather than being added to the list."
8578   (and (fboundp 'menu-bar-update-yank-menu)
8579        (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8580   (if (and replace kill-ring)
8581       (setcar kill-ring string)
8582     (setq kill-ring (cons string kill-ring))
8583     (if (> (length kill-ring) kill-ring-max)
8584         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8585   (setq kill-ring-yank-pointer kill-ring)
8586   (if interprogram-cut-function
8587       (funcall interprogram-cut-function string (not replace))))
8588 @end ignore
8590 (Notice that the function is not interactive.)
8592 As usual, we can look at this function in parts.
8594 The function definition has an optional @code{yank-handler} argument,
8595 which when invoked tells the function how to deal with properties
8596 added to the text, such as bold or italics.  We will skip that.
8598 @need 1200
8599 The first line of the documentation makes sense:
8601 @smallexample
8602 Make STRING the latest kill in the kill ring.
8603 @end smallexample
8605 @noindent
8606 Let's skip over the rest of the documentation for the moment.
8608 @noindent
8609 Also, let's skip over the initial @code{if} expression and those lines
8610 of code involving @code{menu-bar-update-yank-menu}.  We will explain
8611 them below.
8613 @need 1200
8614 The critical lines are these:
8616 @smallexample
8617 @group
8618   (if (and replace kill-ring)
8619       ;; @r{then}
8620       (setcar kill-ring string)
8621 @end group
8622 @group
8623     ;; @r{else}
8624     (push string kill-ring)
8625 @end group
8626 @group
8627     (if (> (length kill-ring) kill-ring-max)
8628         ;; @r{avoid overly long kill ring}
8629         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8630 @end group
8631 @group
8632   (setq kill-ring-yank-pointer kill-ring)
8633   (if interprogram-cut-function
8634       (funcall interprogram-cut-function string (not replace))))
8635 @end group
8636 @end smallexample
8638 The conditional test is @w{@code{(and replace kill-ring)}}.
8639 This will be true when two conditions are met:  the kill ring has
8640 something in it, and the @code{replace} variable is true.
8642 @need 1250
8643 When the @code{kill-append} function sets @code{replace} to be true
8644 and when the kill ring has at least one item in it, the @code{setcar}
8645 expression is executed:
8647 @smallexample
8648 (setcar kill-ring string)
8649 @end smallexample
8651 The @code{setcar} function actually changes the first element of the
8652 @code{kill-ring} list to the value of @code{string}.  It replaces the
8653 first element.
8655 @need 1250
8656 On the other hand, if the kill ring is empty, or replace is false, the
8657 else-part of the condition is executed:
8659 @smallexample
8660 (push string kill-ring)
8661 @end smallexample
8663 @noindent
8664 @need 1250
8665 @code{push} puts its first argument onto the second.  It is similar to
8666 the older
8668 @smallexample
8669 (setq kill-ring (cons string kill-ring))
8670 @end smallexample
8672 @noindent
8673 @need 1250
8674 or the newer
8676 @smallexample
8677 (add-to-list kill-ring string)
8678 @end smallexample
8680 @noindent
8681 When it is false, the expression first constructs a new version of the
8682 kill ring by prepending @code{string} to the existing kill ring as a
8683 new element (that is what the @code{push} does).  Then it executes a
8684 second @code{if} clause.  This second @code{if} clause keeps the kill
8685 ring from growing too long.
8687 Let's look at these two expressions in order.
8689 The @code{push} line of the else-part sets the new value of the kill
8690 ring to what results from adding the string being killed to the old
8691 kill ring.
8693 We can see how this works with an example.
8695 @need 800
8696 First,
8698 @smallexample
8699 (setq example-list '("here is a clause" "another clause"))
8700 @end smallexample
8702 @need 1200
8703 @noindent
8704 After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8705 @code{example-list} and see what it returns:
8707 @smallexample
8708 @group
8709 example-list
8710      @result{} ("here is a clause" "another clause")
8711 @end group
8712 @end smallexample
8714 @need 1200
8715 @noindent
8716 Now, we can add a new element on to this list by evaluating the
8717 following expression:
8718 @findex push, @r{example}
8720 @smallexample
8721 (push "a third clause" example-list)
8722 @end smallexample
8724 @need 800
8725 @noindent
8726 When we evaluate @code{example-list}, we find its value is:
8728 @smallexample
8729 @group
8730 example-list
8731      @result{} ("a third clause" "here is a clause" "another clause")
8732 @end group
8733 @end smallexample
8735 @noindent
8736 Thus, the third clause is added to the list by @code{push}.
8738 @need 1200
8739 Now for the second part of the @code{if} clause.  This expression
8740 keeps the kill ring from growing too long.  It looks like this:
8742 @smallexample
8743 @group
8744 (if (> (length kill-ring) kill-ring-max)
8745     (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8746 @end group
8747 @end smallexample
8749 The code checks whether the length of the kill ring is greater than
8750 the maximum permitted length.  This is the value of
8751 @code{kill-ring-max} (which is 60, by default).  If the length of the
8752 kill ring is too long, then this code sets the last element of the
8753 kill ring to @code{nil}.  It does this by using two functions,
8754 @code{nthcdr} and @code{setcdr}.
8756 We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8757 It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8758 @sc{car} of a list.  In this case, however, @code{setcdr} will not be
8759 setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8760 function is used to cause it to set the @sc{cdr} of the next to last
8761 element of the kill ring---this means that since the @sc{cdr} of the
8762 next to last element is the last element of the kill ring, it will set
8763 the last element of the kill ring.
8765 @findex nthcdr, @r{example}
8766 The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8767 list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8768 @dots{}  It does this @var{N} times and returns the results.
8769 (@xref{nthcdr, , @code{nthcdr}}.)
8771 @findex setcdr, @r{example}
8772 Thus, if we had a four element list that was supposed to be three
8773 elements long, we could set the @sc{cdr} of the next to last element
8774 to @code{nil}, and thereby shorten the list.  (If you set the last
8775 element to some other value than @code{nil}, which you could do, then
8776 you would not have shortened the list.  @xref{setcdr, ,
8777 @code{setcdr}}.)
8779 You can see shortening by evaluating the following three expressions
8780 in turn.  First set the value of @code{trees} to @code{(maple oak pine
8781 birch)}, then set the @sc{cdr} of its second @sc{cdr} to @code{nil}
8782 and then find the value of @code{trees}:
8784 @smallexample
8785 @group
8786 (setq trees '(maple oak pine birch))
8787      @result{} (maple oak pine birch)
8788 @end group
8790 @group
8791 (setcdr (nthcdr 2 trees) nil)
8792      @result{} nil
8794 trees
8795      @result{} (maple oak pine)
8796 @end group
8797 @end smallexample
8799 @noindent
8800 (The value returned by the @code{setcdr} expression is @code{nil} since
8801 that is what the @sc{cdr} is set to.)
8803 To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8804 @sc{cdr} a number of times that is one less than the maximum permitted
8805 size of the kill ring and @code{setcdr} sets the @sc{cdr} of that
8806 element (which will be the rest of the elements in the kill ring) to
8807 @code{nil}.  This prevents the kill ring from growing too long.
8809 @need 800
8810 The next to last expression in the @code{kill-new} function is
8812 @smallexample
8813 (setq kill-ring-yank-pointer kill-ring)
8814 @end smallexample
8816 The @code{kill-ring-yank-pointer} is a global variable that is set to be
8817 the @code{kill-ring}.
8819 Even though the @code{kill-ring-yank-pointer} is called a
8820 @samp{pointer}, it is a variable just like the kill ring.  However, the
8821 name has been chosen to help humans understand how the variable is used.
8823 @need 1200
8824 Now, to return to an early expression in the body of the function:
8826 @smallexample
8827 @group
8828   (if (fboundp 'menu-bar-update-yank-menu)
8829        (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8830 @end group
8831 @end smallexample
8833 @noindent
8834 It starts with an @code{if} expression
8836 In this case, the expression tests first to see whether
8837 @code{menu-bar-update-yank-menu} exists as a function, and if so,
8838 calls it.  The @code{fboundp} function returns true if the symbol it
8839 is testing has a function definition that is not void.  If the
8840 symbol's function definition were void, we would receive an error
8841 message, as we did when we created errors intentionally (@pxref{Making
8842 Errors, , Generate an Error Message}).
8844 @noindent
8845 The then-part contains an expression whose first element is the
8846 function @code{and}.
8848 @findex and
8849 The @code{and} special form evaluates each of its arguments until one
8850 of the arguments returns a value of @code{nil}, in which case the
8851 @code{and} expression returns @code{nil}; however, if none of the
8852 arguments returns a value of @code{nil}, the value resulting from
8853 evaluating the last argument is returned.  (Since such a value is not
8854 @code{nil}, it is considered true in Emacs Lisp.)  In other words, an
8855 @code{and} expression returns a true value only if all its arguments
8856 are true.  (@xref{Second Buffer Related Review}.)
8858 The expression determines whether the second argument to
8859 @code{menu-bar-update-yank-menu} is true or not.
8860 @ignore
8861     ;; If we're supposed to be extending an existing string, and that
8862     ;; string really is at the front of the menu, then update it in place.
8863 @end ignore
8865 @code{menu-bar-update-yank-menu} is one of the functions that make it
8866 possible to use the ``Select and Paste'' menu in the Edit item of a menu
8867 bar; using a mouse, you can look at the various pieces of text you
8868 have saved and select one piece to paste.
8870 The last expression in the @code{kill-new} function adds the newly
8871 copied string to whatever facility exists for copying and pasting
8872 among different programs running in a windowing system.  In the X
8873 Windowing system, for example, the @code{x-select-text} function takes
8874 the string and stores it in memory operated by X@.  You can paste the
8875 string in another program, such as an Xterm.
8877 @need 1200
8878 The expression looks like this:
8880 @smallexample
8881 @group
8882   (if interprogram-cut-function
8883       (funcall interprogram-cut-function string (not replace))))
8884 @end group
8885 @end smallexample
8887 If an @code{interprogram-cut-function} exists, then Emacs executes
8888 @code{funcall}, which in turn calls its first argument as a function
8889 and passes the remaining arguments to it.  (Incidentally, as far as I
8890 can see, this @code{if} expression could be replaced by an @code{and}
8891 expression similar to the one in the first part of the function.)
8893 We are not going to discuss windowing systems and other programs
8894 further, but merely note that this is a mechanism that enables GNU
8895 Emacs to work easily and well with other programs.
8897 This code for placing text in the kill ring, either concatenated with
8898 an existing element or as a new element, leads us to the code for
8899 bringing back text that has been cut out of the buffer---the yank
8900 commands.  However, before discussing the yank commands, it is better
8901 to learn how lists are implemented in a computer.  This will make
8902 clear such mysteries as the use of the term ``pointer''.  But before
8903 that, we will digress into C.
8905 @ignore
8906 @c is this true in Emacs 22?   Does not seems to be
8908   (If the @w{@code{(< end beg))}}
8909 expression is true, @code{kill-append} prepends the string to the just
8910 previously clipped text.  For a detailed discussion, see
8911 @ref{kill-append function, , The @code{kill-append} function}.)
8913 If you then yank back the text, i.e., paste it, you get both
8914 pieces of text at once.  That way, if you delete two words in a row,
8915 and then yank them back, you get both words, in their proper order,
8916 with one yank.  (The @w{@code{(< end beg))}} expression makes sure the
8917 order is correct.)
8919 On the other hand, if the previous command is not @code{kill-region},
8920 then the @code{kill-new} function is called, which adds the text to
8921 the kill ring as the latest item, and sets the
8922 @code{kill-ring-yank-pointer} variable to point to it.
8923 @end ignore
8924 @ignore
8926 @c Evidently, changed for Emacs 22. The zap-to-char command does not
8927 @c use the delete-and-extract-region function
8929 2006 Oct 26, the Digression into C is now OK but should come after
8930 copy-region-as-kill and filter-buffer-substring
8932 2006 Oct 24
8933 In Emacs 22,
8934 copy-region-as-kill is short, 12 lines, and uses
8935 filter-buffer-substring, which is longer, 39 lines
8936 and has delete-and-extract-region in it.
8937 delete-and-extract-region is written in C.
8939 see Initializing a Variable with @code{defvar}
8940 @end ignore
8942 @node Digression into C
8943 @section Digression into C
8944 @findex delete-and-extract-region
8945 @cindex C, a digression into
8946 @cindex Digression into C
8948 The @code{copy-region-as-kill} function (@pxref{copy-region-as-kill, ,
8949 @code{copy-region-as-kill}}) uses the @code{filter-buffer-substring}
8950 function, which in turn uses the @code{delete-and-extract-region}
8951 function.  It removes the contents of a region and you cannot get them
8952 back.
8954 Unlike the other code discussed here, the
8955 @code{delete-and-extract-region} function is not written in Emacs
8956 Lisp; it is written in C and is one of the primitives of the GNU Emacs
8957 system.  Since it is very simple, I will digress briefly from Lisp and
8958 describe it here.
8960 @c GNU Emacs 24  in src/editfns.c
8961 @c the DEFUN for  delete-and-extract-region
8963 @need 1500
8964 Like many of the other Emacs primitives,
8965 @code{delete-and-extract-region} is written as an instance of a C
8966 macro, a macro being a template for code.  The complete macro looks
8967 like this:
8969 @smallexample
8970 @group
8971 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
8972        Sdelete_and_extract_region, 2, 2, 0,
8973        doc: /* Delete the text between START and END and return it.  */)
8974        (Lisp_Object start, Lisp_Object end)
8976   validate_region (&start, &end);
8977   if (XINT (start) == XINT (end))
8978     return empty_unibyte_string;
8979   return del_range_1 (XINT (start), XINT (end), 1, 1);
8981 @end group
8982 @end smallexample
8984 Without going into the details of the macro writing process, let me
8985 point out that this macro starts with the word @code{DEFUN}.  The word
8986 @code{DEFUN} was chosen since the code serves the same purpose as
8987 @code{defun} does in Lisp.  (The @code{DEFUN} C macro is defined in
8988 @file{emacs/src/lisp.h}.)
8990 The word @code{DEFUN} is followed by seven parts inside of
8991 parentheses:
8993 @itemize @bullet
8994 @item
8995 The first part is the name given to the function in Lisp,
8996 @code{delete-and-extract-region}.
8998 @item
8999 The second part is the name of the function in C,
9000 @code{Fdelete_and_extract_region}.  By convention, it starts with
9001 @samp{F}.  Since C does not use hyphens in names, underscores are used
9002 instead.
9004 @item
9005 The third part is the name for the C constant structure that records
9006 information on this function for internal use.  It is the name of the
9007 function in C but begins with an @samp{S} instead of an @samp{F}.
9009 @item
9010 The fourth and fifth parts specify the minimum and maximum number of
9011 arguments the function can have.  This function demands exactly 2
9012 arguments.
9014 @item
9015 The sixth part is nearly like the argument that follows the
9016 @code{interactive} declaration in a function written in Lisp: a letter
9017 followed, perhaps, by a prompt.  The only difference from Lisp is
9018 when the macro is called with no arguments.  Then you write a @code{0}
9019 (which is a null string), as in this macro.
9021 If you were to specify arguments, you would place them between
9022 quotation marks.  The C macro for @code{goto-char} includes
9023 @code{"NGoto char: "} in this position to indicate that the function
9024 expects a raw prefix, in this case, a numerical location in a buffer,
9025 and provides a prompt.
9027 @item
9028 The seventh part is a documentation string, just like the one for a
9029 function written in Emacs Lisp.  This is written as a C comment.  (When
9030 you build Emacs, the program @command{lib-src/make-docfile} extracts
9031 these comments and uses them to make the documentation.)
9032 @end itemize
9034 @need 1200
9035 In a C macro, the formal parameters come next, with a statement of
9036 what kind of object they are, followed by the body
9037 of the macro.  For @code{delete-and-extract-region} the body
9038 consists of the following four lines:
9040 @smallexample
9041 @group
9042 validate_region (&start, &end);
9043 if (XINT (start) == XINT (end))
9044   return empty_unibyte_string;
9045 return del_range_1 (XINT (start), XINT (end), 1, 1);
9046 @end group
9047 @end smallexample
9049 The @code{validate_region} function checks whether the values
9050 passed as the beginning and end of the region are the proper type and
9051 are within range.  If the beginning and end positions are the same,
9052 then return an empty string.
9054 The @code{del_range_1} function actually deletes the text.  It is a
9055 complex function we will not look into.  It updates the buffer and
9056 does other things.  However, it is worth looking at the two arguments
9057 passed to @code{del_range_1}.  These are @w{@code{XINT (start)}} and
9058 @w{@code{XINT (end)}}.
9060 As far as the C language is concerned, @code{start} and @code{end} are
9061 two integers that mark the beginning and end of the region to be
9062 deleted@footnote{More precisely, and requiring more expert knowledge
9063 to understand, the two integers are of type @code{Lisp_Object}, which can
9064 also be a C union instead of an integer type.}.
9066 Integer widths depend on the machine, and are typically 32 or 64 bits.
9067 A few of the bits are used to specify the type of information; the
9068 remaining bits are used as content.
9070 @samp{XINT} is a C macro that extracts the relevant number from the
9071 longer collection of bits; the type bits are discarded.
9073 @need 800
9074 The command in @code{delete-and-extract-region} looks like this:
9076 @smallexample
9077 del_range_1 (XINT (start), XINT (end), 1, 1);
9078 @end smallexample
9080 @noindent
9081 It deletes the region between the beginning position, @code{start},
9082 and the ending position, @code{end}.
9084 From the point of view of the person writing Lisp, Emacs is all very
9085 simple; but hidden underneath is a great deal of complexity to make it
9086 all work.
9088 @node defvar
9089 @section Initializing a Variable with @code{defvar}
9090 @findex defvar
9091 @cindex Initializing a variable
9092 @cindex Variable initialization
9094 @ignore
9095 2006 Oct 24
9096 In Emacs 22,
9097 copy-region-as-kill is short, 12 lines, and uses
9098 filter-buffer-substring, which is longer, 39 lines
9099 and has delete-and-extract-region in it.
9100 delete-and-extract-region is written in C.
9102 see Initializing a Variable with @code{defvar}
9104 @end ignore
9106 The @code{copy-region-as-kill} function is written in Emacs Lisp.  Two
9107 functions within it, @code{kill-append} and @code{kill-new}, copy a
9108 region in a buffer and save it in a variable called the
9109 @code{kill-ring}.  This section describes how the @code{kill-ring}
9110 variable is created and initialized using the @code{defvar} special
9111 form.
9113 (Again we note that the term @code{kill-ring} is a misnomer.  The text
9114 that is clipped out of the buffer can be brought back; it is not a ring
9115 of corpses, but a ring of resurrectable text.)
9117 In Emacs Lisp, a variable such as the @code{kill-ring} is created and
9118 given an initial value by using the @code{defvar} special form.  The
9119 name comes from ``define variable''.
9121 The @code{defvar} special form is similar to @code{setq} in that it sets
9122 the value of a variable.  It is unlike @code{setq} in two ways: first,
9123 it only sets the value of the variable if the variable does not already
9124 have a value.  If the variable already has a value, @code{defvar} does
9125 not override the existing value.  Second, @code{defvar} has a
9126 documentation string.
9128 (There is a related macro, @code{defcustom}, designed for variables
9129 that people customize.  It has more features than @code{defvar}.
9130 (@xref{defcustom, , Setting Variables with @code{defcustom}}.)
9132 @menu
9133 * See variable current value::
9134 * defvar and asterisk::
9135 @end menu
9137 @ifnottex
9138 @node See variable current value
9139 @unnumberedsubsec Seeing the Current Value of a Variable
9140 @end ifnottex
9142 You can see the current value of a variable, any variable, by using
9143 the @code{describe-variable} function, which is usually invoked by
9144 typing @kbd{C-h v}.  If you type @kbd{C-h v} and then @code{kill-ring}
9145 (followed by @key{RET}) when prompted, you will see what is in your
9146 current kill ring---this may be quite a lot!  Conversely, if you have
9147 been doing nothing this Emacs session except read this document, you
9148 may have nothing in it.  Also, you will see the documentation for
9149 @code{kill-ring}:
9151 @smallexample
9152 @group
9153 Documentation:
9154 List of killed text sequences.
9155 Since the kill ring is supposed to interact nicely with cut-and-paste
9156 facilities offered by window systems, use of this variable should
9157 @end group
9158 @group
9159 interact nicely with `interprogram-cut-function' and
9160 `interprogram-paste-function'.  The functions `kill-new',
9161 `kill-append', and `current-kill' are supposed to implement this
9162 interaction; you may want to use them instead of manipulating the kill
9163 ring directly.
9164 @end group
9165 @end smallexample
9167 @need 800
9168 The kill ring is defined by a @code{defvar} in the following way:
9170 @smallexample
9171 @group
9172 (defvar kill-ring nil
9173   "List of killed text sequences.
9174 @dots{}")
9175 @end group
9176 @end smallexample
9178 @noindent
9179 In this variable definition, the variable is given an initial value of
9180 @code{nil}, which makes sense, since if you have saved nothing, you want
9181 nothing back if you give a @code{yank} command.  The documentation
9182 string is written just like the documentation string of a @code{defun}.
9183 As with the documentation string of the @code{defun}, the first line of
9184 the documentation should be a complete sentence, since some commands,
9185 like @code{apropos}, print only the first line of documentation.
9186 Succeeding lines should not be indented; otherwise they look odd when
9187 you use @kbd{C-h v} (@code{describe-variable}).
9189 @node defvar and asterisk
9190 @subsection @code{defvar} and an asterisk
9191 @findex defvar @r{for a user customizable variable}
9192 @findex defvar @r{with an asterisk}
9194 In the past, Emacs used the @code{defvar} special form both for
9195 internal variables that you would not expect a user to change and for
9196 variables that you do expect a user to change.  Although you can still
9197 use @code{defvar} for user customizable variables, please use
9198 @code{defcustom} instead, since it provides a path into
9199 the Customization commands.  (@xref{defcustom, , Specifying Variables
9200 using @code{defcustom}}.)
9202 When you specified a variable using the @code{defvar} special form,
9203 you could distinguish a variable that a user might want to change from
9204 others by typing an asterisk, @samp{*}, in the first column of its
9205 documentation string.  For example:
9207 @smallexample
9208 @group
9209 (defvar shell-command-default-error-buffer nil
9210   "*Buffer name for `shell-command' @dots{} error output.
9211 @dots{} ")
9212 @end group
9213 @end smallexample
9215 @findex set-variable
9216 @noindent
9217 You could (and still can) use the @code{set-variable} command to
9218 change the value of @code{shell-command-default-error-buffer}
9219 temporarily.  However, options set using @code{set-variable} are set
9220 only for the duration of your editing session.  The new values are not
9221 saved between sessions.  Each time Emacs starts, it reads the original
9222 value, unless you change the value within your @file{.emacs} file,
9223 either by setting it manually or by using @code{customize}.
9224 @xref{Emacs Initialization, , Your @file{.emacs} File}.
9226 For me, the major use of the @code{set-variable} command is to suggest
9227 variables that I might want to set in my @file{.emacs} file.  There
9228 are now more than 700 such variables, far too many to remember
9229 readily.  Fortunately, you can press @key{TAB} after calling the
9230 @code{M-x set-variable} command to see the list of variables.
9231 (@xref{Examining, , Examining and Setting Variables, emacs,
9232 The GNU Emacs Manual}.)
9234 @need 1250
9235 @node cons & search-fwd Review
9236 @section Review
9238 Here is a brief summary of some recently introduced functions.
9240 @table @code
9241 @item car
9242 @itemx cdr
9243 @code{car} returns the first element of a list; @code{cdr} returns the
9244 second and subsequent elements of a list.
9246 @need 1250
9247 For example:
9249 @smallexample
9250 @group
9251 (car '(1 2 3 4 5 6 7))
9252      @result{} 1
9253 (cdr '(1 2 3 4 5 6 7))
9254      @result{} (2 3 4 5 6 7)
9255 @end group
9256 @end smallexample
9258 @item cons
9259 @code{cons} constructs a list by prepending its first argument to its
9260 second argument.
9262 @need 1250
9263 For example:
9265 @smallexample
9266 @group
9267 (cons 1 '(2 3 4))
9268      @result{} (1 2 3 4)
9269 @end group
9270 @end smallexample
9272 @item funcall
9273 @code{funcall} evaluates its first argument as a function.  It passes
9274 its remaining arguments to its first argument.
9276 @item nthcdr
9277 Return the result of taking @sc{cdr} @var{n} times on a list.
9278 @iftex
9280 @tex
9281 $n^{th}$
9282 @end tex
9283 @code{cdr}.
9284 @end iftex
9285 The ``rest of the rest'', as it were.
9287 @need 1250
9288 For example:
9290 @smallexample
9291 @group
9292 (nthcdr 3 '(1 2 3 4 5 6 7))
9293      @result{} (4 5 6 7)
9294 @end group
9295 @end smallexample
9297 @item setcar
9298 @itemx setcdr
9299 @code{setcar} changes the first element of a list; @code{setcdr}
9300 changes the second and subsequent elements of a list.
9302 @need 1250
9303 For example:
9305 @smallexample
9306 @group
9307 (setq triple '(1 2 3))
9309 (setcar triple '37)
9311 triple
9312      @result{} (37 2 3)
9314 (setcdr triple '("foo" "bar"))
9316 triple
9317      @result{} (37 "foo" "bar")
9318 @end group
9319 @end smallexample
9321 @item progn
9322 Evaluate each argument in sequence and then return the value of the
9323 last.
9325 @need 1250
9326 For example:
9328 @smallexample
9329 @group
9330 (progn 1 2 3 4)
9331      @result{} 4
9332 @end group
9333 @end smallexample
9335 @item save-restriction
9336 Record whatever narrowing is in effect in the current buffer, if any,
9337 and restore that narrowing after evaluating the arguments.
9339 @item search-forward
9340 Search for a string, and if the string is found, move point.  With a
9341 regular expression, use the similar @code{re-search-forward}.
9342 (@xref{Regexp Search, , Regular Expression Searches}, for an
9343 explanation of regular expression patterns and searches.)
9345 @need 1250
9346 @noindent
9347 @code{search-forward} and @code{re-search-forward} take four
9348 arguments:
9350 @enumerate
9351 @item
9352 The string or regular expression to search for.
9354 @item
9355 Optionally, the limit of the search.
9357 @item
9358 Optionally, what to do if the search fails, return @code{nil} or an
9359 error message.
9361 @item
9362 Optionally, how many times to repeat the search; if negative, the
9363 search goes backwards.
9364 @end enumerate
9366 @item kill-region
9367 @itemx delete-and-extract-region
9368 @itemx copy-region-as-kill
9370 @code{kill-region} cuts the text between point and mark from the
9371 buffer and stores that text in the kill ring, so you can get it back
9372 by yanking.
9374 @code{copy-region-as-kill} copies the text between point and mark into
9375 the kill ring, from which you can get it by yanking.  The function
9376 does not cut or remove the text from the buffer.
9377 @end table
9379 @code{delete-and-extract-region} removes the text between point and
9380 mark from the buffer and throws it away.  You cannot get it back.
9381 (This is not an interactive command.)
9383 @need 1500
9384 @node search Exercises
9385 @section Searching Exercises
9387 @itemize @bullet
9388 @item
9389 Write an interactive function that searches for a string.  If the
9390 search finds the string, leave point after it and display a message
9391 that says ``Found!''.  (Do not use @code{search-forward} for the name
9392 of this function; if you do, you will overwrite the existing version of
9393 @code{search-forward} that comes with Emacs.  Use a name such as
9394 @code{test-search} instead.)
9396 @item
9397 Write a function that prints the third element of the kill ring in the
9398 echo area, if any; if the kill ring does not contain a third element,
9399 print an appropriate message.
9400 @end itemize
9402 @node List Implementation
9403 @chapter How Lists are Implemented
9404 @cindex Lists in a computer
9406 In Lisp, atoms are recorded in a straightforward fashion; if the
9407 implementation is not straightforward in practice, it is, nonetheless,
9408 straightforward in theory.  The atom @samp{rose}, for example, is
9409 recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
9410 @samp{e}.  A list, on the other hand, is kept differently.  The mechanism
9411 is equally simple, but it takes a moment to get used to the idea.  A
9412 list is kept using a series of pairs of pointers.  In the series, the
9413 first pointer in each pair points to an atom or to another list, and the
9414 second pointer in each pair points to the next pair, or to the symbol
9415 @code{nil}, which marks the end of the list.
9417 A pointer itself is quite simply the electronic address of what is
9418 pointed to.  Hence, a list is kept as a series of electronic addresses.
9420 @menu
9421 * Lists diagrammed::
9422 * Symbols as Chest::            Exploring a powerful metaphor.
9423 * List Exercise::
9424 @end menu
9426 @ifnottex
9427 @node Lists diagrammed
9428 @unnumberedsec Lists diagrammed
9429 @end ifnottex
9431 For example, the list @code{(rose violet buttercup)} has three elements,
9432 @samp{rose}, @samp{violet}, and @samp{buttercup}.  In the computer, the
9433 electronic address of @samp{rose} is recorded in a segment of computer
9434 memory along with the address that gives the electronic address of where
9435 the atom @samp{violet} is located; and that address (the one that tells
9436 where @samp{violet} is located) is kept along with an address that tells
9437 where the address for the atom @samp{buttercup} is located.
9439 @need 1200
9440 This sounds more complicated than it is and is easier seen in a diagram:
9442 @c clear print-postscript-figures
9443 @c !!! cons-cell-diagram #1
9444 @ifnottex
9445 @smallexample
9446 @group
9447     ___ ___      ___ ___      ___ ___
9448    |___|___|--> |___|___|--> |___|___|--> nil
9449      |            |            |
9450      |            |            |
9451       --> rose     --> violet   --> buttercup
9452 @end group
9453 @end smallexample
9454 @end ifnottex
9455 @ifset print-postscript-figures
9456 @sp 1
9457 @tex
9458 @center @image{cons-1}
9459 @end tex
9460 @sp 1
9461 @end ifset
9462 @ifclear print-postscript-figures
9463 @iftex
9464 @smallexample
9465 @group
9466     ___ ___      ___ ___      ___ ___
9467    |___|___|--> |___|___|--> |___|___|--> nil
9468      |            |            |
9469      |            |            |
9470       --> rose     --> violet   --> buttercup
9471 @end group
9472 @end smallexample
9473 @end iftex
9474 @end ifclear
9476 @noindent
9477 In the diagram, each box represents a word of computer memory that
9478 holds a Lisp object, usually in the form of a memory address.  The boxes,
9479 i.e., the addresses, are in pairs.  Each arrow points to what the address
9480 is the address of, either an atom or another pair of addresses.  The
9481 first box is the electronic address of @samp{rose} and the arrow points
9482 to @samp{rose}; the second box is the address of the next pair of boxes,
9483 the first part of which is the address of @samp{violet} and the second
9484 part of which is the address of the next pair.  The very last box
9485 points to the symbol @code{nil}, which marks the end of the list.
9487 @need 1200
9488 When a variable is set to a list with a function such as @code{setq},
9489 it stores the address of the first box in the variable.  Thus,
9490 evaluation of the expression
9492 @smallexample
9493 (setq bouquet '(rose violet buttercup))
9494 @end smallexample
9496 @need 1250
9497 @noindent
9498 creates a situation like this:
9500 @c cons-cell-diagram #2
9501 @ifnottex
9502 @smallexample
9503 @group
9504 bouquet
9505      |
9506      |     ___ ___      ___ ___      ___ ___
9507       --> |___|___|--> |___|___|--> |___|___|--> nil
9508             |            |            |
9509             |            |            |
9510              --> rose     --> violet   --> buttercup
9511 @end group
9512 @end smallexample
9513 @end ifnottex
9514 @ifset print-postscript-figures
9515 @sp 1
9516 @tex
9517 @center @image{cons-2}
9518 @end tex
9519 @sp 1
9520 @end ifset
9521 @ifclear print-postscript-figures
9522 @iftex
9523 @smallexample
9524 @group
9525 bouquet
9526      |
9527      |     ___ ___      ___ ___      ___ ___
9528       --> |___|___|--> |___|___|--> |___|___|--> nil
9529             |            |            |
9530             |            |            |
9531              --> rose     --> violet   --> buttercup
9532 @end group
9533 @end smallexample
9534 @end iftex
9535 @end ifclear
9537 @noindent
9538 In this example, the symbol @code{bouquet} holds the address of the first
9539 pair of boxes.
9541 @need 1200
9542 This same list can be illustrated in a different sort of box notation
9543 like this:
9545 @c cons-cell-diagram #2a
9546 @ifnottex
9547 @smallexample
9548 @group
9549 bouquet
9551  |    --------------       ---------------       ----------------
9552  |   | car   | cdr  |     | car    | cdr  |     | car     | cdr  |
9553   -->| rose  |   o------->| violet |   o------->| butter- |  nil |
9554      |       |      |     |        |      |     | cup     |      |
9555       --------------       ---------------       ----------------
9556 @end group
9557 @end smallexample
9558 @end ifnottex
9559 @ifset print-postscript-figures
9560 @sp 1
9561 @tex
9562 @center @image{cons-2a}
9563 @end tex
9564 @sp 1
9565 @end ifset
9566 @ifclear print-postscript-figures
9567 @iftex
9568 @smallexample
9569 @group
9570 bouquet
9572  |    --------------       ---------------       ----------------
9573  |   | car   | cdr  |     | car    | cdr  |     | car     | cdr  |
9574   -->| rose  |   o------->| violet |   o------->| butter- |  nil |
9575      |       |      |     |        |      |     | cup     |      |
9576       --------------       ---------------       ----------------
9577 @end group
9578 @end smallexample
9579 @end iftex
9580 @end ifclear
9582 (Symbols consist of more than pairs of addresses, but the structure of
9583 a symbol is made up of addresses.  Indeed, the symbol @code{bouquet}
9584 consists of a group of address-boxes, one of which is the address of
9585 the printed word @samp{bouquet}, a second of which is the address of a
9586 function definition attached to the symbol, if any, a third of which
9587 is the address of the first pair of address-boxes for the list
9588 @code{(rose violet buttercup)}, and so on.  Here we are showing that
9589 the symbol's third address-box points to the first pair of
9590 address-boxes for the list.)
9592 If a symbol is set to the @sc{cdr} of a list, the list itself is not
9593 changed; the symbol simply has an address further down the list.  (In
9594 the jargon, @sc{car} and @sc{cdr} are ``non-destructive''.)  Thus,
9595 evaluation of the following expression
9597 @smallexample
9598 (setq flowers (cdr bouquet))
9599 @end smallexample
9601 @need 800
9602 @noindent
9603 produces this:
9605 @c cons-cell-diagram #3
9606 @ifnottex
9607 @sp 1
9608 @smallexample
9609 @group
9610 bouquet        flowers
9611   |              |
9612   |     ___ ___  |     ___ ___      ___ ___
9613    --> |   |   |  --> |   |   |    |   |   |
9614        |___|___|----> |___|___|--> |___|___|--> nil
9615          |              |            |
9616          |              |            |
9617           --> rose       --> violet   --> buttercup
9618 @end group
9619 @end smallexample
9620 @sp 1
9621 @end ifnottex
9622 @ifset print-postscript-figures
9623 @sp 1
9624 @tex
9625 @center @image{cons-3}
9626 @end tex
9627 @sp 1
9628 @end ifset
9629 @ifclear print-postscript-figures
9630 @iftex
9631 @sp 1
9632 @smallexample
9633 @group
9634 bouquet        flowers
9635   |              |
9636   |     ___ ___  |     ___ ___      ___ ___
9637    --> |   |   |  --> |   |   |    |   |   |
9638        |___|___|----> |___|___|--> |___|___|--> nil
9639          |              |            |
9640          |              |            |
9641           --> rose       --> violet   --> buttercup
9642 @end group
9643 @end smallexample
9644 @sp 1
9645 @end iftex
9646 @end ifclear
9648 @noindent
9649 The value of @code{flowers} is @code{(violet buttercup)}, which is
9650 to say, the symbol @code{flowers} holds the address of the pair of
9651 address-boxes, the first of which holds the address of @code{violet},
9652 and the second of which holds the address of @code{buttercup}.
9654 A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9655 pair}.  @xref{Cons Cell Type, , Cons Cell and List Types, elisp, The GNU Emacs Lisp
9656 Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9657 Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9658 information about cons cells and dotted pairs.
9660 @need 1200
9661 The function @code{cons} adds a new pair of addresses to the front of
9662 a series of addresses like that shown above.  For example, evaluating
9663 the expression
9665 @smallexample
9666 (setq bouquet (cons 'lily bouquet))
9667 @end smallexample
9669 @need 1500
9670 @noindent
9671 produces:
9673 @c cons-cell-diagram #4
9674 @ifnottex
9675 @sp 1
9676 @smallexample
9677 @group
9678 bouquet                       flowers
9679   |                             |
9680   |     ___ ___        ___ ___  |     ___ ___       ___ ___
9681    --> |   |   |      |   |   |  --> |   |   |     |   |   |
9682        |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9683          |              |              |             |
9684          |              |              |             |
9685           --> lily      --> rose       --> violet    --> buttercup
9686 @end group
9687 @end smallexample
9688 @sp 1
9689 @end ifnottex
9690 @ifset print-postscript-figures
9691 @sp 1
9692 @tex
9693 @center @image{cons-4}
9694 @end tex
9695 @sp 1
9696 @end ifset
9697 @ifclear print-postscript-figures
9698 @iftex
9699 @sp 1
9700 @smallexample
9701 @group
9702 bouquet                       flowers
9703   |                             |
9704   |     ___ ___        ___ ___  |     ___ ___       ___ ___
9705    --> |   |   |      |   |   |  --> |   |   |     |   |   |
9706        |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9707          |              |              |             |
9708          |              |              |             |
9709           --> lily      --> rose       --> violet    --> buttercup
9710 @end group
9711 @end smallexample
9712 @sp 1
9713 @end iftex
9714 @end ifclear
9716 @need 1200
9717 @noindent
9718 However, this does not change the value of the symbol
9719 @code{flowers}, as you can see by evaluating the following,
9721 @smallexample
9722 (eq (cdr (cdr bouquet)) flowers)
9723 @end smallexample
9725 @noindent
9726 which returns @code{t} for true.
9728 Until it is reset, @code{flowers} still has the value
9729 @code{(violet buttercup)}; that is, it has the address of the cons
9730 cell whose first address is of @code{violet}.  Also, this does not
9731 alter any of the pre-existing cons cells; they are all still there.
9733 Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9734 of the next cons cell in the series; to get the @sc{car} of a list,
9735 you get the address of the first element of the list; to @code{cons} a
9736 new element on a list, you add a new cons cell to the front of the list.
9737 That is all there is to it!  The underlying structure of Lisp is
9738 brilliantly simple!
9740 And what does the last address in a series of cons cells refer to?  It
9741 is the address of the empty list, of @code{nil}.
9743 In summary, when a Lisp variable is set to a value, it is provided with
9744 the address of the list to which the variable refers.
9746 @node Symbols as Chest
9747 @section Symbols as a Chest of Drawers
9748 @cindex Symbols as a Chest of Drawers
9749 @cindex Chest of Drawers, metaphor for a symbol
9750 @cindex Drawers, Chest of, metaphor for a symbol
9752 In an earlier section, I suggested that you might imagine a symbol as
9753 being a chest of drawers.  The function definition is put in one
9754 drawer, the value in another, and so on.  What is put in the drawer
9755 holding the value can be changed without affecting the contents of the
9756 drawer holding the function definition, and vice versa.
9758 Actually, what is put in each drawer is the address of the value or
9759 function definition.  It is as if you found an old chest in the attic,
9760 and in one of its drawers you found a map giving you directions to
9761 where the buried treasure lies.
9763 (In addition to its name, symbol definition, and variable value, a
9764 symbol has a drawer for a @dfn{property list} which can be used to
9765 record other information.  Property lists are not discussed here; see
9766 @ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9767 Reference Manual}.)
9769 @need 1500
9770 Here is a fanciful representation:
9772 @c chest-of-drawers diagram
9773 @ifnottex
9774 @sp 1
9775 @smallexample
9776 @group
9777             Chest of Drawers            Contents of Drawers
9779             __   o0O0o   __
9780           /                 \
9781          ---------------------
9782         |    directions to    |            [map to]
9783         |     symbol name     |             bouquet
9784         |                     |
9785         +---------------------+
9786         |    directions to    |
9787         |  symbol definition  |             [none]
9788         |                     |
9789         +---------------------+
9790         |    directions to    |            [map to]
9791         |    variable value   |             (rose violet buttercup)
9792         |                     |
9793         +---------------------+
9794         |    directions to    |
9795         |    property list    |             [not described here]
9796         |                     |
9797         +---------------------+
9798         |/                   \|
9799 @end group
9800 @end smallexample
9801 @sp 1
9802 @end ifnottex
9803 @ifset print-postscript-figures
9804 @sp 1
9805 @tex
9806 @center @image{drawers}
9807 @end tex
9808 @sp 1
9809 @end ifset
9810 @ifclear print-postscript-figures
9811 @iftex
9812 @sp 1
9813 @smallexample
9814 @group
9815             Chest of Drawers            Contents of Drawers
9817             __   o0O0o   __
9818           /                 \
9819          ---------------------
9820         |    directions to    |            [map to]
9821         |     symbol name     |             bouquet
9822         |                     |
9823         +---------------------+
9824         |    directions to    |
9825         |  symbol definition  |             [none]
9826         |                     |
9827         +---------------------+
9828         |    directions to    |            [map to]
9829         |    variable value   |             (rose violet buttercup)
9830         |                     |
9831         +---------------------+
9832         |    directions to    |
9833         |    property list    |             [not described here]
9834         |                     |
9835         +---------------------+
9836         |/                   \|
9837 @end group
9838 @end smallexample
9839 @sp 1
9840 @end iftex
9841 @end ifclear
9843 @node List Exercise
9844 @section Exercise
9846 Set @code{flowers} to @code{violet} and @code{buttercup}.  Cons two
9847 more flowers on to this list and set this new list to
9848 @code{more-flowers}.  Set the @sc{car} of @code{flowers} to a fish.
9849 What does the @code{more-flowers} list now contain?
9851 @node Yanking
9852 @chapter Yanking Text Back
9853 @findex yank
9854 @cindex Text retrieval
9855 @cindex Retrieving text
9856 @cindex Pasting text
9858 Whenever you cut text out of a buffer with a kill command in GNU Emacs,
9859 you can bring it back with a yank command.  The text that is cut out of
9860 the buffer is put in the kill ring and the yank commands insert the
9861 appropriate contents of the kill ring back into a buffer (not necessarily
9862 the original buffer).
9864 A simple @kbd{C-y} (@code{yank}) command inserts the first item from
9865 the kill ring into the current buffer.  If the @kbd{C-y} command is
9866 followed immediately by @kbd{M-y}, the first element is replaced by
9867 the second element.  Successive @kbd{M-y} commands replace the second
9868 element with the third, fourth, or fifth element, and so on.  When the
9869 last element in the kill ring is reached, it is replaced by the first
9870 element and the cycle is repeated.  (Thus the kill ring is called a
9871 ``ring'' rather than just a ``list''.  However, the actual data structure
9872 that holds the text is a list.
9873 @xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
9874 list is handled as a ring.)
9876 @menu
9877 * Kill Ring Overview::
9878 * kill-ring-yank-pointer::      The kill ring is a list.
9879 * yank nthcdr Exercises::       The @code{kill-ring-yank-pointer} variable.
9880 @end menu
9882 @node Kill Ring Overview
9883 @section Kill Ring Overview
9884 @cindex Kill ring overview
9886 The kill ring is a list of textual strings.  This is what it looks like:
9888 @smallexample
9889 ("some text" "a different piece of text" "yet more text")
9890 @end smallexample
9892 If this were the contents of my kill ring and I pressed @kbd{C-y}, the
9893 string of characters saying @samp{some text} would be inserted in this
9894 buffer where my cursor is located.
9896 The @code{yank} command is also used for duplicating text by copying it.
9897 The copied text is not cut from the buffer, but a copy of it is put on the
9898 kill ring and is inserted by yanking it back.
9900 Three functions are used for bringing text back from the kill ring:
9901 @code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
9902 which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
9903 which is used by the two other functions.
9905 These functions refer to the kill ring through a variable called the
9906 @code{kill-ring-yank-pointer}.  Indeed, the insertion code for both the
9907 @code{yank} and @code{yank-pop} functions is:
9909 @smallexample
9910 (insert (car kill-ring-yank-pointer))
9911 @end smallexample
9913 @noindent
9914 (Well, no more.  In GNU Emacs 22, the function has been replaced by
9915 @code{insert-for-yank} which calls @code{insert-for-yank-1}
9916 repetitively for each @code{yank-handler} segment.  In turn,
9917 @code{insert-for-yank-1} strips text properties from the inserted text
9918 according to @code{yank-excluded-properties}.  Otherwise, it is just
9919 like @code{insert}.  We will stick with plain @code{insert} since it
9920 is easier to understand.)
9922 To begin to understand how @code{yank} and @code{yank-pop} work, it is
9923 first necessary to look at the @code{kill-ring-yank-pointer} variable.
9925 @node kill-ring-yank-pointer
9926 @section The @code{kill-ring-yank-pointer} Variable
9928 @code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
9929 a variable.  It points to something by being bound to the value of what
9930 it points to, like any other Lisp variable.
9932 @need 1000
9933 Thus, if the value of the kill ring is:
9935 @smallexample
9936 ("some text" "a different piece of text" "yet more text")
9937 @end smallexample
9939 @need 1250
9940 @noindent
9941 and the @code{kill-ring-yank-pointer} points to the second clause, the
9942 value of @code{kill-ring-yank-pointer} is:
9944 @smallexample
9945 ("a different piece of text" "yet more text")
9946 @end smallexample
9948 As explained in the previous chapter (@pxref{List Implementation}), the
9949 computer does not keep two different copies of the text being pointed to
9950 by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}.  The
9951 words ``a different piece of text'' and ``yet more text'' are not
9952 duplicated.  Instead, the two Lisp variables point to the same pieces of
9953 text.  Here is a diagram:
9955 @c cons-cell-diagram #5
9956 @ifnottex
9957 @smallexample
9958 @group
9959 kill-ring     kill-ring-yank-pointer
9960     |               |
9961     |      ___ ___  |     ___ ___      ___ ___
9962      ---> |   |   |  --> |   |   |    |   |   |
9963           |___|___|----> |___|___|--> |___|___|--> nil
9964             |              |            |
9965             |              |            |
9966             |              |             --> "yet more text"
9967             |              |
9968             |               --> "a different piece of text"
9969             |
9970              --> "some text"
9971 @end group
9972 @end smallexample
9973 @sp 1
9974 @end ifnottex
9975 @ifset print-postscript-figures
9976 @sp 1
9977 @tex
9978 @center @image{cons-5}
9979 @end tex
9980 @sp 1
9981 @end ifset
9982 @ifclear print-postscript-figures
9983 @iftex
9984 @smallexample
9985 @group
9986 kill-ring     kill-ring-yank-pointer
9987     |               |
9988     |      ___ ___  |     ___ ___      ___ ___
9989      ---> |   |   |  --> |   |   |    |   |   |
9990           |___|___|----> |___|___|--> |___|___|--> nil
9991             |              |            |
9992             |              |            |
9993             |              |             --> "yet more text"
9994             |              |
9995             |               --> "a different piece of text
9996             |
9997              --> "some text"
9998 @end group
9999 @end smallexample
10000 @sp 1
10001 @end iftex
10002 @end ifclear
10004 Both the variable @code{kill-ring} and the variable
10005 @code{kill-ring-yank-pointer} are pointers.  But the kill ring itself is
10006 usually described as if it were actually what it is composed of.  The
10007 @code{kill-ring} is spoken of as if it were the list rather than that it
10008 points to the list.  Conversely, the @code{kill-ring-yank-pointer} is
10009 spoken of as pointing to a list.
10011 These two ways of talking about the same thing sound confusing at first but
10012 make sense on reflection.  The kill ring is generally thought of as the
10013 complete structure of data that holds the information of what has recently
10014 been cut out of the Emacs buffers.  The @code{kill-ring-yank-pointer}
10015 on the other hand, serves to indicate---that is, to point to---that part
10016 of the kill ring of which the first element (the @sc{car}) will be
10017 inserted.
10019 @ignore
10020 In GNU Emacs 22, the @code{kill-new} function calls
10022 @code{(setq kill-ring-yank-pointer kill-ring)}
10024 (defun rotate-yank-pointer (arg)
10025   "Rotate the yanking point in the kill ring.
10026 With argument, rotate that many kills forward (or backward, if negative)."
10027   (interactive "p")
10028   (current-kill arg))
10030 (defun current-kill (n &optional do-not-move)
10031   "Rotate the yanking point by N places, and then return that kill.
10032 If N is zero, `interprogram-paste-function' is set, and calling it
10033 returns a string, then that string is added to the front of the
10034 kill ring and returned as the latest kill.
10035 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
10036 yanking point; just return the Nth kill forward."
10037   (let ((interprogram-paste (and (= n 0)
10038                                  interprogram-paste-function
10039                                  (funcall interprogram-paste-function))))
10040     (if interprogram-paste
10041         (progn
10042           ;; Disable the interprogram cut function when we add the new
10043           ;; text to the kill ring, so Emacs doesn't try to own the
10044           ;; selection, with identical text.
10045           (let ((interprogram-cut-function nil))
10046             (kill-new interprogram-paste))
10047           interprogram-paste)
10048       (or kill-ring (error "Kill ring is empty"))
10049       (let ((ARGth-kill-element
10050              (nthcdr (mod (- n (length kill-ring-yank-pointer))
10051                           (length kill-ring))
10052                      kill-ring)))
10053         (or do-not-move
10054             (setq kill-ring-yank-pointer ARGth-kill-element))
10055         (car ARGth-kill-element)))))
10057 @end ignore
10059 @need 1500
10060 @node yank nthcdr Exercises
10061 @section Exercises with @code{yank} and @code{nthcdr}
10063 @itemize @bullet
10064 @item
10065 Using @kbd{C-h v} (@code{describe-variable}), look at the value of
10066 your kill ring.  Add several items to your kill ring; look at its
10067 value again.  Using @kbd{M-y} (@code{yank-pop)}, move all the way
10068 around the kill ring.  How many items were in your kill ring?  Find
10069 the value of @code{kill-ring-max}.  Was your kill ring full, or could
10070 you have kept more blocks of text within it?
10072 @item
10073 Using @code{nthcdr} and @code{car}, construct a series of expressions
10074 to return the first, second, third, and fourth elements of a list.
10075 @end itemize
10077 @node Loops & Recursion
10078 @chapter Loops and Recursion
10079 @cindex Loops and recursion
10080 @cindex Recursion and loops
10081 @cindex Repetition (loops)
10083 Emacs Lisp has two primary ways to cause an expression, or a series of
10084 expressions, to be evaluated repeatedly: one uses a @code{while}
10085 loop, and the other uses @dfn{recursion}.
10087 Repetition can be very valuable.  For example, to move forward four
10088 sentences, you need only write a program that will move forward one
10089 sentence and then repeat the process four times.  Since a computer does
10090 not get bored or tired, such repetitive action does not have the
10091 deleterious effects that excessive or the wrong kinds of repetition can
10092 have on humans.
10094 People mostly write Emacs Lisp functions using @code{while} loops and
10095 their kin; but you can use recursion, which provides a very powerful
10096 way to think about and then to solve problems@footnote{You can write
10097 recursive functions to be frugal or wasteful of mental or computer
10098 resources; as it happens, methods that people find easy---that are
10099 frugal of mental resources---sometimes use considerable computer
10100 resources.  Emacs was designed to run on machines that we now consider
10101 limited and its default settings are conservative.  You may want to
10102 increase the values of @code{max-specpdl-size} and
10103 @code{max-lisp-eval-depth}.  In my @file{.emacs} file, I set them to
10104 15 and 30 times their default value.}.
10106 @menu
10107 * while::                       Causing a stretch of code to repeat.
10108 * dolist dotimes::
10109 * Recursion::                   Causing a function to call itself.
10110 * Looping exercise::
10111 @end menu
10113 @node while
10114 @section @code{while}
10115 @cindex Loops
10116 @findex while
10118 The @code{while} special form tests whether the value returned by
10119 evaluating its first argument is true or false.  This is similar to what
10120 the Lisp interpreter does with an @code{if}; what the interpreter does
10121 next, however, is different.
10123 In a @code{while} expression, if the value returned by evaluating the
10124 first argument is false, the Lisp interpreter skips the rest of the
10125 expression (the @dfn{body} of the expression) and does not evaluate it.
10126 However, if the value is true, the Lisp interpreter evaluates the body
10127 of the expression and then again tests whether the first argument to
10128 @code{while} is true or false.  If the value returned by evaluating the
10129 first argument is again true, the Lisp interpreter again evaluates the
10130 body of the expression.
10132 @need 1200
10133 The template for a @code{while} expression looks like this:
10135 @smallexample
10136 @group
10137 (while @var{true-or-false-test}
10138   @var{body}@dots{})
10139 @end group
10140 @end smallexample
10142 @menu
10143 * Looping with while::          Repeat so long as test returns true.
10144 * Loop Example::                A @code{while} loop that uses a list.
10145 * print-elements-of-list::      Uses @code{while}, @code{car}, @code{cdr}.
10146 * Incrementing Loop::           A loop with an incrementing counter.
10147 * Incrementing Loop Details::
10148 * Decrementing Loop::           A loop with a decrementing counter.
10149 @end menu
10151 @ifnottex
10152 @node Looping with while
10153 @unnumberedsubsec Looping with @code{while}
10154 @end ifnottex
10156 So long as the true-or-false-test of the @code{while} expression
10157 returns a true value when it is evaluated, the body is repeatedly
10158 evaluated.  This process is called a loop since the Lisp interpreter
10159 repeats the same thing again and again, like an airplane doing a loop.
10160 When the result of evaluating the true-or-false-test is false, the
10161 Lisp interpreter does not evaluate the rest of the @code{while}
10162 expression and exits the loop.
10164 Clearly, if the value returned by evaluating the first argument to
10165 @code{while} is always true, the body following will be evaluated
10166 again and again @dots{} and again @dots{} forever.  Conversely, if the
10167 value returned is never true, the expressions in the body will never
10168 be evaluated.  The craft of writing a @code{while} loop consists of
10169 choosing a mechanism such that the true-or-false-test returns true
10170 just the number of times that you want the subsequent expressions to
10171 be evaluated, and then have the test return false.
10173 The value returned by evaluating a @code{while} is the value of the
10174 true-or-false-test.  An interesting consequence of this is that a
10175 @code{while} loop that evaluates without error will return @code{nil}
10176 or false regardless of whether it has looped 1 or 100 times or none at
10177 all.  A @code{while} expression that evaluates successfully never
10178 returns a true value!  What this means is that @code{while} is always
10179 evaluated for its side effects, which is to say, the consequences of
10180 evaluating the expressions within the body of the @code{while} loop.
10181 This makes sense.  It is not the mere act of looping that is desired,
10182 but the consequences of what happens when the expressions in the loop
10183 are repeatedly evaluated.
10185 @node Loop Example
10186 @subsection A @code{while} Loop and a List
10188 A common way to control a @code{while} loop is to test whether a list
10189 has any elements.  If it does, the loop is repeated; but if it does not,
10190 the repetition is ended.  Since this is an important technique, we will
10191 create a short example to illustrate it.
10193 A simple way to test whether a list has elements is to evaluate the
10194 list: if it has no elements, it is an empty list and will return the
10195 empty list, @code{()}, which is a synonym for @code{nil} or false.  On
10196 the other hand, a list with elements will return those elements when it
10197 is evaluated.  Since Emacs Lisp considers as true any value that is not
10198 @code{nil}, a list that returns elements will test true in a
10199 @code{while} loop.
10201 @need 1200
10202 For example, you can set the variable @code{empty-list} to @code{nil} by
10203 evaluating the following @code{setq} expression:
10205 @smallexample
10206 (setq empty-list ())
10207 @end smallexample
10209 @noindent
10210 After evaluating the @code{setq} expression, you can evaluate the
10211 variable @code{empty-list} in the usual way, by placing the cursor after
10212 the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
10213 echo area:
10215 @smallexample
10216 empty-list
10217 @end smallexample
10219 On the other hand, if you set a variable to be a list with elements, the
10220 list will appear when you evaluate the variable, as you can see by
10221 evaluating the following two expressions:
10223 @smallexample
10224 @group
10225 (setq animals '(gazelle giraffe lion tiger))
10227 animals
10228 @end group
10229 @end smallexample
10231 Thus, to create a @code{while} loop that tests whether there are any
10232 items in the list @code{animals}, the first part of the loop will be
10233 written like this:
10235 @smallexample
10236 @group
10237 (while animals
10238        @dots{}
10239 @end group
10240 @end smallexample
10242 @noindent
10243 When the @code{while} tests its first argument, the variable
10244 @code{animals} is evaluated.  It returns a list.  So long as the list
10245 has elements, the @code{while} considers the results of the test to be
10246 true; but when the list is empty, it considers the results of the test
10247 to be false.
10249 To prevent the @code{while} loop from running forever, some mechanism
10250 needs to be provided to empty the list eventually.  An oft-used
10251 technique is to have one of the subsequent forms in the @code{while}
10252 expression set the value of the list to be the @sc{cdr} of the list.
10253 Each time the @code{cdr} function is evaluated, the list will be made
10254 shorter, until eventually only the empty list will be left.  At this
10255 point, the test of the @code{while} loop will return false, and the
10256 arguments to the @code{while} will no longer be evaluated.
10258 For example, the list of animals bound to the variable @code{animals}
10259 can be set to be the @sc{cdr} of the original list with the
10260 following expression:
10262 @smallexample
10263 (setq animals (cdr animals))
10264 @end smallexample
10266 @noindent
10267 If you have evaluated the previous expressions and then evaluate this
10268 expression, you will see @code{(giraffe lion tiger)} appear in the echo
10269 area.  If you evaluate the expression again, @code{(lion tiger)} will
10270 appear in the echo area.  If you evaluate it again and yet again,
10271 @code{(tiger)} appears and then the empty list, shown by @code{nil}.
10273 A template for a @code{while} loop that uses the @code{cdr} function
10274 repeatedly to cause the true-or-false-test eventually to test false
10275 looks like this:
10277 @smallexample
10278 @group
10279 (while @var{test-whether-list-is-empty}
10280   @var{body}@dots{}
10281   @var{set-list-to-cdr-of-list})
10282 @end group
10283 @end smallexample
10285 This test and use of @code{cdr} can be put together in a function that
10286 goes through a list and prints each element of the list on a line of its
10287 own.
10289 @node print-elements-of-list
10290 @subsection An Example: @code{print-elements-of-list}
10291 @findex print-elements-of-list
10293 The @code{print-elements-of-list} function illustrates a @code{while}
10294 loop with a list.
10296 @cindex @file{*scratch*} buffer
10297 The function requires several lines for its output.  If you are
10298 reading this in a recent instance of GNU Emacs,
10299 @c GNU Emacs 21, GNU Emacs 22, or a later version,
10300 you can evaluate the following expression inside of Info, as usual.
10302 If you are using an earlier version of Emacs, you need to copy the
10303 necessary expressions to your @file{*scratch*} buffer and evaluate
10304 them there.  This is because the echo area had only one line in the
10305 earlier versions.
10307 You can copy the expressions by marking the beginning of the region
10308 with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
10309 the end of the region and then copying the region using @kbd{M-w}
10310 (@code{kill-ring-save}, which calls @code{copy-region-as-kill} and
10311 then provides visual feedback).  In the @file{*scratch*}
10312 buffer, you can yank the expressions back by typing @kbd{C-y}
10313 (@code{yank}).
10315 After you have copied the expressions to the @file{*scratch*} buffer,
10316 evaluate each expression in turn.  Be sure to evaluate the last
10317 expression, @code{(print-elements-of-list animals)}, by typing
10318 @kbd{C-u C-x C-e}, that is, by giving an argument to
10319 @code{eval-last-sexp}.  This will cause the result of the evaluation
10320 to be printed in the @file{*scratch*} buffer instead of being printed
10321 in the echo area.  (Otherwise you will see something like this in your
10322 echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
10323 each @samp{^J} stands for a newline.)
10325 @need 1500
10326 In a recent instance of GNU Emacs, you can evaluate these expressions
10327 directly in the Info buffer, and the echo area will grow to show the
10328 results.
10330 @smallexample
10331 @group
10332 (setq animals '(gazelle giraffe lion tiger))
10334 (defun print-elements-of-list (list)
10335   "Print each element of LIST on a line of its own."
10336   (while list
10337     (print (car list))
10338     (setq list (cdr list))))
10340 (print-elements-of-list animals)
10341 @end group
10342 @end smallexample
10344 @need 1200
10345 @noindent
10346 When you evaluate the three expressions in sequence, you will see
10347 this:
10349 @smallexample
10350 @group
10351 gazelle
10353 giraffe
10355 lion
10357 tiger
10359 @end group
10360 @end smallexample
10362 Each element of the list is printed on a line of its own (that is what
10363 the function @code{print} does) and then the value returned by the
10364 function is printed.  Since the last expression in the function is the
10365 @code{while} loop, and since @code{while} loops always return
10366 @code{nil}, a @code{nil} is printed after the last element of the list.
10368 @node Incrementing Loop
10369 @subsection A Loop with an Incrementing Counter
10371 A loop is not useful unless it stops when it ought.  Besides
10372 controlling a loop with a list, a common way of stopping a loop is to
10373 write the first argument as a test that returns false when the correct
10374 number of repetitions are complete.  This means that the loop must
10375 have a counter---an expression that counts how many times the loop
10376 repeats itself.
10378 @ifnottex
10379 @node Incrementing Loop Details
10380 @unnumberedsubsec Details of an Incrementing Loop
10381 @end ifnottex
10383 The test for a loop with an incrementing counter can be an expression
10384 such as @code{(< count desired-number)} which returns @code{t} for
10385 true if the value of @code{count} is less than the
10386 @code{desired-number} of repetitions and @code{nil} for false if the
10387 value of @code{count} is equal to or is greater than the
10388 @code{desired-number}.  The expression that increments the count can
10389 be a simple @code{setq} such as @code{(setq count (1+ count))}, where
10390 @code{1+} is a built-in function in Emacs Lisp that adds 1 to its
10391 argument.  (The expression @w{@code{(1+ count)}} has the same result
10392 as @w{@code{(+ count 1)}}, but is easier for a human to read.)
10394 @need 1250
10395 The template for a @code{while} loop controlled by an incrementing
10396 counter looks like this:
10398 @smallexample
10399 @group
10400 @var{set-count-to-initial-value}
10401 (while (< count desired-number)         ; @r{true-or-false-test}
10402   @var{body}@dots{}
10403   (setq count (1+ count)))              ; @r{incrementer}
10404 @end group
10405 @end smallexample
10407 @noindent
10408 Note that you need to set the initial value of @code{count}; usually it
10409 is set to 1.
10411 @menu
10412 * Incrementing Example::        Counting pebbles in a triangle.
10413 * Inc Example parts::           The parts of the function definition.
10414 * Inc Example altogether::      Putting the function definition together.
10415 @end menu
10417 @node Incrementing Example
10418 @unnumberedsubsubsec  Example with incrementing counter
10420 Suppose you are playing on the beach and decide to make a triangle of
10421 pebbles, putting one pebble in the first row, two in the second row,
10422 three in the third row and so on, like this:
10424 @sp 1
10425 @c pebble diagram
10426 @ifnottex
10427 @smallexample
10428 @group
10429                *
10430               * *
10431              * * *
10432             * * * *
10433 @end group
10434 @end smallexample
10435 @end ifnottex
10436 @iftex
10437 @smallexample
10438 @group
10439                @bullet{}
10440               @bullet{} @bullet{}
10441              @bullet{} @bullet{} @bullet{}
10442             @bullet{} @bullet{} @bullet{} @bullet{}
10443 @end group
10444 @end smallexample
10445 @end iftex
10446 @sp 1
10448 @noindent
10449 (About 2500 years ago, Pythagoras and others developed the beginnings of
10450 number theory by considering questions such as this.)
10452 Suppose you want to know how many pebbles you will need to make a
10453 triangle with 7 rows?
10455 Clearly, what you need to do is add up the numbers from 1 to 7.  There
10456 are two ways to do this; start with the smallest number, one, and add up
10457 the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
10458 number and add the list going down: 7, 6, 5, 4 and so on.  Because both
10459 mechanisms illustrate common ways of writing @code{while} loops, we will
10460 create two examples, one counting up and the other counting down.  In
10461 this first example, we will start with 1 and add 2, 3, 4 and so on.
10463 If you are just adding up a short list of numbers, the easiest way to do
10464 it is to add up all the numbers at once.  However, if you do not know
10465 ahead of time how many numbers your list will have, or if you want to be
10466 prepared for a very long list, then you need to design your addition so
10467 that what you do is repeat a simple process many times instead of doing
10468 a more complex process once.
10470 For example, instead of adding up all the pebbles all at once, what you
10471 can do is add the number of pebbles in the first row, 1, to the number
10472 in the second row, 2, and then add the total of those two rows to the
10473 third row, 3.  Then you can add the number in the fourth row, 4, to the
10474 total of the first three rows; and so on.
10476 The critical characteristic of the process is that each repetitive
10477 action is simple.  In this case, at each step we add only two numbers,
10478 the number of pebbles in the row and the total already found.  This
10479 process of adding two numbers is repeated again and again until the last
10480 row has been added to the total of all the preceding rows.  In a more
10481 complex loop the repetitive action might not be so simple, but it will
10482 be simpler than doing everything all at once.
10484 @node Inc Example parts
10485 @unnumberedsubsubsec The parts of the function definition
10487 The preceding analysis gives us the bones of our function definition:
10488 first, we will need a variable that we can call @code{total} that will
10489 be the total number of pebbles.  This will be the value returned by
10490 the function.
10492 Second, we know that the function will require an argument: this
10493 argument will be the total number of rows in the triangle.  It can be
10494 called @code{number-of-rows}.
10496 Finally, we need a variable to use as a counter.  We could call this
10497 variable @code{counter}, but a better name is @code{row-number}.  That
10498 is because what the counter does in this function is count rows, and a
10499 program should be written to be as understandable as possible.
10501 When the Lisp interpreter first starts evaluating the expressions in the
10502 function, the value of @code{total} should be set to zero, since we have
10503 not added anything to it.  Then the function should add the number of
10504 pebbles in the first row to the total, and then add the number of
10505 pebbles in the second to the total, and then add the number of
10506 pebbles in the third row to the total, and so on, until there are no
10507 more rows left to add.
10509 Both @code{total} and @code{row-number} are used only inside the
10510 function, so they can be declared as local variables with @code{let}
10511 and given initial values.  Clearly, the initial value for @code{total}
10512 should be 0.  The initial value of @code{row-number} should be 1,
10513 since we start with the first row.  This means that the @code{let}
10514 statement will look like this:
10516 @smallexample
10517 @group
10518   (let ((total 0)
10519         (row-number 1))
10520     @var{body}@dots{})
10521 @end group
10522 @end smallexample
10524 After the internal variables are declared and bound to their initial
10525 values, we can begin the @code{while} loop.  The expression that serves
10526 as the test should return a value of @code{t} for true so long as the
10527 @code{row-number} is less than or equal to the @code{number-of-rows}.
10528 (If the expression tests true only so long as the row number is less
10529 than the number of rows in the triangle, the last row will never be
10530 added to the total; hence the row number has to be either less than or
10531 equal to the number of rows.)
10533 @need 1500
10534 @findex <= @r{(less than or equal)}
10535 Lisp provides the @code{<=} function that returns true if the value of
10536 its first argument is less than or equal to the value of its second
10537 argument and false otherwise.  So the expression that the @code{while}
10538 will evaluate as its test should look like this:
10540 @smallexample
10541 (<= row-number number-of-rows)
10542 @end smallexample
10544 The total number of pebbles can be found by repeatedly adding the number
10545 of pebbles in a row to the total already found.  Since the number of
10546 pebbles in the row is equal to the row number, the total can be found by
10547 adding the row number to the total.  (Clearly, in a more complex
10548 situation, the number of pebbles in the row might be related to the row
10549 number in a more complicated way; if this were the case, the row number
10550 would be replaced by the appropriate expression.)
10552 @smallexample
10553 (setq total (+ total row-number))
10554 @end smallexample
10556 @noindent
10557 What this does is set the new value of @code{total} to be equal to the
10558 sum of adding the number of pebbles in the row to the previous total.
10560 After setting the value of @code{total}, the conditions need to be
10561 established for the next repetition of the loop, if there is one.  This
10562 is done by incrementing the value of the @code{row-number} variable,
10563 which serves as a counter.  After the @code{row-number} variable has
10564 been incremented, the true-or-false-test at the beginning of the
10565 @code{while} loop tests whether its value is still less than or equal to
10566 the value of the @code{number-of-rows} and if it is, adds the new value
10567 of the @code{row-number} variable to the @code{total} of the previous
10568 repetition of the loop.
10570 @need 1200
10571 The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10572 @code{row-number} variable can be incremented with this expression:
10574 @smallexample
10575 (setq row-number (1+ row-number))
10576 @end smallexample
10578 @node Inc Example altogether
10579 @unnumberedsubsubsec Putting the function definition together
10581 We have created the parts for the function definition; now we need to
10582 put them together.
10584 @need 800
10585 First, the contents of the @code{while} expression:
10587 @smallexample
10588 @group
10589 (while (<= row-number number-of-rows)   ; @r{true-or-false-test}
10590   (setq total (+ total row-number))
10591   (setq row-number (1+ row-number)))    ; @r{incrementer}
10592 @end group
10593 @end smallexample
10595 Along with the @code{let} expression varlist, this very nearly
10596 completes the body of the function definition.  However, it requires
10597 one final element, the need for which is somewhat subtle.
10599 The final touch is to place the variable @code{total} on a line by
10600 itself after the @code{while} expression.  Otherwise, the value returned
10601 by the whole function is the value of the last expression that is
10602 evaluated in the body of the @code{let}, and this is the value
10603 returned by the @code{while}, which is always @code{nil}.
10605 This may not be evident at first sight.  It almost looks as if the
10606 incrementing expression is the last expression of the whole function.
10607 But that expression is part of the body of the @code{while}; it is the
10608 last element of the list that starts with the symbol @code{while}.
10609 Moreover, the whole of the @code{while} loop is a list within the body
10610 of the @code{let}.
10612 @need 1250
10613 In outline, the function will look like this:
10615 @smallexample
10616 @group
10617 (defun @var{name-of-function} (@var{argument-list})
10618   "@var{documentation}@dots{}"
10619   (let (@var{varlist})
10620     (while (@var{true-or-false-test})
10621       @var{body-of-while}@dots{} )
10622     @dots{} ))                    ; @r{Need final expression here.}
10623 @end group
10624 @end smallexample
10626 The result of evaluating the @code{let} is what is going to be returned
10627 by the @code{defun} since the @code{let} is not embedded within any
10628 containing list, except for the @code{defun} as a whole.  However, if
10629 the @code{while} is the last element of the @code{let} expression, the
10630 function will always return @code{nil}.  This is not what we want!
10631 Instead, what we want is the value of the variable @code{total}.  This
10632 is returned by simply placing the symbol as the last element of the list
10633 starting with @code{let}.  It gets evaluated after the preceding
10634 elements of the list are evaluated, which means it gets evaluated after
10635 it has been assigned the correct value for the total.
10637 It may be easier to see this by printing the list starting with
10638 @code{let} all on one line.  This format makes it evident that the
10639 @var{varlist} and @code{while} expressions are the second and third
10640 elements of the list starting with @code{let}, and the @code{total} is
10641 the last element:
10643 @smallexample
10644 @group
10645 (let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10646 @end group
10647 @end smallexample
10649 @need 1200
10650 Putting everything together, the @code{triangle} function definition
10651 looks like this:
10653 @smallexample
10654 @group
10655 (defun triangle (number-of-rows)    ; @r{Version with}
10656                                     ; @r{  incrementing counter.}
10657   "Add up the number of pebbles in a triangle.
10658 The first row has one pebble, the second row two pebbles,
10659 the third row three pebbles, and so on.
10660 The argument is NUMBER-OF-ROWS."
10661 @end group
10662 @group
10663   (let ((total 0)
10664         (row-number 1))
10665     (while (<= row-number number-of-rows)
10666       (setq total (+ total row-number))
10667       (setq row-number (1+ row-number)))
10668     total))
10669 @end group
10670 @end smallexample
10672 @need 1200
10673 After you have installed @code{triangle} by evaluating the function, you
10674 can try it out.  Here are two examples:
10676 @smallexample
10677 @group
10678 (triangle 4)
10680 (triangle 7)
10681 @end group
10682 @end smallexample
10684 @noindent
10685 The sum of the first four numbers is 10 and the sum of the first seven
10686 numbers is 28.
10688 @node Decrementing Loop
10689 @subsection Loop with a Decrementing Counter
10691 Another common way to write a @code{while} loop is to write the test
10692 so that it determines whether a counter is greater than zero.  So long
10693 as the counter is greater than zero, the loop is repeated.  But when
10694 the counter is equal to or less than zero, the loop is stopped.  For
10695 this to work, the counter has to start out greater than zero and then
10696 be made smaller and smaller by a form that is evaluated
10697 repeatedly.
10699 The test will be an expression such as @code{(> counter 0)} which
10700 returns @code{t} for true if the value of @code{counter} is greater
10701 than zero, and @code{nil} for false if the value of @code{counter} is
10702 equal to or less than zero.  The expression that makes the number
10703 smaller and smaller can be a simple @code{setq} such as @code{(setq
10704 counter (1- counter))}, where @code{1-} is a built-in function in
10705 Emacs Lisp that subtracts 1 from its argument.
10707 @need 1250
10708 The template for a decrementing @code{while} loop looks like this:
10710 @smallexample
10711 @group
10712 (while (> counter 0)                    ; @r{true-or-false-test}
10713   @var{body}@dots{}
10714   (setq counter (1- counter)))          ; @r{decrementer}
10715 @end group
10716 @end smallexample
10718 @menu
10719 * Decrementing Example::        More pebbles on the beach.
10720 * Dec Example parts::           The parts of the function definition.
10721 * Dec Example altogether::      Putting the function definition together.
10722 @end menu
10724 @node Decrementing Example
10725 @unnumberedsubsubsec Example with decrementing counter
10727 To illustrate a loop with a decrementing counter, we will rewrite the
10728 @code{triangle} function so the counter decreases to zero.
10730 This is the reverse of the earlier version of the function.  In this
10731 case, to find out how many pebbles are needed to make a triangle with
10732 3 rows, add the number of pebbles in the third row, 3, to the number
10733 in the preceding row, 2, and then add the total of those two rows to
10734 the row that precedes them, which is 1.
10736 Likewise, to find the number of pebbles in a triangle with 7 rows, add
10737 the number of pebbles in the seventh row, 7, to the number in the
10738 preceding row, which is 6, and then add the total of those two rows to
10739 the row that precedes them, which is 5, and so on.  As in the previous
10740 example, each addition only involves adding two numbers, the total of
10741 the rows already added up and the number of pebbles in the row that is
10742 being added to the total.  This process of adding two numbers is
10743 repeated again and again until there are no more pebbles to add.
10745 We know how many pebbles to start with: the number of pebbles in the
10746 last row is equal to the number of rows.  If the triangle has seven
10747 rows, the number of pebbles in the last row is 7.  Likewise, we know how
10748 many pebbles are in the preceding row: it is one less than the number in
10749 the row.
10751 @node Dec Example parts
10752 @unnumberedsubsubsec The parts of the function definition
10754 We start with three variables: the total number of rows in the
10755 triangle; the number of pebbles in a row; and the total number of
10756 pebbles, which is what we want to calculate.  These variables can be
10757 named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10758 @code{total}, respectively.
10760 Both @code{total} and @code{number-of-pebbles-in-row} are used only
10761 inside the function and are declared with @code{let}.  The initial
10762 value of @code{total} should, of course, be zero.  However, the
10763 initial value of @code{number-of-pebbles-in-row} should be equal to
10764 the number of rows in the triangle, since the addition will start with
10765 the longest row.
10767 @need 1250
10768 This means that the beginning of the @code{let} expression will look
10769 like this:
10771 @smallexample
10772 @group
10773 (let ((total 0)
10774       (number-of-pebbles-in-row number-of-rows))
10775   @var{body}@dots{})
10776 @end group
10777 @end smallexample
10779 The total number of pebbles can be found by repeatedly adding the number
10780 of pebbles in a row to the total already found, that is, by repeatedly
10781 evaluating the following expression:
10783 @smallexample
10784 (setq total (+ total number-of-pebbles-in-row))
10785 @end smallexample
10787 @noindent
10788 After the @code{number-of-pebbles-in-row} is added to the @code{total},
10789 the @code{number-of-pebbles-in-row} should be decremented by one, since
10790 the next time the loop repeats, the preceding row will be
10791 added to the total.
10793 The number of pebbles in a preceding row is one less than the number of
10794 pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10795 used to compute the number of pebbles in the preceding row.  This can be
10796 done with the following expression:
10798 @smallexample
10799 @group
10800 (setq number-of-pebbles-in-row
10801       (1- number-of-pebbles-in-row))
10802 @end group
10803 @end smallexample
10805 Finally, we know that the @code{while} loop should stop making repeated
10806 additions when there are no pebbles in a row.  So the test for
10807 the @code{while} loop is simply:
10809 @smallexample
10810 (while (> number-of-pebbles-in-row 0)
10811 @end smallexample
10813 @node Dec Example altogether
10814 @unnumberedsubsubsec Putting the function definition together
10816 We can put these expressions together to create a function definition
10817 that works.  However, on examination, we find that one of the local
10818 variables is unneeded!
10820 @need 1250
10821 The function definition looks like this:
10823 @smallexample
10824 @group
10825 ;;; @r{First subtractive version.}
10826 (defun triangle (number-of-rows)
10827   "Add up the number of pebbles in a triangle."
10828   (let ((total 0)
10829         (number-of-pebbles-in-row number-of-rows))
10830     (while (> number-of-pebbles-in-row 0)
10831       (setq total (+ total number-of-pebbles-in-row))
10832       (setq number-of-pebbles-in-row
10833             (1- number-of-pebbles-in-row)))
10834     total))
10835 @end group
10836 @end smallexample
10838 As written, this function works.
10840 However, we do not need @code{number-of-pebbles-in-row}.
10842 @cindex Argument as local variable
10843 When the @code{triangle} function is evaluated, the symbol
10844 @code{number-of-rows} will be bound to a number, giving it an initial
10845 value.  That number can be changed in the body of the function as if
10846 it were a local variable, without any fear that such a change will
10847 effect the value of the variable outside of the function.  This is a
10848 very useful characteristic of Lisp; it means that the variable
10849 @code{number-of-rows} can be used anywhere in the function where
10850 @code{number-of-pebbles-in-row} is used.
10852 @need 800
10853 Here is a second version of the function written a bit more cleanly:
10855 @smallexample
10856 @group
10857 (defun triangle (number)                ; @r{Second version.}
10858   "Return sum of numbers 1 through NUMBER inclusive."
10859   (let ((total 0))
10860     (while (> number 0)
10861       (setq total (+ total number))
10862       (setq number (1- number)))
10863     total))
10864 @end group
10865 @end smallexample
10867 In brief, a properly written @code{while} loop will consist of three parts:
10869 @enumerate
10870 @item
10871 A test that will return false after the loop has repeated itself the
10872 correct number of times.
10874 @item
10875 An expression the evaluation of which will return the value desired
10876 after being repeatedly evaluated.
10878 @item
10879 An expression to change the value passed to the true-or-false-test so
10880 that the test returns false after the loop has repeated itself the right
10881 number of times.
10882 @end enumerate
10884 @node dolist dotimes
10885 @section Save your time: @code{dolist} and @code{dotimes}
10887 In addition to @code{while}, both @code{dolist} and @code{dotimes}
10888 provide for looping.  Sometimes these are quicker to write than the
10889 equivalent @code{while} loop.  Both are Lisp macros.  (@xref{Macros, ,
10890 Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
10892 @code{dolist} works like a @code{while} loop that @sc{cdr}s down a
10893 list:  @code{dolist} automatically shortens the list each time it
10894 loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
10895 each shorter version of the list to the first of its arguments.
10897 @code{dotimes} loops a specific number of times: you specify the number.
10899 @menu
10900 * dolist::
10901 * dotimes::
10902 @end menu
10904 @node dolist
10905 @unnumberedsubsec The @code{dolist} Macro
10906 @findex dolist
10908 Suppose, for example, you want to reverse a list, so that
10909 ``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
10911 @need 1250
10912 In practice, you would use the @code{reverse} function, like this:
10914 @smallexample
10915 @group
10916 (setq animals '(gazelle giraffe lion tiger))
10918 (reverse animals)
10919 @end group
10920 @end smallexample
10922 @need 800
10923 @noindent
10924 Here is how you could reverse the list using a @code{while} loop:
10926 @smallexample
10927 @group
10928 (setq animals '(gazelle giraffe lion tiger))
10930 (defun reverse-list-with-while (list)
10931   "Using while, reverse the order of LIST."
10932   (let (value)  ; make sure list starts empty
10933     (while list
10934       (setq value (cons (car list) value))
10935       (setq list (cdr list)))
10936     value))
10938 (reverse-list-with-while animals)
10939 @end group
10940 @end smallexample
10942 @need 800
10943 @noindent
10944 And here is how you could use the @code{dolist} macro:
10946 @smallexample
10947 @group
10948 (setq animals '(gazelle giraffe lion tiger))
10950 (defun reverse-list-with-dolist (list)
10951   "Using dolist, reverse the order of LIST."
10952   (let (value)  ; make sure list starts empty
10953     (dolist (element list value)
10954       (setq value (cons element value)))))
10956 (reverse-list-with-dolist animals)
10957 @end group
10958 @end smallexample
10960 @need 1250
10961 @noindent
10962 In Info, you can place your cursor after the closing parenthesis of
10963 each expression and type @kbd{C-x C-e}; in each case, you should see
10965 @smallexample
10966 (tiger lion giraffe gazelle)
10967 @end smallexample
10969 @noindent
10970 in the echo area.
10972 For this example, the existing @code{reverse} function is obviously best.
10973 The @code{while} loop is just like our first example (@pxref{Loop
10974 Example, , A @code{while} Loop and a List}).  The @code{while} first
10975 checks whether the list has elements; if so, it constructs a new list
10976 by adding the first element of the list to the existing list (which in
10977 the first iteration of the loop is @code{nil}).  Since the second
10978 element is prepended in front of the first element, and the third
10979 element is prepended in front of the second element, the list is reversed.
10981 In the expression using a @code{while} loop,
10982 the @w{@code{(setq list (cdr list))}}
10983 expression shortens the list, so the @code{while} loop eventually
10984 stops.  In addition, it provides the @code{cons} expression with a new
10985 first element by creating a new and shorter list at each repetition of
10986 the loop.
10988 The @code{dolist} expression does very much the same as the
10989 @code{while} expression, except that the @code{dolist} macro does some
10990 of the work you have to do when writing a @code{while} expression.
10992 Like a @code{while} loop, a @code{dolist} loops.  What is different is
10993 that it automatically shortens the list each time it loops---it
10994 @sc{cdr}s down the list on its own---and it automatically binds
10995 the @sc{car} of each shorter version of the list to the first of its
10996 arguments.
10998 In the example, the @sc{car} of each shorter version of the list is
10999 referred to using the symbol @samp{element}, the list itself is called
11000 @samp{list}, and the value returned is called @samp{value}.  The
11001 remainder of the @code{dolist} expression is the body.
11003 The @code{dolist} expression binds the @sc{car} of each shorter
11004 version of the list to @code{element} and then evaluates the body of
11005 the expression; and repeats the loop.  The result is returned in
11006 @code{value}.
11008 @node dotimes
11009 @unnumberedsubsec The @code{dotimes} Macro
11010 @findex dotimes
11012 The @code{dotimes} macro is similar to @code{dolist}, except that it
11013 loops a specific number of times.
11015 The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
11016 and so forth each time around the loop, and the value of the third
11017 argument is returned.  You need to provide the value of the second
11018 argument, which is how many times the macro loops.
11020 @need 1250
11021 For example, the following binds the numbers from 0 up to, but not
11022 including, the number 3 to the first argument, @var{number}, and then
11023 constructs a list of the three numbers.  (The first number is 0, the
11024 second number is 1, and the third number is 2; this makes a total of
11025 three numbers in all, starting with zero as the first number.)
11027 @smallexample
11028 @group
11029 (let (value)      ; otherwise a value is a void variable
11030   (dotimes (number 3 value)
11031     (setq value (cons number value))))
11033 @result{} (2 1 0)
11034 @end group
11035 @end smallexample
11037 @noindent
11038 @code{dotimes} returns @code{value}, so the way to use
11039 @code{dotimes} is to operate on some expression @var{number} number of
11040 times and then return the result, either as a list or an atom.
11042 @need 1250
11043 Here is an example of a @code{defun} that uses @code{dotimes} to add
11044 up the number of pebbles in a triangle.
11046 @smallexample
11047 @group
11048 (defun triangle-using-dotimes (number-of-rows)
11049   "Using `dotimes', add up the number of pebbles in a triangle."
11050 (let ((total 0))  ; otherwise a total is a void variable
11051   (dotimes (number number-of-rows total)
11052     (setq total (+ total (1+ number))))))
11054 (triangle-using-dotimes 4)
11055 @end group
11056 @end smallexample
11058 @node Recursion
11059 @section Recursion
11060 @cindex Recursion
11062 A recursive function contains code that tells the Lisp interpreter to
11063 call a program that runs exactly like itself, but with slightly
11064 different arguments.  The code runs exactly the same because it has
11065 the same name.  However, even though the program has the same name, it
11066 is not the same entity.  It is different.  In the jargon, it is a
11067 different ``instance''.
11069 Eventually, if the program is written correctly, the slightly
11070 different arguments will become sufficiently different from the first
11071 arguments that the final instance will stop.
11073 @menu
11074 * Building Robots::             Same model, different serial number ...
11075 * Recursive Definition Parts::  Walk until you stop ...
11076 * Recursion with list::         Using a list as the test whether to recurse.
11077 * Recursive triangle function::
11078 * Recursion with cond::
11079 * Recursive Patterns::          Often used templates.
11080 * No Deferment::                Don't store up work ...
11081 * No deferment solution::
11082 @end menu
11084 @node Building Robots
11085 @subsection Building Robots: Extending the Metaphor
11086 @cindex Building robots
11087 @cindex Robots, building
11089 It is sometimes helpful to think of a running program as a robot that
11090 does a job.  In doing its job, a recursive function calls on a second
11091 robot to help it.  The second robot is identical to the first in every
11092 way, except that the second robot helps the first and has been
11093 passed different arguments than the first.
11095 In a recursive function, the second robot may call a third; and the
11096 third may call a fourth, and so on.  Each of these is a different
11097 entity; but all are clones.
11099 Since each robot has slightly different instructions---the arguments
11100 will differ from one robot to the next---the last robot should know
11101 when to stop.
11103 Let's expand on the metaphor in which a computer program is a robot.
11105 A function definition provides the blueprints for a robot.  When you
11106 install a function definition, that is, when you evaluate a
11107 @code{defun} macro, you install the necessary equipment to build
11108 robots.  It is as if you were in a factory, setting up an assembly
11109 line.  Robots with the same name are built according to the same
11110 blueprints.  So they have the same model number, but a
11111 different serial number.
11113 We often say that a recursive function ``calls itself''.  What we mean
11114 is that the instructions in a recursive function cause the Lisp
11115 interpreter to run a different function that has the same name and
11116 does the same job as the first, but with different arguments.
11118 It is important that the arguments differ from one instance to the
11119 next; otherwise, the process will never stop.
11121 @node Recursive Definition Parts
11122 @subsection The Parts of a Recursive Definition
11123 @cindex Parts of a Recursive Definition
11124 @cindex Recursive Definition Parts
11126 A recursive function typically contains a conditional expression which
11127 has three parts:
11129 @enumerate
11130 @item
11131 A true-or-false-test that determines whether the function is called
11132 again, here called the @dfn{do-again-test}.
11134 @item
11135 The name of the function.  When this name is called, a new instance of
11136 the function---a new robot, as it were---is created and told what to do.
11138 @item
11139 An expression that returns a different value each time the function is
11140 called, here called the @dfn{next-step-expression}.  Consequently, the
11141 argument (or arguments) passed to the new instance of the function
11142 will be different from that passed to the previous instance.  This
11143 causes the conditional expression, the @dfn{do-again-test}, to test
11144 false after the correct number of repetitions.
11145 @end enumerate
11147 Recursive functions can be much simpler than any other kind of
11148 function.  Indeed, when people first start to use them, they often look
11149 so mysteriously simple as to be incomprehensible.  Like riding a
11150 bicycle, reading a recursive function definition takes a certain knack
11151 which is hard at first but then seems simple.
11153 @need 1200
11154 There are several different common recursive patterns.  A very simple
11155 pattern looks like this:
11157 @smallexample
11158 @group
11159 (defun @var{name-of-recursive-function} (@var{argument-list})
11160   "@var{documentation}@dots{}"
11161   (if @var{do-again-test}
11162     @var{body}@dots{}
11163     (@var{name-of-recursive-function}
11164          @var{next-step-expression})))
11165 @end group
11166 @end smallexample
11168 Each time a recursive function is evaluated, a new instance of it is
11169 created and told what to do.  The arguments tell the instance what to do.
11171 An argument is bound to the value of the next-step-expression.  Each
11172 instance runs with a different value of the next-step-expression.
11174 The value in the next-step-expression is used in the do-again-test.
11176 The value returned by the next-step-expression is passed to the new
11177 instance of the function, which evaluates it (or some
11178 transmogrification of it) to determine whether to continue or stop.
11179 The next-step-expression is designed so that the do-again-test returns
11180 false when the function should no longer be repeated.
11182 The do-again-test is sometimes called the @dfn{stop condition},
11183 since it stops the repetitions when it tests false.
11185 @node Recursion with list
11186 @subsection Recursion with a List
11188 The example of a @code{while} loop that printed the elements of a list
11189 of numbers can be written recursively.  Here is the code, including
11190 an expression to set the value of the variable @code{animals} to a list.
11192 If you are reading this in Info in Emacs, you can evaluate this
11193 expression directly in Info.  Otherwise, you must copy the example
11194 to the @file{*scratch*} buffer and evaluate each expression there.
11195 Use @kbd{C-u C-x C-e} to evaluate the
11196 @code{(print-elements-recursively animals)} expression so that the
11197 results are printed in the buffer; otherwise the Lisp interpreter will
11198 try to squeeze the results into the one line of the echo area.
11200 Also, place your cursor immediately after the last closing parenthesis
11201 of the @code{print-elements-recursively} function, before the comment.
11202 Otherwise, the Lisp interpreter will try to evaluate the comment.
11204 @findex print-elements-recursively
11205 @smallexample
11206 @group
11207 (setq animals '(gazelle giraffe lion tiger))
11209 (defun print-elements-recursively (list)
11210   "Print each element of LIST on a line of its own.
11211 Uses recursion."
11212   (when list                            ; @r{do-again-test}
11213         (print (car list))              ; @r{body}
11214         (print-elements-recursively     ; @r{recursive call}
11215          (cdr list))))                  ; @r{next-step-expression}
11217 (print-elements-recursively animals)
11218 @end group
11219 @end smallexample
11221 The @code{print-elements-recursively} function first tests whether
11222 there is any content in the list; if there is, the function prints the
11223 first element of the list, the @sc{car} of the list.  Then the
11224 function invokes itself, but gives itself as its argument, not the
11225 whole list, but the second and subsequent elements of the list, the
11226 @sc{cdr} of the list.
11228 Put another way, if the list is not empty, the function invokes
11229 another instance of code that is similar to the initial code, but is a
11230 different thread of execution, with different arguments than the first
11231 instance.
11233 Put in yet another way, if the list is not empty, the first robot
11234 assembles a second robot and tells it what to do; the second robot is
11235 a different individual from the first, but is the same model.
11237 When the second evaluation occurs, the @code{when} expression is
11238 evaluated and if true, prints the first element of the list it
11239 receives as its argument (which is the second element of the original
11240 list).  Then the function calls itself with the @sc{cdr} of the list
11241 it is invoked with, which (the second time around) is the @sc{cdr} of
11242 the @sc{cdr} of the original list.
11244 Note that although we say that the function ``calls itself'', what we
11245 mean is that the Lisp interpreter assembles and instructs a new
11246 instance of the program.  The new instance is a clone of the first,
11247 but is a separate individual.
11249 Each time the function invokes itself, it does so on a
11250 shorter version of the original list.  It creates a new instance that
11251 works on a shorter list.
11253 Eventually, the function invokes itself on an empty list.  It creates
11254 a new instance whose argument is @code{nil}.  The conditional expression
11255 tests the value of @code{list}.  Since the value of @code{list} is
11256 @code{nil}, the @code{when} expression tests false so the then-part is
11257 not evaluated.  The function as a whole then returns @code{nil}.
11259 @need 1200
11260 When you evaluate the expression @code{(print-elements-recursively
11261 animals)} in the @file{*scratch*} buffer, you see this result:
11263 @smallexample
11264 @group
11265 gazelle
11267 giraffe
11269 lion
11271 tiger
11273 @end group
11274 @end smallexample
11276 @need 2000
11277 @node Recursive triangle function
11278 @subsection Recursion in Place of a Counter
11279 @findex triangle-recursively
11281 @need 1200
11282 The @code{triangle} function described in a previous section can also
11283 be written recursively.  It looks like this:
11285 @smallexample
11286 @group
11287 (defun triangle-recursively (number)
11288   "Return the sum of the numbers 1 through NUMBER inclusive.
11289 Uses recursion."
11290   (if (= number 1)                    ; @r{do-again-test}
11291       1                               ; @r{then-part}
11292     (+ number                         ; @r{else-part}
11293        (triangle-recursively          ; @r{recursive call}
11294         (1- number)))))               ; @r{next-step-expression}
11296 (triangle-recursively 7)
11297 @end group
11298 @end smallexample
11300 @noindent
11301 You can install this function by evaluating it and then try it by
11302 evaluating @code{(triangle-recursively 7)}.  (Remember to put your
11303 cursor immediately after the last parenthesis of the function
11304 definition, before the comment.)  The function evaluates to 28.
11306 To understand how this function works, let's consider what happens in the
11307 various cases when the function is passed 1, 2, 3, or 4 as the value of
11308 its argument.
11310 @menu
11311 * Recursive Example arg of 1 or 2::
11312 * Recursive Example arg of 3 or 4::
11313 @end menu
11315 @ifnottex
11316 @node Recursive Example arg of 1 or 2
11317 @unnumberedsubsubsec An argument of 1 or 2
11318 @end ifnottex
11320 First, what happens if the value of the argument is 1?
11322 The function has an @code{if} expression after the documentation
11323 string.  It tests whether the value of @code{number} is equal to 1; if
11324 so, Emacs evaluates the then-part of the @code{if} expression, which
11325 returns the number 1 as the value of the function.  (A triangle with
11326 one row has one pebble in it.)
11328 Suppose, however, that the value of the argument is 2.  In this case,
11329 Emacs evaluates the else-part of the @code{if} expression.
11331 @need 1200
11332 The else-part consists of an addition, the recursive call to
11333 @code{triangle-recursively} and a decrementing action; and it looks like
11334 this:
11336 @smallexample
11337 (+ number (triangle-recursively (1- number)))
11338 @end smallexample
11340 When Emacs evaluates this expression, the innermost expression is
11341 evaluated first; then the other parts in sequence.  Here are the steps
11342 in detail:
11344 @table @i
11345 @item Step 1 @w{  } Evaluate the innermost expression.
11347 The innermost expression is @code{(1- number)} so Emacs decrements the
11348 value of @code{number} from 2 to 1.
11350 @item Step 2 @w{  } Evaluate the @code{triangle-recursively} function.
11352 The Lisp interpreter creates an individual instance of
11353 @code{triangle-recursively}.  It does not matter that this function is
11354 contained within itself.  Emacs passes the result Step 1 as the
11355 argument used by this instance of the @code{triangle-recursively}
11356 function
11358 In this case, Emacs evaluates @code{triangle-recursively} with an
11359 argument of 1.  This means that this evaluation of
11360 @code{triangle-recursively} returns 1.
11362 @item Step 3 @w{  } Evaluate the value of @code{number}.
11364 The variable @code{number} is the second element of the list that
11365 starts with @code{+}; its value is 2.
11367 @item Step 4 @w{  } Evaluate the @code{+} expression.
11369 The @code{+} expression receives two arguments, the first
11370 from the evaluation of @code{number} (Step 3) and the second from the
11371 evaluation of @code{triangle-recursively} (Step 2).
11373 The result of the addition is the sum of 2 plus 1, and the number 3 is
11374 returned, which is correct.  A triangle with two rows has three
11375 pebbles in it.
11376 @end table
11378 @node Recursive Example arg of 3 or 4
11379 @unnumberedsubsubsec An argument of 3 or 4
11381 Suppose that @code{triangle-recursively} is called with an argument of
11384 @table @i
11385 @item Step 1 @w{  } Evaluate the do-again-test.
11387 The @code{if} expression is evaluated first.  This is the do-again
11388 test and returns false, so the else-part of the @code{if} expression
11389 is evaluated.  (Note that in this example, the do-again-test causes
11390 the function to call itself when it tests false, not when it tests
11391 true.)
11393 @item Step 2 @w{  } Evaluate the innermost expression of the else-part.
11395 The innermost expression of the else-part is evaluated, which decrements
11396 3 to 2.  This is the next-step-expression.
11398 @item Step 3 @w{  } Evaluate the @code{triangle-recursively} function.
11400 The number 2 is passed to the @code{triangle-recursively} function.
11402 We already know what happens when Emacs evaluates @code{triangle-recursively} with
11403 an argument of 2.  After going through the sequence of actions described
11404 earlier, it returns a value of 3.  So that is what will happen here.
11406 @item Step 4 @w{  } Evaluate the addition.
11408 3 will be passed as an argument to the addition and will be added to the
11409 number with which the function was called, which is 3.
11410 @end table
11412 @noindent
11413 The value returned by the function as a whole will be 6.
11415 Now that we know what will happen when @code{triangle-recursively} is
11416 called with an argument of 3, it is evident what will happen if it is
11417 called with an argument of 4:
11419 @quotation
11420 @need 800
11421 In the recursive call, the evaluation of
11423 @smallexample
11424 (triangle-recursively (1- 4))
11425 @end smallexample
11427 @need 800
11428 @noindent
11429 will return the value of evaluating
11431 @smallexample
11432 (triangle-recursively 3)
11433 @end smallexample
11435 @noindent
11436 which is 6 and this value will be added to 4 by the addition in the
11437 third line.
11438 @end quotation
11440 @noindent
11441 The value returned by the function as a whole will be 10.
11443 Each time @code{triangle-recursively} is evaluated, it evaluates a
11444 version of itself---a different instance of itself---with a smaller
11445 argument, until the argument is small enough so that it does not
11446 evaluate itself.
11448 Note that this particular design for a recursive function
11449 requires that operations be deferred.
11451 Before @code{(triangle-recursively 7)} can calculate its answer, it
11452 must call @code{(triangle-recursively 6)}; and before
11453 @code{(triangle-recursively 6)} can calculate its answer, it must call
11454 @code{(triangle-recursively 5)}; and so on.  That is to say, the
11455 calculation that @code{(triangle-recursively 7)} makes must be
11456 deferred until @code{(triangle-recursively 6)} makes its calculation;
11457 and @code{(triangle-recursively 6)} must defer until
11458 @code{(triangle-recursively 5)} completes; and so on.
11460 If each of these instances of @code{triangle-recursively} are thought
11461 of as different robots, the first robot must wait for the second to
11462 complete its job, which must wait until the third completes, and so
11465 There is a way around this kind of waiting, which we will discuss in
11466 @ref{No Deferment, , Recursion without Deferments}.
11468 @node Recursion with cond
11469 @subsection Recursion Example Using @code{cond}
11470 @findex cond
11472 The version of @code{triangle-recursively} described earlier is written
11473 with the @code{if} special form.  It can also be written using another
11474 special form called @code{cond}.  The name of the special form
11475 @code{cond} is an abbreviation of the word @samp{conditional}.
11477 Although the @code{cond} special form is not used as often in the
11478 Emacs Lisp sources as @code{if}, it is used often enough to justify
11479 explaining it.
11481 @need 800
11482 The template for a @code{cond} expression looks like this:
11484 @smallexample
11485 @group
11486 (cond
11487  @var{body}@dots{})
11488 @end group
11489 @end smallexample
11491 @noindent
11492 where the @var{body} is a series of lists.
11494 @need 800
11495 Written out more fully, the template looks like this:
11497 @smallexample
11498 @group
11499 (cond
11500  (@var{first-true-or-false-test} @var{first-consequent})
11501  (@var{second-true-or-false-test} @var{second-consequent})
11502  (@var{third-true-or-false-test} @var{third-consequent})
11503   @dots{})
11504 @end group
11505 @end smallexample
11507 When the Lisp interpreter evaluates the @code{cond} expression, it
11508 evaluates the first element (the @sc{car} or true-or-false-test) of
11509 the first expression in a series of expressions within the body of the
11510 @code{cond}.
11512 If the true-or-false-test returns @code{nil} the rest of that
11513 expression, the consequent, is skipped and  the true-or-false-test of the
11514 next expression is evaluated.  When an expression is found whose
11515 true-or-false-test returns a value that is not @code{nil}, the
11516 consequent of that expression is evaluated.  The consequent can be one
11517 or more expressions.  If the consequent consists of more than one
11518 expression, the expressions are evaluated in sequence and the value of
11519 the last one is returned.  If the expression does not have a consequent,
11520 the value of the true-or-false-test is returned.
11522 If none of the true-or-false-tests test true, the @code{cond} expression
11523 returns @code{nil}.
11525 @need 1250
11526 Written using @code{cond}, the @code{triangle} function looks like this:
11528 @smallexample
11529 @group
11530 (defun triangle-using-cond (number)
11531   (cond ((<= number 0) 0)
11532         ((= number 1) 1)
11533         ((> number 1)
11534          (+ number (triangle-using-cond (1- number))))))
11535 @end group
11536 @end smallexample
11538 @noindent
11539 In this example, the @code{cond} returns 0 if the number is less than or
11540 equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11541 number (triangle-using-cond (1- number)))} if the number is greater than
11544 @node Recursive Patterns
11545 @subsection Recursive Patterns
11546 @cindex Recursive Patterns
11548 Here are three common recursive patterns.  Each involves a list.
11549 Recursion does not need to involve lists, but Lisp is designed for lists
11550 and this provides a sense of its primal capabilities.
11552 @menu
11553 * Every::
11554 * Accumulate::
11555 * Keep::
11556 @end menu
11558 @node Every
11559 @unnumberedsubsubsec Recursive Pattern: @emph{every}
11560 @cindex Every, type of recursive pattern
11561 @cindex Recursive pattern - every
11563 In the @code{every} recursive pattern, an action is performed on every
11564 element of a list.
11566 @need 1500
11567 The basic pattern is:
11569 @itemize @bullet
11570 @item
11571 If a list be empty, return @code{nil}.
11572 @item
11573 Else, act on the beginning of the list (the @sc{car} of the list)
11574     @itemize @minus
11575     @item
11576     through a recursive call by the function on the rest (the
11577     @sc{cdr}) of the list,
11578     @item
11579     and, optionally, combine the acted-on element, using @code{cons},
11580     with the results of acting on the rest.
11581     @end itemize
11582 @end itemize
11584 @need 1500
11585 Here is an example:
11587 @smallexample
11588 @group
11589 (defun square-each (numbers-list)
11590   "Square each of a NUMBERS LIST, recursively."
11591   (if (not numbers-list)                ; do-again-test
11592       nil
11593     (cons
11594      (* (car numbers-list) (car numbers-list))
11595      (square-each (cdr numbers-list))))) ; next-step-expression
11596 @end group
11598 @group
11599 (square-each '(1 2 3))
11600     @result{} (1 4 9)
11601 @end group
11602 @end smallexample
11604 @need 1200
11605 @noindent
11606 If @code{numbers-list} is empty, do nothing.  But if it has content,
11607 construct a list combining the square of the first number in the list
11608 with the result of the recursive call.
11610 (The example follows the pattern exactly: @code{nil} is returned if
11611 the numbers' list is empty.  In practice, you would write the
11612 conditional so it carries out the action when the numbers' list is not
11613 empty.)
11615 The @code{print-elements-recursively} function (@pxref{Recursion with
11616 list, , Recursion with a List}) is another example of an @code{every}
11617 pattern, except in this case, rather than bring the results together
11618 using @code{cons}, we print each element of output.
11620 @need 1250
11621 The @code{print-elements-recursively} function looks like this:
11623 @smallexample
11624 @group
11625 (setq animals '(gazelle giraffe lion tiger))
11626 @end group
11628 @group
11629 (defun print-elements-recursively (list)
11630   "Print each element of LIST on a line of its own.
11631 Uses recursion."
11632   (when list                            ; @r{do-again-test}
11633         (print (car list))              ; @r{body}
11634         (print-elements-recursively     ; @r{recursive call}
11635          (cdr list))))                  ; @r{next-step-expression}
11637 (print-elements-recursively animals)
11638 @end group
11639 @end smallexample
11641 @need 1500
11642 The pattern for @code{print-elements-recursively} is:
11644 @itemize @bullet
11645 @item
11646 When the list is empty, do nothing.
11647 @item
11648 But when the list has at least one element,
11649     @itemize @minus
11650     @item
11651     act on the beginning of the list (the @sc{car} of the list),
11652     @item
11653     and make a recursive call on the rest (the @sc{cdr}) of the list.
11654     @end itemize
11655 @end itemize
11657 @node Accumulate
11658 @unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11659 @cindex Accumulate, type of recursive pattern
11660 @cindex Recursive pattern - accumulate
11662 Another recursive pattern is called the @code{accumulate} pattern.  In
11663 the @code{accumulate} recursive pattern, an action is performed on
11664 every element of a list and the result of that action is accumulated
11665 with the results of performing the action on the other elements.
11667 This is very like the @code{every} pattern using @code{cons}, except that
11668 @code{cons} is not used, but some other combiner.
11670 @need 1500
11671 The pattern is:
11673 @itemize @bullet
11674 @item
11675 If a list be empty, return zero or some other constant.
11676 @item
11677 Else, act on the beginning of the list (the @sc{car} of the list),
11678     @itemize @minus
11679     @item
11680     and combine that acted-on element, using @code{+} or
11681     some other combining function, with
11682     @item
11683     a recursive call by the function on the rest (the @sc{cdr}) of the list.
11684     @end itemize
11685 @end itemize
11687 @need 1500
11688 Here is an example:
11690 @smallexample
11691 @group
11692 (defun add-elements (numbers-list)
11693   "Add the elements of NUMBERS-LIST together."
11694   (if (not numbers-list)
11695       0
11696     (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11697 @end group
11699 @group
11700 (add-elements '(1 2 3 4))
11701     @result{} 10
11702 @end group
11703 @end smallexample
11705 @xref{Files List, , Making a List of Files}, for an example of the
11706 accumulate pattern.
11708 @node Keep
11709 @unnumberedsubsubsec Recursive Pattern: @emph{keep}
11710 @cindex Keep, type of recursive pattern
11711 @cindex Recursive pattern - keep
11713 A third recursive pattern is called the @code{keep} pattern.
11714 In the @code{keep} recursive pattern, each element of a list is tested;
11715 the element is acted on and the results are kept only if the element
11716 meets a criterion.
11718 Again, this is very like the @code{every} pattern, except the element is
11719 skipped unless it meets a criterion.
11721 @need 1500
11722 The pattern has three parts:
11724 @itemize @bullet
11725 @item
11726 If a list be empty, return @code{nil}.
11727 @item
11728 Else, if the beginning of the list (the @sc{car} of the list) passes
11729         a test
11730     @itemize @minus
11731     @item
11732     act on that element and combine it, using @code{cons} with
11733     @item
11734     a recursive call by the function on the rest (the @sc{cdr}) of the list.
11735     @end itemize
11736 @item
11737 Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11738 the test
11739     @itemize @minus
11740     @item
11741     skip on that element,
11742     @item
11743     and, recursively call the function on the rest (the @sc{cdr}) of the list.
11744     @end itemize
11745 @end itemize
11747 @need 1500
11748 Here is an example that uses @code{cond}:
11750 @smallexample
11751 @group
11752 (defun keep-three-letter-words (word-list)
11753   "Keep three letter words in WORD-LIST."
11754   (cond
11755    ;; First do-again-test: stop-condition
11756    ((not word-list) nil)
11758    ;; Second do-again-test: when to act
11759    ((eq 3 (length (symbol-name (car word-list))))
11760     ;; combine acted-on element with recursive call on shorter list
11761     (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11763    ;; Third do-again-test: when to skip element;
11764    ;;   recursively call shorter list with next-step expression
11765    (t (keep-three-letter-words (cdr word-list)))))
11766 @end group
11768 @group
11769 (keep-three-letter-words '(one two three four five six))
11770     @result{} (one two six)
11771 @end group
11772 @end smallexample
11774 It goes without saying that you need not use @code{nil} as the test for
11775 when to stop; and you can, of course, combine these patterns.
11777 @node No Deferment
11778 @subsection Recursion without Deferments
11779 @cindex Deferment in recursion
11780 @cindex Recursion without Deferments
11782 Let's consider again what happens with the @code{triangle-recursively}
11783 function.  We will find that the intermediate calculations are
11784 deferred until all can be done.
11786 @need 800
11787 Here is the function definition:
11789 @smallexample
11790 @group
11791 (defun triangle-recursively (number)
11792   "Return the sum of the numbers 1 through NUMBER inclusive.
11793 Uses recursion."
11794   (if (= number 1)                    ; @r{do-again-test}
11795       1                               ; @r{then-part}
11796     (+ number                         ; @r{else-part}
11797        (triangle-recursively          ; @r{recursive call}
11798         (1- number)))))               ; @r{next-step-expression}
11799 @end group
11800 @end smallexample
11802 What happens when we call this function with a argument of 7?
11804 The first instance of the @code{triangle-recursively} function adds
11805 the number 7 to the value returned by a second instance of
11806 @code{triangle-recursively}, an instance that has been passed an
11807 argument of 6.  That is to say, the first calculation is:
11809 @smallexample
11810 (+ 7 (triangle-recursively 6))
11811 @end smallexample
11813 @noindent
11814 The first instance of @code{triangle-recursively}---you may want to
11815 think of it as a little robot---cannot complete its job.  It must hand
11816 off the calculation for @code{(triangle-recursively 6)} to a second
11817 instance of the program, to a second robot.  This second individual is
11818 completely different from the first one; it is, in the jargon, a
11819 ``different instantiation''.  Or, put another way, it is a different
11820 robot.  It is the same model as the first; it calculates triangle
11821 numbers recursively; but it has a different serial number.
11823 And what does @code{(triangle-recursively 6)} return?  It returns the
11824 number 6 added to the value returned by evaluating
11825 @code{triangle-recursively} with an argument of 5.  Using the robot
11826 metaphor, it asks yet another robot to help it.
11828 @need 800
11829 Now the total is:
11831 @smallexample
11832 (+ 7 6 (triangle-recursively 5))
11833 @end smallexample
11835 @need 800
11836 And what happens next?
11838 @smallexample
11839 (+ 7 6 5 (triangle-recursively 4))
11840 @end smallexample
11842 Each time @code{triangle-recursively} is called, except for the last
11843 time, it creates another instance of the program---another robot---and
11844 asks it to make a calculation.
11846 @need 800
11847 Eventually, the full addition is set up and performed:
11849 @smallexample
11850 (+ 7 6 5 4 3 2 1)
11851 @end smallexample
11853 This design for the function defers the calculation of the first step
11854 until the second can be done, and defers that until the third can be
11855 done, and so on.  Each deferment means the computer must remember what
11856 is being waited on.  This is not a problem when there are only a few
11857 steps, as in this example.  But it can be a problem when there are
11858 more steps.
11860 @node No deferment solution
11861 @subsection No Deferment Solution
11862 @cindex No deferment solution
11863 @cindex Solution without deferment
11865 The solution to the problem of deferred operations is to write in a
11866 manner that does not defer operations@footnote{The phrase @dfn{tail
11867 recursive} is used to describe such a process, one that uses
11868 constant space.}.  This requires
11869 writing to a different pattern, often one that involves writing two
11870 function definitions, an initialization function and a helper
11871 function.
11873 The initialization function sets up the job; the helper function
11874 does the work.
11876 @need 1200
11877 Here are the two function definitions for adding up numbers.  They are
11878 so simple, I find them hard to understand.
11880 @smallexample
11881 @group
11882 (defun triangle-initialization (number)
11883   "Return the sum of the numbers 1 through NUMBER inclusive.
11884 This is the initialization component of a two function
11885 duo that uses recursion."
11886   (triangle-recursive-helper 0 0 number))
11887 @end group
11888 @end smallexample
11890 @smallexample
11891 @group
11892 (defun triangle-recursive-helper (sum counter number)
11893   "Return SUM, using COUNTER, through NUMBER inclusive.
11894 This is the helper component of a two function duo
11895 that uses recursion."
11896   (if (> counter number)
11897       sum
11898     (triangle-recursive-helper (+ sum counter)  ; @r{sum}
11899                                (1+ counter)     ; @r{counter}
11900                                number)))        ; @r{number}
11901 @end group
11902 @end smallexample
11904 @need 1250
11905 Install both function definitions by evaluating them, then call
11906 @code{triangle-initialization} with 2 rows:
11908 @smallexample
11909 @group
11910 (triangle-initialization 2)
11911     @result{} 3
11912 @end group
11913 @end smallexample
11915 The initialization function calls the first instance of the helper
11916 function with three arguments: zero, zero, and a number which is the
11917 number of rows in the triangle.
11919 The first two arguments passed to the helper function are
11920 initialization values.  These values are changed when
11921 @code{triangle-recursive-helper} invokes new instances.@footnote{The
11922 jargon is mildly confusing:  @code{triangle-recursive-helper} uses a
11923 process that is iterative in a procedure that is recursive.  The
11924 process is called iterative because the computer need only record the
11925 three values, @code{sum}, @code{counter}, and @code{number}; the
11926 procedure is recursive because the function calls itself.  On the
11927 other hand, both the process and the procedure used by
11928 @code{triangle-recursively} are called recursive.  The word
11929 ``recursive'' has different meanings in the two contexts.}
11931 Let's see what happens when we have a triangle that has one row.  (This
11932 triangle will have one pebble in it!)
11934 @need 1200
11935 @code{triangle-initialization} will call its helper with
11936 the arguments @w{@code{0 0 1}}.  That function will run the conditional
11937 test whether @code{(> counter number)}:
11939 @smallexample
11940 (> 0 1)
11941 @end smallexample
11943 @need 1200
11944 @noindent
11945 and find that the result is false, so it will invoke
11946 the else-part of the @code{if} clause:
11948 @smallexample
11949 @group
11950     (triangle-recursive-helper
11951      (+ sum counter)  ; @r{sum plus counter} @result{} @r{sum}
11952      (1+ counter)     ; @r{increment counter} @result{} @r{counter}
11953      number)          ; @r{number stays the same}
11954 @end group
11955 @end smallexample
11957 @need 800
11958 @noindent
11959 which will first compute:
11961 @smallexample
11962 @group
11963 (triangle-recursive-helper (+ 0 0)  ; @r{sum}
11964                            (1+ 0)   ; @r{counter}
11965                            1)       ; @r{number}
11966 @exdent which is:
11968 (triangle-recursive-helper 0 1 1)
11969 @end group
11970 @end smallexample
11972 Again, @code{(> counter number)} will be false, so again, the Lisp
11973 interpreter will evaluate @code{triangle-recursive-helper}, creating a
11974 new instance with new arguments.
11976 @need 800
11977 This new instance will be;
11979 @smallexample
11980 @group
11981     (triangle-recursive-helper
11982      (+ sum counter)  ; @r{sum plus counter} @result{} @r{sum}
11983      (1+ counter)     ; @r{increment counter} @result{} @r{counter}
11984      number)          ; @r{number stays the same}
11986 @exdent which is:
11988 (triangle-recursive-helper 1 2 1)
11989 @end group
11990 @end smallexample
11992 In this case, the @code{(> counter number)} test will be true!  So the
11993 instance will return the value of the sum, which will be 1, as
11994 expected.
11996 Now, let's pass @code{triangle-initialization} an argument
11997 of 2, to find out how many pebbles there are in a triangle with two rows.
11999 That function calls @code{(triangle-recursive-helper 0 0 2)}.
12001 @need 800
12002 In stages, the instances called will be:
12004 @smallexample
12005 @group
12006                           @r{sum counter number}
12007 (triangle-recursive-helper 0    1       2)
12009 (triangle-recursive-helper 1    2       2)
12011 (triangle-recursive-helper 3    3       2)
12012 @end group
12013 @end smallexample
12015 When the last instance is called, the @code{(> counter number)} test
12016 will be true, so the instance will return the value of @code{sum},
12017 which will be 3.
12019 This kind of pattern helps when you are writing functions that can use
12020 many resources in a computer.
12022 @need 1500
12023 @node Looping exercise
12024 @section Looping Exercise
12026 @itemize @bullet
12027 @item
12028 Write a function similar to @code{triangle} in which each row has a
12029 value which is the square of the row number.  Use a @code{while} loop.
12031 @item
12032 Write a function similar to @code{triangle} that multiplies instead of
12033 adds the values.
12035 @item
12036 Rewrite these two functions recursively.  Rewrite these functions
12037 using @code{cond}.
12039 @c comma in printed title causes problem in Info cross reference
12040 @item
12041 Write a function for Texinfo mode that creates an index entry at the
12042 beginning of a paragraph for every @samp{@@dfn} within the paragraph.
12043 (In a Texinfo file, @samp{@@dfn} marks a definition.  This book is
12044 written in Texinfo.)
12046 Many of the functions you will need are described in two of the
12047 previous chapters, @ref{Cutting & Storing Text, , Cutting and Storing
12048 Text}, and @ref{Yanking, , Yanking Text Back}.  If you use
12049 @code{forward-paragraph} to put the index entry at the beginning of
12050 the paragraph, you will have to use @w{@kbd{C-h f}}
12051 (@code{describe-function}) to find out how to make the command go
12052 backwards.
12054 For more information, see
12055 @ifinfo
12056 @ref{Indicating, , Indicating Definitions, texinfo}.
12057 @end ifinfo
12058 @ifhtml
12059 @ref{Indicating, , Indicating, texinfo, Texinfo Manual}, which goes to
12060 a Texinfo manual in the current directory.  Or, if you are on the
12061 Internet, see
12062 @uref{https://www.gnu.org/software/texinfo/manual/texinfo/}
12063 @end ifhtml
12064 @iftex
12065 ``Indicating Definitions, Commands, etc.''@: in @cite{Texinfo, The GNU
12066 Documentation Format}.
12067 @end iftex
12068 @end itemize
12070 @node Regexp Search
12071 @chapter Regular Expression Searches
12072 @cindex Searches, illustrating
12073 @cindex Regular expression searches
12074 @cindex Patterns, searching for
12075 @cindex Motion by sentence and paragraph
12076 @cindex Sentences, movement by
12077 @cindex Paragraphs, movement by
12079 Regular expression searches are used extensively in GNU Emacs.  The
12080 two functions, @code{forward-sentence} and @code{forward-paragraph},
12081 illustrate these searches well.  They use regular expressions to find
12082 where to move point.  The phrase ``regular expression'' is often written
12083 as ``regexp''.
12085 Regular expression searches are described in @ref{Regexp Search, ,
12086 Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
12087 @ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
12088 Manual}.  In writing this chapter, I am presuming that you have at
12089 least a mild acquaintance with them.  The major point to remember is
12090 that regular expressions permit you to search for patterns as well as
12091 for literal strings of characters.  For example, the code in
12092 @code{forward-sentence} searches for the pattern of possible
12093 characters that could mark the end of a sentence, and moves point to
12094 that spot.
12096 Before looking at the code for the @code{forward-sentence} function, it
12097 is worth considering what the pattern that marks the end of a sentence
12098 must be.  The pattern is discussed in the next section; following that
12099 is a description of the regular expression search function,
12100 @code{re-search-forward}.  The @code{forward-sentence} function
12101 is described in the section following.  Finally, the
12102 @code{forward-paragraph} function is described in the last section of
12103 this chapter.  @code{forward-paragraph} is a complex function that
12104 introduces several new features.
12106 @menu
12107 * sentence-end::                The regular expression for @code{sentence-end}.
12108 * re-search-forward::           Very similar to @code{search-forward}.
12109 * forward-sentence::            A straightforward example of regexp search.
12110 * forward-paragraph::           A somewhat complex example.
12111 * Regexp Review::
12112 * re-search Exercises::
12113 @end menu
12115 @node sentence-end
12116 @section The Regular Expression for @code{sentence-end}
12117 @findex sentence-end
12119 The symbol @code{sentence-end} is bound to the pattern that marks the
12120 end of a sentence.  What should this regular expression be?
12122 Clearly, a sentence may be ended by a period, a question mark, or an
12123 exclamation mark.  Indeed, in English, only clauses that end with one
12124 of those three characters should be considered the end of a sentence.
12125 This means that the pattern should include the character set:
12127 @smallexample
12128 [.?!]
12129 @end smallexample
12131 However, we do not want @code{forward-sentence} merely to jump to a
12132 period, a question mark, or an exclamation mark, because such a character
12133 might be used in the middle of a sentence.  A period, for example, is
12134 used after abbreviations.  So other information is needed.
12136 According to convention, you type two spaces after every sentence, but
12137 only one space after a period, a question mark, or an exclamation mark in
12138 the body of a sentence.  So a period, a question mark, or an exclamation
12139 mark followed by two spaces is a good indicator of an end of sentence.
12140 However, in a file, the two spaces may instead be a tab or the end of a
12141 line.  This means that the regular expression should include these three
12142 items as alternatives.
12144 @need 800
12145 This group of alternatives will look like this:
12147 @smallexample
12148 @group
12149 \\($\\| \\|  \\)
12150        ^   ^^
12151       TAB  SPC
12152 @end group
12153 @end smallexample
12155 @noindent
12156 Here, @samp{$} indicates the end of the line, and I have pointed out
12157 where the tab and two spaces are inserted in the expression.  Both are
12158 inserted by putting the actual characters into the expression.
12160 Two backslashes, @samp{\\}, are required before the parentheses and
12161 vertical bars: the first backslash quotes the following backslash in
12162 Emacs; and the second indicates that the following character, the
12163 parenthesis or the vertical bar, is special.
12165 @need 1000
12166 Also, a sentence may be followed by one or more carriage returns, like
12167 this:
12169 @smallexample
12170 @group
12173 @end group
12174 @end smallexample
12176 @noindent
12177 Like tabs and spaces, a carriage return is inserted into a regular
12178 expression by inserting it literally.  The asterisk indicates that the
12179 @key{RET} is repeated zero or more times.
12181 But a sentence end does not consist only of a period, a question mark or
12182 an exclamation mark followed by appropriate space: a closing quotation
12183 mark or a closing brace of some kind may precede the space.  Indeed more
12184 than one such mark or brace may precede the space.  These require a
12185 expression that looks like this:
12187 @smallexample
12188 []\"')@}]*
12189 @end smallexample
12191 In this expression, the first @samp{]} is the first character in the
12192 expression; the second character is @samp{"}, which is preceded by a
12193 @samp{\} to tell Emacs the @samp{"} is @emph{not} special.  The last
12194 three characters are @samp{'}, @samp{)}, and @samp{@}}.
12196 All this suggests what the regular expression pattern for matching the
12197 end of a sentence should be; and, indeed, if we evaluate
12198 @code{sentence-end} we find that it returns the following value:
12200 @smallexample
12201 @group
12202 sentence-end
12203      @result{} "[.?!][]\"')@}]*\\($\\|     \\|  \\)[
12205 @end group
12206 @end smallexample
12208 @noindent
12209 (Well, not in GNU Emacs 22; that is because of an effort to make the
12210 process simpler and to handle more glyphs and languages.  When the
12211 value of @code{sentence-end} is @code{nil}, then use the value defined
12212 by the function @code{sentence-end}.  (Here is a use of the difference
12213 between a value and a function in Emacs Lisp.)  The function returns a
12214 value constructed from the variables @code{sentence-end-base},
12215 @code{sentence-end-double-space}, @code{sentence-end-without-period},
12216 and @code{sentence-end-without-space}.  The critical variable is
12217 @code{sentence-end-base}; its global value is similar to the one
12218 described above but it also contains two additional quotation marks.
12219 These have differing degrees of curliness.  The
12220 @code{sentence-end-without-period} variable, when true, tells Emacs
12221 that a sentence may end without a period, such as text in Thai.)
12223 @ignore
12224 @noindent
12225 (Note that here the @key{TAB}, two spaces, and  @key{RET} are shown
12226 literally in the pattern.)
12228 This regular expression can be deciphered as follows:
12230 @table @code
12231 @item [.?!]
12232 The first part of the pattern is the three characters, a period, a question
12233 mark and an exclamation mark, within square brackets.  The pattern must
12234 begin with one or other of these characters.
12236 @item []\"')@}]*
12237 The second part of the pattern is the group of closing braces and
12238 quotation marks, which can appear zero or more times.  These may follow
12239 the period, question mark or exclamation mark.  In a regular expression,
12240 the backslash, @samp{\}, followed by the double quotation mark,
12241 @samp{"}, indicates the class of string-quote characters.  Usually, the
12242 double quotation mark is the only character in this class.  The
12243 asterisk, @samp{*}, indicates that the items in the previous group (the
12244 group surrounded by square brackets, @samp{[]}) may be repeated zero or
12245 more times.
12247 @item \\($\\|   \\|  \\)
12248 The third part of the pattern is one or other of: either the end of a
12249 line, or two blank spaces, or a tab.  The double back-slashes are used
12250 to prevent Emacs from reading the parentheses and vertical bars as part
12251 of the search pattern; the parentheses are used to mark the group and
12252 the vertical bars are used to indicated that the patterns to either side
12253 of them are alternatives.  The dollar sign is used to indicate the end
12254 of a line and both the two spaces and the tab are each inserted as is to
12255 indicate what they are.
12257 @item [@key{RET}]*
12258 Finally, the last part of the pattern indicates that the end of the line
12259 or the whitespace following the period, question mark or exclamation
12260 mark may, but need not, be followed by one or more carriage returns.  In
12261 the pattern, the carriage return is inserted as an actual carriage
12262 return between square brackets but here it is shown as @key{RET}.
12263 @end table
12264 @end ignore
12266 @node re-search-forward
12267 @section The @code{re-search-forward} Function
12268 @findex re-search-forward
12270 The @code{re-search-forward} function is very like the
12271 @code{search-forward} function.  (@xref{search-forward, , The
12272 @code{search-forward} Function}.)
12274 @code{re-search-forward} searches for a regular expression.  If the
12275 search is successful, it leaves point immediately after the last
12276 character in the target.  If the search is backwards, it leaves point
12277 just before the first character in the target.  You may tell
12278 @code{re-search-forward} to return @code{t} for true.  (Moving point
12279 is therefore a side effect.)
12281 Like @code{search-forward}, the @code{re-search-forward} function takes
12282 four arguments:
12284 @enumerate
12285 @item
12286 The first argument is the regular expression that the function searches
12287 for.  The regular expression will be a string between quotation marks.
12289 @item
12290 The optional second argument limits how far the function will search; it is a
12291 bound, which is specified as a position in the buffer.
12293 @item
12294 The optional third argument specifies how the function responds to
12295 failure: @code{nil} as the third argument causes the function to
12296 signal an error (and print a message) when the search fails; any other
12297 value causes it to return @code{nil} if the search fails and @code{t}
12298 if the search succeeds.
12300 @item
12301 The optional fourth argument is the repeat count.  A negative repeat
12302 count causes @code{re-search-forward} to search backwards.
12303 @end enumerate
12305 @need 800
12306 The template for @code{re-search-forward} looks like this:
12308 @smallexample
12309 @group
12310 (re-search-forward "@var{regular-expression}"
12311                 @var{limit-of-search}
12312                 @var{what-to-do-if-search-fails}
12313                 @var{repeat-count})
12314 @end group
12315 @end smallexample
12317 The second, third, and fourth arguments are optional.  However, if you
12318 want to pass a value to either or both of the last two arguments, you
12319 must also pass a value to all the preceding arguments.  Otherwise, the
12320 Lisp interpreter will mistake which argument you are passing the value
12323 @need 1200
12324 In the @code{forward-sentence} function, the regular expression will be
12325 the value of the variable @code{sentence-end}.  In simple form, that is:
12327 @smallexample
12328 @group
12329 "[.?!][]\"')@}]*\\($\\|  \\|  \\)[
12331 @end group
12332 @end smallexample
12334 @noindent
12335 The limit of the search will be the end of the paragraph (since a
12336 sentence cannot go beyond a paragraph).  If the search fails, the
12337 function will return @code{nil}; and the repeat count will be provided
12338 by the argument to the @code{forward-sentence} function.
12340 @node forward-sentence
12341 @section @code{forward-sentence}
12342 @findex forward-sentence
12344 The command to move the cursor forward a sentence is a straightforward
12345 illustration of how to use regular expression searches in Emacs Lisp.
12346 Indeed, the function looks longer and more complicated than it is; this
12347 is because the function is designed to go backwards as well as forwards;
12348 and, optionally, over more than one sentence.  The function is usually
12349 bound to the key command @kbd{M-e}.
12351 @menu
12352 * Complete forward-sentence::
12353 * fwd-sentence while loops::    Two @code{while} loops.
12354 * fwd-sentence re-search::      A regular expression search.
12355 @end menu
12357 @ifnottex
12358 @node Complete forward-sentence
12359 @unnumberedsubsec Complete @code{forward-sentence} function definition
12360 @end ifnottex
12362 @need 1250
12363 Here is the code for @code{forward-sentence}:
12365 @c in GNU Emacs 22
12366 @smallexample
12367 @group
12368 (defun forward-sentence (&optional arg)
12369   "Move forward to next end of sentence.  With argument, repeat.
12370 With negative argument, move backward repeatedly to start of sentence.
12372 The variable `sentence-end' is a regular expression that matches ends of
12373 sentences.  Also, every paragraph boundary terminates sentences as well."
12374 @end group
12375 @group
12376   (interactive "p")
12377   (or arg (setq arg 1))
12378   (let ((opoint (point))
12379         (sentence-end (sentence-end)))
12380     (while (< arg 0)
12381       (let ((pos (point))
12382             (par-beg (save-excursion (start-of-paragraph-text) (point))))
12383        (if (and (re-search-backward sentence-end par-beg t)
12384                 (or (< (match-end 0) pos)
12385                     (re-search-backward sentence-end par-beg t)))
12386            (goto-char (match-end 0))
12387          (goto-char par-beg)))
12388       (setq arg (1+ arg)))
12389 @end group
12390 @group
12391     (while (> arg 0)
12392       (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12393        (if (re-search-forward sentence-end par-end t)
12394            (skip-chars-backward " \t\n")
12395          (goto-char par-end)))
12396       (setq arg (1- arg)))
12397     (constrain-to-field nil opoint t)))
12398 @end group
12399 @end smallexample
12401 @ignore
12402 GNU Emacs 21
12403 @smallexample
12404 @group
12405 (defun forward-sentence (&optional arg)
12406   "Move forward to next sentence-end.  With argument, repeat.
12407 With negative argument, move backward repeatedly to sentence-beginning.
12408 Sentence ends are identified by the value of sentence-end
12409 treated as a regular expression.  Also, every paragraph boundary
12410 terminates sentences as well."
12411 @end group
12412 @group
12413   (interactive "p")
12414   (or arg (setq arg 1))
12415   (while (< arg 0)
12416     (let ((par-beg
12417            (save-excursion (start-of-paragraph-text) (point))))
12418       (if (re-search-backward
12419            (concat sentence-end "[^ \t\n]") par-beg t)
12420           (goto-char (1- (match-end 0)))
12421         (goto-char par-beg)))
12422     (setq arg (1+ arg)))
12423   (while (> arg 0)
12424     (let ((par-end
12425            (save-excursion (end-of-paragraph-text) (point))))
12426       (if (re-search-forward sentence-end par-end t)
12427           (skip-chars-backward " \t\n")
12428         (goto-char par-end)))
12429     (setq arg (1- arg))))
12430 @end group
12431 @end smallexample
12432 @end ignore
12434 The function looks long at first sight and it is best to look at its
12435 skeleton first, and then its muscle.  The way to see the skeleton is to
12436 look at the expressions that start in the left-most columns:
12438 @smallexample
12439 @group
12440 (defun forward-sentence (&optional arg)
12441   "@var{documentation}@dots{}"
12442   (interactive "p")
12443   (or arg (setq arg 1))
12444   (let ((opoint (point)) (sentence-end (sentence-end)))
12445     (while (< arg 0)
12446       (let ((pos (point))
12447             (par-beg (save-excursion (start-of-paragraph-text) (point))))
12448        @var{rest-of-body-of-while-loop-when-going-backwards}
12449     (while (> arg 0)
12450       (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12451        @var{rest-of-body-of-while-loop-when-going-forwards}
12452     @var{handle-forms-and-equivalent}
12453 @end group
12454 @end smallexample
12456 This looks much simpler!  The function definition consists of
12457 documentation, an @code{interactive} expression, an @code{or}
12458 expression, a @code{let} expression, and @code{while} loops.
12460 Let's look at each of these parts in turn.
12462 We note that the documentation is thorough and understandable.
12464 The function has an @code{interactive "p"} declaration.  This means
12465 that the processed prefix argument, if any, is passed to the
12466 function as its argument.  (This will be a number.)  If the function
12467 is not passed an argument (it is optional) then the argument
12468 @code{arg} will be bound to 1.
12470 When @code{forward-sentence} is called non-interactively without an
12471 argument, @code{arg} is bound to @code{nil}.  The @code{or} expression
12472 handles this.  What it does is either leave the value of @code{arg} as
12473 it is, but only if @code{arg} is bound to a value; or it sets the
12474 value of @code{arg} to 1, in the case when @code{arg} is bound to
12475 @code{nil}.
12477 Next is a @code{let}.  That specifies the values of two local
12478 variables, @code{opoint} and @code{sentence-end}.  The local value of
12479 point, from before the search, is used in the
12480 @code{constrain-to-field} function which handles forms and
12481 equivalents.  The @code{sentence-end} variable is set by the
12482 @code{sentence-end} function.
12484 @node fwd-sentence while loops
12485 @unnumberedsubsec The @code{while} loops
12487 Two @code{while} loops follow.  The first @code{while} has a
12488 true-or-false-test that tests true if the prefix argument for
12489 @code{forward-sentence} is a negative number.  This is for going
12490 backwards.  The body of this loop is similar to the body of the second
12491 @code{while} clause, but it is not exactly the same.  We will skip
12492 this @code{while} loop and concentrate on the second @code{while}
12493 loop.
12495 @need 1500
12496 The second @code{while} loop is for moving point forward.  Its skeleton
12497 looks like this:
12499 @smallexample
12500 @group
12501 (while (> arg 0)            ; @r{true-or-false-test}
12502   (let @var{varlist}
12503     (if (@var{true-or-false-test})
12504         @var{then-part}
12505       @var{else-part}
12506   (setq arg (1- arg))))     ; @code{while} @r{loop decrementer}
12507 @end group
12508 @end smallexample
12510 The @code{while} loop is of the decrementing kind.
12511 (@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.)  It
12512 has a true-or-false-test that tests true so long as the counter (in
12513 this case, the variable @code{arg}) is greater than zero; and it has a
12514 decrementer that subtracts 1 from the value of the counter every time
12515 the loop repeats.
12517 If no prefix argument is given to @code{forward-sentence}, which is
12518 the most common way the command is used, this @code{while} loop will
12519 run once, since the value of @code{arg} will be 1.
12521 The body of the @code{while} loop consists of a @code{let} expression,
12522 which creates and binds a local variable, and has, as its body, an
12523 @code{if} expression.
12525 @need 1250
12526 The body of the @code{while} loop looks like this:
12528 @smallexample
12529 @group
12530 (let ((par-end
12531        (save-excursion (end-of-paragraph-text) (point))))
12532   (if (re-search-forward sentence-end par-end t)
12533       (skip-chars-backward " \t\n")
12534     (goto-char par-end)))
12535 @end group
12536 @end smallexample
12538 The @code{let} expression creates and binds the local variable
12539 @code{par-end}.  As we shall see, this local variable is designed to
12540 provide a bound or limit to the regular expression search.  If the
12541 search fails to find a proper sentence ending in the paragraph, it will
12542 stop on reaching the end of the paragraph.
12544 But first, let us examine how @code{par-end} is bound to the value of
12545 the end of the paragraph.  What happens is that the @code{let} sets the
12546 value of @code{par-end} to the value returned when the Lisp interpreter
12547 evaluates the expression
12549 @smallexample
12550 @group
12551 (save-excursion (end-of-paragraph-text) (point))
12552 @end group
12553 @end smallexample
12555 @noindent
12556 In this expression, @code{(end-of-paragraph-text)} moves point to the
12557 end of the paragraph, @code{(point)} returns the value of point, and then
12558 @code{save-excursion} restores point to its original position.  Thus,
12559 the @code{let} binds @code{par-end} to the value returned by the
12560 @code{save-excursion} expression, which is the position of the end of
12561 the paragraph.  (The @code{end-of-paragraph-text} function uses
12562 @code{forward-paragraph}, which we will discuss shortly.)
12564 @need 1200
12565 Emacs next evaluates the body of the @code{let}, which is an @code{if}
12566 expression that looks like this:
12568 @smallexample
12569 @group
12570 (if (re-search-forward sentence-end par-end t) ; @r{if-part}
12571     (skip-chars-backward " \t\n")              ; @r{then-part}
12572   (goto-char par-end)))                        ; @r{else-part}
12573 @end group
12574 @end smallexample
12576 The @code{if} tests whether its first argument is true and if so,
12577 evaluates its then-part; otherwise, the Emacs Lisp interpreter
12578 evaluates the else-part.  The true-or-false-test of the @code{if}
12579 expression is the regular expression search.
12581 It may seem odd to have what looks like the real work of
12582 the @code{forward-sentence} function buried here, but this is a common
12583 way this kind of operation is carried out in Lisp.
12585 @node fwd-sentence re-search
12586 @unnumberedsubsec The regular expression search
12588 The @code{re-search-forward} function searches for the end of the
12589 sentence, that is, for the pattern defined by the @code{sentence-end}
12590 regular expression.  If the pattern is found---if the end of the sentence is
12591 found---then the @code{re-search-forward} function does two things:
12593 @enumerate
12594 @item
12595 The @code{re-search-forward} function carries out a side effect, which
12596 is to move point to the end of the occurrence found.
12598 @item
12599 The @code{re-search-forward} function returns a value of true.  This is
12600 the value received by the @code{if}, and means that the search was
12601 successful.
12602 @end enumerate
12604 @noindent
12605 The side effect, the movement of point, is completed before the
12606 @code{if} function is handed the value returned by the successful
12607 conclusion of the search.
12609 When the @code{if} function receives the value of true from a successful
12610 call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12611 which is the expression @code{(skip-chars-backward " \t\n")}.  This
12612 expression moves backwards over any blank spaces, tabs or carriage
12613 returns until a printed character is found and then leaves point after
12614 the character.  Since point has already been moved to the end of the
12615 pattern that marks the end of the sentence, this action leaves point
12616 right after the closing printed character of the sentence, which is
12617 usually a period.
12619 On the other hand, if the @code{re-search-forward} function fails to
12620 find a pattern marking the end of the sentence, the function returns
12621 false.  The false then causes the @code{if} to evaluate its third
12622 argument, which is @code{(goto-char par-end)}:  it moves point to the
12623 end of the paragraph.
12625 (And if the text is in a form or equivalent, and point may not move
12626 fully, then the @code{constrain-to-field} function comes into play.)
12628 Regular expression searches are exceptionally useful and the pattern
12629 illustrated by @code{re-search-forward}, in which the search is the
12630 test of an @code{if} expression, is handy.  You will see or write code
12631 incorporating this pattern often.
12633 @node forward-paragraph
12634 @section @code{forward-paragraph}: a Goldmine of Functions
12635 @findex forward-paragraph
12637 @ignore
12638 @c in GNU Emacs 22
12639 (defun forward-paragraph (&optional arg)
12640   "Move forward to end of paragraph.
12641 With argument ARG, do it ARG times;
12642 a negative argument ARG = -N means move backward N paragraphs.
12644 A line which `paragraph-start' matches either separates paragraphs
12645 \(if `paragraph-separate' matches it also) or is the first line of a paragraph.
12646 A paragraph end is the beginning of a line which is not part of the paragraph
12647 to which the end of the previous line belongs, or the end of the buffer.
12648 Returns the count of paragraphs left to move."
12649   (interactive "p")
12650   (or arg (setq arg 1))
12651   (let* ((opoint (point))
12652          (fill-prefix-regexp
12653           (and fill-prefix (not (equal fill-prefix ""))
12654                (not paragraph-ignore-fill-prefix)
12655                (regexp-quote fill-prefix)))
12656          ;; Remove ^ from paragraph-start and paragraph-sep if they are there.
12657          ;; These regexps shouldn't be anchored, because we look for them
12658          ;; starting at the left-margin.  This allows paragraph commands to
12659          ;; work normally with indented text.
12660          ;; This hack will not find problem cases like "whatever\\|^something".
12661          (parstart (if (and (not (equal "" paragraph-start))
12662                             (equal ?^ (aref paragraph-start 0)))
12663                        (substring paragraph-start 1)
12664                      paragraph-start))
12665          (parsep (if (and (not (equal "" paragraph-separate))
12666                           (equal ?^ (aref paragraph-separate 0)))
12667                      (substring paragraph-separate 1)
12668                    paragraph-separate))
12669          (parsep
12670           (if fill-prefix-regexp
12671               (concat parsep "\\|"
12672                       fill-prefix-regexp "[ \t]*$")
12673             parsep))
12674          ;; This is used for searching.
12675          (sp-parstart (concat "^[ \t]*\\(?:" parstart "\\|" parsep "\\)"))
12676          start found-start)
12677     (while (and (< arg 0) (not (bobp)))
12678       (if (and (not (looking-at parsep))
12679                (re-search-backward "^\n" (max (1- (point)) (point-min)) t)
12680                (looking-at parsep))
12681           (setq arg (1+ arg))
12682         (setq start (point))
12683         ;; Move back over paragraph-separating lines.
12684         (forward-char -1) (beginning-of-line)
12685         (while (and (not (bobp))
12686                     (progn (move-to-left-margin)
12687                            (looking-at parsep)))
12688           (forward-line -1))
12689         (if (bobp)
12690             nil
12691           (setq arg (1+ arg))
12692           ;; Go to end of the previous (non-separating) line.
12693           (end-of-line)
12694           ;; Search back for line that starts or separates paragraphs.
12695           (if (if fill-prefix-regexp
12696                   ;; There is a fill prefix; it overrides parstart.
12697                   (let (multiple-lines)
12698                     (while (and (progn (beginning-of-line) (not (bobp)))
12699                                 (progn (move-to-left-margin)
12700                                        (not (looking-at parsep)))
12701                                 (looking-at fill-prefix-regexp))
12702                       (unless (= (point) start)
12703                         (setq multiple-lines t))
12704                       (forward-line -1))
12705                     (move-to-left-margin)
12706                     ;; This deleted code caused a long hanging-indent line
12707                     ;; not to be filled together with the following lines.
12708                     ;; ;; Don't move back over a line before the paragraph
12709                     ;; ;; which doesn't start with fill-prefix
12710                     ;; ;; unless that is the only line we've moved over.
12711                     ;; (and (not (looking-at fill-prefix-regexp))
12712                     ;;      multiple-lines
12713                     ;;      (forward-line 1))
12714                     (not (bobp)))
12715                 (while (and (re-search-backward sp-parstart nil 1)
12716                             (setq found-start t)
12717                             ;; Found a candidate, but need to check if it is a
12718                             ;; REAL parstart.
12719                             (progn (setq start (point))
12720                                    (move-to-left-margin)
12721                                    (not (looking-at parsep)))
12722                             (not (and (looking-at parstart)
12723                                       (or (not use-hard-newlines)
12724                                           (bobp)
12725                                           (get-text-property
12726                                            (1- start) 'hard)))))
12727                   (setq found-start nil)
12728                   (goto-char start))
12729                 found-start)
12730               ;; Found one.
12731               (progn
12732                 ;; Move forward over paragraph separators.
12733                 ;; We know this cannot reach the place we started
12734                 ;; because we know we moved back over a non-separator.
12735                 (while (and (not (eobp))
12736                             (progn (move-to-left-margin)
12737                                    (looking-at parsep)))
12738                   (forward-line 1))
12739                 ;; If line before paragraph is just margin, back up to there.
12740                 (end-of-line 0)
12741                 (if (> (current-column) (current-left-margin))
12742                     (forward-char 1)
12743                   (skip-chars-backward " \t")
12744                   (if (not (bolp))
12745                       (forward-line 1))))
12746             ;; No starter or separator line => use buffer beg.
12747             (goto-char (point-min))))))
12749     (while (and (> arg 0) (not (eobp)))
12750       ;; Move forward over separator lines...
12751       (while (and (not (eobp))
12752                   (progn (move-to-left-margin) (not (eobp)))
12753                   (looking-at parsep))
12754         (forward-line 1))
12755       (unless (eobp) (setq arg (1- arg)))
12756       ;; ... and one more line.
12757       (forward-line 1)
12758       (if fill-prefix-regexp
12759           ;; There is a fill prefix; it overrides parstart.
12760           (while (and (not (eobp))
12761                       (progn (move-to-left-margin) (not (eobp)))
12762                       (not (looking-at parsep))
12763                       (looking-at fill-prefix-regexp))
12764             (forward-line 1))
12765         (while (and (re-search-forward sp-parstart nil 1)
12766                     (progn (setq start (match-beginning 0))
12767                            (goto-char start)
12768                            (not (eobp)))
12769                     (progn (move-to-left-margin)
12770                            (not (looking-at parsep)))
12771                     (or (not (looking-at parstart))
12772                         (and use-hard-newlines
12773                              (not (get-text-property (1- start) 'hard)))))
12774           (forward-char 1))
12775         (if (< (point) (point-max))
12776             (goto-char start))))
12777     (constrain-to-field nil opoint t)
12778     ;; Return the number of steps that could not be done.
12779     arg))
12780 @end ignore
12782 The @code{forward-paragraph} function moves point forward to the end
12783 of the paragraph.  It is usually bound to @kbd{M-@}} and makes use of a
12784 number of functions that are important in themselves, including
12785 @code{let*}, @code{match-beginning}, and @code{looking-at}.
12787 The function definition for @code{forward-paragraph} is considerably
12788 longer than the function definition for @code{forward-sentence}
12789 because it works with a paragraph, each line of which may begin with a
12790 fill prefix.
12792 A fill prefix consists of a string of characters that are repeated at
12793 the beginning of each line.  For example, in Lisp code, it is a
12794 convention to start each line of a paragraph-long comment with
12795 @samp{;;; }.  In Text mode, four blank spaces make up another common
12796 fill prefix, creating an indented paragraph.  (@xref{Fill Prefix, , ,
12797 emacs, The GNU Emacs Manual}, for more information about fill
12798 prefixes.)
12800 The existence of a fill prefix means that in addition to being able to
12801 find the end of a paragraph whose lines begin on the left-most
12802 column, the @code{forward-paragraph} function must be able to find the
12803 end of a paragraph when all or many of the lines in the buffer begin
12804 with the fill prefix.
12806 Moreover, it is sometimes practical to ignore a fill prefix that
12807 exists, especially when blank lines separate paragraphs.
12808 This is an added complication.
12810 @menu
12811 * forward-paragraph in brief::  Key parts of the function definition.
12812 * fwd-para let::                The @code{let*} expression.
12813 * fwd-para while::              The forward motion @code{while} loop.
12814 @end menu
12816 @ifnottex
12817 @node forward-paragraph in brief
12818 @unnumberedsubsec Shortened @code{forward-paragraph} function definition
12819 @end ifnottex
12821 Rather than print all of the @code{forward-paragraph} function, we
12822 will only print parts of it.  Read without preparation, the function
12823 can be daunting!
12825 @need 800
12826 In outline, the function looks like this:
12828 @smallexample
12829 @group
12830 (defun forward-paragraph (&optional arg)
12831   "@var{documentation}@dots{}"
12832   (interactive "p")
12833   (or arg (setq arg 1))
12834   (let*
12835       @var{varlist}
12836     (while (and (< arg 0) (not (bobp)))     ; @r{backward-moving-code}
12837       @dots{}
12838     (while (and (> arg 0) (not (eobp)))     ; @r{forward-moving-code}
12839       @dots{}
12840 @end group
12841 @end smallexample
12843 The first parts of the function are routine: the function's argument
12844 list consists of one optional argument.  Documentation follows.
12846 The lower case @samp{p} in the @code{interactive} declaration means
12847 that the processed prefix argument, if any, is passed to the function.
12848 This will be a number, and is the repeat count of how many paragraphs
12849 point will move.  The @code{or} expression in the next line handles
12850 the common case when no argument is passed to the function, which occurs
12851 if the function is called from other code rather than interactively.
12852 This case was described earlier.  (@xref{forward-sentence, The
12853 @code{forward-sentence} function}.)  Now we reach the end of the
12854 familiar part of this function.
12856 @node fwd-para let
12857 @unnumberedsubsec The @code{let*} expression
12859 The next line of the @code{forward-paragraph} function begins a
12860 @code{let*} expression.  This is a different than @code{let}.  The
12861 symbol is @code{let*} not @code{let}.
12863 @findex let*
12864 The @code{let*} special form is like @code{let} except that Emacs sets
12865 each variable in sequence, one after another, and variables in the
12866 latter part of the varlist can make use of the values to which Emacs
12867 set variables in the earlier part of the varlist.
12869 @ignore
12870 ( refappend save-excursion, , code save-excursion in code append-to-buffer .)
12871 @end ignore
12873 (@ref{append save-excursion, , @code{save-excursion} in @code{append-to-buffer}}.)
12875 In the @code{let*} expression in this function, Emacs binds a total of
12876 seven variables:  @code{opoint}, @code{fill-prefix-regexp},
12877 @code{parstart}, @code{parsep}, @code{sp-parstart}, @code{start}, and
12878 @code{found-start}.
12880 The variable @code{parsep} appears twice, first, to remove instances
12881 of @samp{^}, and second, to handle fill prefixes.
12883 The variable @code{opoint} is just the value of @code{point}.  As you
12884 can guess, it is used in a @code{constrain-to-field} expression, just
12885 as in @code{forward-sentence}.
12887 The variable @code{fill-prefix-regexp} is set to the value returned by
12888 evaluating the following list:
12890 @smallexample
12891 @group
12892 (and fill-prefix
12893      (not (equal fill-prefix ""))
12894      (not paragraph-ignore-fill-prefix)
12895      (regexp-quote fill-prefix))
12896 @end group
12897 @end smallexample
12899 @noindent
12900 This is an expression whose first element is the @code{and} special form.
12902 As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
12903 function}), the @code{and} special form evaluates each of its
12904 arguments until one of the arguments returns a value of @code{nil}, in
12905 which case the @code{and} expression returns @code{nil}; however, if
12906 none of the arguments returns a value of @code{nil}, the value
12907 resulting from evaluating the last argument is returned.  (Since such
12908 a value is not @code{nil}, it is considered true in Lisp.)  In other
12909 words, an @code{and} expression returns a true value only if all its
12910 arguments are true.
12911 @findex and
12913 In this case, the variable @code{fill-prefix-regexp} is bound to a
12914 non-@code{nil} value only if the following four expressions produce a
12915 true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
12916 @code{fill-prefix-regexp} is bound to @code{nil}.
12918 @table @code
12919 @item fill-prefix
12920 When this variable is evaluated, the value of the fill prefix, if any,
12921 is returned.  If there is no fill prefix, this variable returns
12922 @code{nil}.
12924 @item (not (equal fill-prefix "")
12925 This expression checks whether an existing fill prefix is an empty
12926 string, that is, a string with no characters in it.  An empty string is
12927 not a useful fill prefix.
12929 @item (not paragraph-ignore-fill-prefix)
12930 This expression returns @code{nil} if the variable
12931 @code{paragraph-ignore-fill-prefix} has been turned on by being set to a
12932 true value such as @code{t}.
12934 @item (regexp-quote fill-prefix)
12935 This is the last argument to the @code{and} special form.  If all the
12936 arguments to the @code{and} are true, the value resulting from
12937 evaluating this expression will be returned by the @code{and} expression
12938 and bound to the variable @code{fill-prefix-regexp},
12939 @end table
12941 @findex regexp-quote
12942 @noindent
12943 The result of evaluating this @code{and} expression successfully is that
12944 @code{fill-prefix-regexp} will be bound to the value of
12945 @code{fill-prefix} as modified by the @code{regexp-quote} function.
12946 What @code{regexp-quote} does is read a string and return a regular
12947 expression that will exactly match the string and match nothing else.
12948 This means that @code{fill-prefix-regexp} will be set to a value that
12949 will exactly match the fill prefix if the fill prefix exists.
12950 Otherwise, the variable will be set to @code{nil}.
12952 The next two local variables in the @code{let*} expression are
12953 designed to remove instances of @samp{^} from @code{parstart} and
12954 @code{parsep}, the local variables which indicate the paragraph start
12955 and the paragraph separator.  The next expression sets @code{parsep}
12956 again.  That is to handle fill prefixes.
12958 This is the setting that requires the definition call @code{let*}
12959 rather than @code{let}.  The true-or-false-test for the @code{if}
12960 depends on whether the variable @code{fill-prefix-regexp} evaluates to
12961 @code{nil} or some other value.
12963 If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
12964 the else-part of the @code{if} expression and binds @code{parsep} to
12965 its local value.  (@code{parsep} is a regular expression that matches
12966 what separates paragraphs.)
12968 But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
12969 the then-part of the @code{if} expression and binds @code{parsep} to a
12970 regular expression that includes the @code{fill-prefix-regexp} as part
12971 of the pattern.
12973 Specifically, @code{parsep} is set to the original value of the
12974 paragraph separate regular expression concatenated with an alternative
12975 expression that consists of the @code{fill-prefix-regexp} followed by
12976 optional whitespace to the end of the line.  The whitespace is defined
12977 by @w{@code{"[ \t]*$"}}.)  The @samp{\\|} defines this portion of the
12978 regexp as an alternative to @code{parsep}.
12980 According to a comment in the code, the next local variable,
12981 @code{sp-parstart}, is used for searching, and then the final two,
12982 @code{start} and @code{found-start}, are set to @code{nil}.
12984 Now we get into the body of the @code{let*}.  The first part of the body
12985 of the @code{let*} deals with the case when the function is given a
12986 negative argument and is therefore moving backwards.  We will skip this
12987 section.
12989 @node fwd-para while
12990 @unnumberedsubsec The forward motion @code{while} loop
12992 The second part of the body of the @code{let*} deals with forward
12993 motion.  It is a @code{while} loop that repeats itself so long as the
12994 value of @code{arg} is greater than zero.  In the most common use of
12995 the function, the value of the argument is 1, so the body of the
12996 @code{while} loop is evaluated exactly once, and the cursor moves
12997 forward one paragraph.
12999 @ignore
13000 (while (and (> arg 0) (not (eobp)))
13002   ;; Move forward over separator lines...
13003   (while (and (not (eobp))
13004               (progn (move-to-left-margin) (not (eobp)))
13005               (looking-at parsep))
13006     (forward-line 1))
13007   (unless (eobp) (setq arg (1- arg)))
13008   ;; ... and one more line.
13009   (forward-line 1)
13011   (if fill-prefix-regexp
13012       ;; There is a fill prefix; it overrides parstart.
13013       (while (and (not (eobp))
13014                   (progn (move-to-left-margin) (not (eobp)))
13015                   (not (looking-at parsep))
13016                   (looking-at fill-prefix-regexp))
13017         (forward-line 1))
13019     (while (and (re-search-forward sp-parstart nil 1)
13020                 (progn (setq start (match-beginning 0))
13021                        (goto-char start)
13022                        (not (eobp)))
13023                 (progn (move-to-left-margin)
13024                        (not (looking-at parsep)))
13025                 (or (not (looking-at parstart))
13026                     (and use-hard-newlines
13027                          (not (get-text-property (1- start) 'hard)))))
13028       (forward-char 1))
13030     (if (< (point) (point-max))
13031         (goto-char start))))
13032 @end ignore
13034 This part handles three situations: when point is between paragraphs,
13035 when there is a fill prefix and when there is no fill prefix.
13037 @need 800
13038 The @code{while} loop looks like this:
13040 @smallexample
13041 @group
13042 ;; @r{going forwards and not at the end of the buffer}
13043 (while (and (> arg 0) (not (eobp)))
13045   ;; @r{between paragraphs}
13046   ;; Move forward over separator lines...
13047   (while (and (not (eobp))
13048               (progn (move-to-left-margin) (not (eobp)))
13049               (looking-at parsep))
13050     (forward-line 1))
13051   ;;  @r{This decrements the loop}
13052   (unless (eobp) (setq arg (1- arg)))
13053   ;; ... and one more line.
13054   (forward-line 1)
13055 @end group
13057 @group
13058   (if fill-prefix-regexp
13059       ;; There is a fill prefix; it overrides parstart;
13060       ;; we go forward line by line
13061       (while (and (not (eobp))
13062                   (progn (move-to-left-margin) (not (eobp)))
13063                   (not (looking-at parsep))
13064                   (looking-at fill-prefix-regexp))
13065         (forward-line 1))
13066 @end group
13068 @group
13069     ;; There is no fill prefix;
13070     ;; we go forward character by character
13071     (while (and (re-search-forward sp-parstart nil 1)
13072                 (progn (setq start (match-beginning 0))
13073                        (goto-char start)
13074                        (not (eobp)))
13075                 (progn (move-to-left-margin)
13076                        (not (looking-at parsep)))
13077                 (or (not (looking-at parstart))
13078                     (and use-hard-newlines
13079                          (not (get-text-property (1- start) 'hard)))))
13080       (forward-char 1))
13081 @end group
13083 @group
13084     ;; and if there is no fill prefix and if we are not at the end,
13085     ;;     go to whatever was found in the regular expression search
13086     ;;     for sp-parstart
13087     (if (< (point) (point-max))
13088         (goto-char start))))
13089 @end group
13090 @end smallexample
13092 @findex eobp
13093 We can see that this is a decrementing counter @code{while} loop,
13094 using the expression @code{(setq arg (1- arg))} as the decrementer.
13095 That expression is not far from the @code{while}, but is hidden in
13096 another Lisp macro, an @code{unless} macro.  Unless we are at the end
13097 of the buffer---that is what the @code{eobp} function determines; it
13098 is an abbreviation of @samp{End Of Buffer P}---we decrease the value
13099 of @code{arg} by one.
13101 (If we are at the end of the buffer, we cannot go forward any more and
13102 the next loop of the @code{while} expression will test false since the
13103 test is an @code{and} with @code{(not (eobp))}.  The @code{not}
13104 function means exactly as you expect; it is another name for
13105 @code{null}, a function that returns true when its argument is false.)
13107 Interestingly, the loop count is not decremented until we leave the
13108 space between paragraphs, unless we come to the end of buffer or stop
13109 seeing the local value of the paragraph separator.
13111 That second @code{while} also has a @code{(move-to-left-margin)}
13112 expression.  The function is self-explanatory.  It is inside a
13113 @code{progn} expression and not the last element of its body, so it is
13114 only invoked for its side effect, which is to move point to the left
13115 margin of the current line.
13117 @findex looking-at
13118 The @code{looking-at} function is also self-explanatory; it returns
13119 true if the text after point matches the regular expression given as
13120 its argument.
13122 The rest of the body of the loop looks difficult at first, but makes
13123 sense as you come to understand it.
13125 @need 800
13126 First consider what happens if there is a fill prefix:
13128 @smallexample
13129 @group
13130   (if fill-prefix-regexp
13131       ;; There is a fill prefix; it overrides parstart;
13132       ;; we go forward line by line
13133       (while (and (not (eobp))
13134                   (progn (move-to-left-margin) (not (eobp)))
13135                   (not (looking-at parsep))
13136                   (looking-at fill-prefix-regexp))
13137         (forward-line 1))
13138 @end group
13139 @end smallexample
13141 @noindent
13142 This expression moves point forward line by line so long
13143 as four conditions are true:
13145 @enumerate
13146 @item
13147 Point is not at the end of the buffer.
13149 @item
13150 We can move to the left margin of the text and are
13151 not at the end of the buffer.
13153 @item
13154 The text following point does not separate paragraphs.
13156 @item
13157 The pattern following point is the fill prefix regular expression.
13158 @end enumerate
13160 The last condition may be puzzling, until you remember that point was
13161 moved to the beginning of the line early in the @code{forward-paragraph}
13162 function.  This means that if the text has a fill prefix, the
13163 @code{looking-at} function will see it.
13165 @need 1250
13166 Consider what happens when there is no fill prefix.
13168 @smallexample
13169 @group
13170     (while (and (re-search-forward sp-parstart nil 1)
13171                 (progn (setq start (match-beginning 0))
13172                        (goto-char start)
13173                        (not (eobp)))
13174                 (progn (move-to-left-margin)
13175                        (not (looking-at parsep)))
13176                 (or (not (looking-at parstart))
13177                     (and use-hard-newlines
13178                          (not (get-text-property (1- start) 'hard)))))
13179       (forward-char 1))
13180 @end group
13181 @end smallexample
13183 @noindent
13184 This @code{while} loop has us searching forward for
13185 @code{sp-parstart}, which is the combination of possible whitespace
13186 with the local value of the start of a paragraph or of a paragraph
13187 separator.  (The latter two are within an expression starting
13188 @code{\(?:} so that they are not referenced by the
13189 @code{match-beginning} function.)
13191 @need 800
13192 The two expressions,
13194 @smallexample
13195 @group
13196 (setq start (match-beginning 0))
13197 (goto-char start)
13198 @end group
13199 @end smallexample
13201 @noindent
13202 mean go to the start of the text matched by the regular expression
13203 search.
13205 The @code{(match-beginning 0)} expression is new.  It returns a number
13206 specifying the location of the start of the text that was matched by
13207 the last search.
13209 The @code{match-beginning} function is used here because of a
13210 characteristic of a forward search: a successful forward search,
13211 regardless of whether it is a plain search or a regular expression
13212 search, moves point to the end of the text that is found.  In this
13213 case, a successful search moves point to the end of the pattern for
13214 @code{sp-parstart}.
13216 However, we want to put point at the end of the current paragraph, not
13217 somewhere else.  Indeed, since the search possibly includes the
13218 paragraph separator, point may end up at the beginning of the next one
13219 unless we use an expression that includes @code{match-beginning}.
13221 @findex match-beginning
13222 When given an argument of 0, @code{match-beginning} returns the
13223 position that is the start of the text matched by the most recent
13224 search.  In this case, the most recent search looks for
13225 @code{sp-parstart}.  The @code{(match-beginning 0)} expression returns
13226 the beginning position of that pattern, rather than the end position
13227 of that pattern.
13229 (Incidentally, when passed a positive number as an argument, the
13230 @code{match-beginning} function returns the location of point at that
13231 parenthesized expression in the last search unless that parenthesized
13232 expression begins with @code{\(?:}.  I don't know why @code{\(?:}
13233 appears here since the argument is 0.)
13235 @need 1250
13236 The last expression when there is no fill prefix is
13238 @smallexample
13239 @group
13240 (if (< (point) (point-max))
13241     (goto-char start))))
13242 @end group
13243 @end smallexample
13245 @noindent
13246 This says that if there is no fill prefix and if we are not at the
13247 end, point should move to the beginning of whatever was found by the
13248 regular expression search for @code{sp-parstart}.
13250 The full definition for the @code{forward-paragraph} function not only
13251 includes code for going forwards, but also code for going backwards.
13253 If you are reading this inside of GNU Emacs and you want to see the
13254 whole function, you can type @kbd{C-h f} (@code{describe-function})
13255 and the name of the function.  This gives you the function
13256 documentation and the name of the library containing the function's
13257 source.  Place point over the name of the library and press the RET
13258 key; you will be taken directly to the source.  (Be sure to install
13259 your sources!  Without them, you are like a person who tries to drive
13260 a car with his eyes shut!)
13262 @node Regexp Review
13263 @section Review
13265 Here is a brief summary of some recently introduced functions.
13267 @table @code
13268 @item while
13269 Repeatedly evaluate the body of the expression so long as the first
13270 element of the body tests true.  Then return @code{nil}.  (The
13271 expression is evaluated only for its side effects.)
13273 @need 1250
13274 For example:
13276 @smallexample
13277 @group
13278 (let ((foo 2))
13279   (while (> foo 0)
13280     (insert (format "foo is %d.\n" foo))
13281     (setq foo (1- foo))))
13283      @result{}      foo is 2.
13284              foo is 1.
13285              nil
13286 @end group
13287 @end smallexample
13289 @noindent
13290 (The @code{insert} function inserts its arguments at point; the
13291 @code{format} function returns a string formatted from its arguments
13292 the way @code{message} formats its arguments; @code{\n} produces a new
13293 line.)
13295 @item re-search-forward
13296 Search for a pattern, and if the pattern is found, move point to rest
13297 just after it.
13299 @noindent
13300 Takes four arguments, like @code{search-forward}:
13302 @enumerate
13303 @item
13304 A regular expression that specifies the pattern to search for.
13305 (Remember to put quotation marks around this argument!)
13307 @item
13308 Optionally, the limit of the search.
13310 @item
13311 Optionally, what to do if the search fails, return @code{nil} or an
13312 error message.
13314 @item
13315 Optionally, how many times to repeat the search; if negative, the
13316 search goes backwards.
13317 @end enumerate
13319 @item let*
13320 Bind some variables locally to particular values,
13321 and then evaluate the remaining arguments, returning the value of the
13322 last one.  While binding the local variables, use the local values of
13323 variables bound earlier, if any.
13325 @need 1250
13326 For example:
13328 @smallexample
13329 @group
13330 (let* ((foo 7)
13331        (bar (* 3 foo)))
13332   (message "`bar' is %d." bar))
13333      @result{} â€˜bar’ is 21.
13334 @end group
13335 @end smallexample
13337 @item match-beginning
13338 Return the position of the start of the text found by the last regular
13339 expression search.
13341 @item looking-at
13342 Return @code{t} for true if the text after point matches the argument,
13343 which should be a regular expression.
13345 @item eobp
13346 Return @code{t} for true if point is at the end of the accessible part
13347 of a buffer.  The end of the accessible part is the end of the buffer
13348 if the buffer is not narrowed; it is the end of the narrowed part if
13349 the buffer is narrowed.
13350 @end table
13352 @need 1500
13353 @node re-search Exercises
13354 @section Exercises with @code{re-search-forward}
13356 @itemize @bullet
13357 @item
13358 Write a function to search for a regular expression that matches two
13359 or more blank lines in sequence.
13361 @item
13362 Write a function to search for duplicated words, such as ``the the''.
13363 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
13364 Manual}, for information on how to write a regexp (a regular
13365 expression) to match a string that is composed of two identical
13366 halves.  You can devise several regexps; some are better than others.
13367 The function I use is described in an appendix, along with several
13368 regexps.  @xref{the-the, , @code{the-the} Duplicated Words Function}.
13369 @end itemize
13371 @node Counting Words
13372 @chapter Counting via Repetition and Regexps
13373 @cindex Repetition for word counting
13374 @cindex Regular expressions for word counting
13376 Repetition and regular expression searches are powerful tools that you
13377 often use when you write code in Emacs Lisp.  This chapter illustrates
13378 the use of regular expression searches through the construction of
13379 word count commands using @code{while} loops and recursion.
13381 @menu
13382 * Why Count Words::
13383 * @value{COUNT-WORDS}::          Use a regexp, but find a problem.
13384 * recursive-count-words::       Start with case of no words in region.
13385 * Counting Exercise::
13386 @end menu
13388 @ifnottex
13389 @node Why Count Words
13390 @unnumberedsec Counting words
13391 @end ifnottex
13393 The standard Emacs distribution contains functions for counting the
13394 number of lines and words within a region.
13396 Certain types of writing ask you to count words.  Thus, if you write
13397 an essay, you may be limited to 800 words; if you write a novel, you
13398 may discipline yourself to write 1000 words a day.  It seems odd, but
13399 for a long time, Emacs lacked a word count command.  Perhaps people used
13400 Emacs mostly for code or types of documentation that did not require
13401 word counts; or perhaps they restricted themselves to the operating
13402 system word count command, @code{wc}.  Alternatively, people may have
13403 followed the publishers' convention and computed a word count by
13404 dividing the number of characters in a document by five.
13406 There are many ways to implement a command to count words.  Here are
13407 some examples, which you may wish to compare with the standard Emacs
13408 command, @code{count-words-region}.
13410 @node @value{COUNT-WORDS}
13411 @section The @code{@value{COUNT-WORDS}} Function
13412 @findex @value{COUNT-WORDS}
13414 A word count command could count words in a line, paragraph, region,
13415 or buffer.  What should the command cover?  You could design the
13416 command to count the number of words in a complete buffer.  However,
13417 the Emacs tradition encourages flexibility---you may want to count
13418 words in just a section, rather than all of a buffer.  So it makes
13419 more sense to design the command to count the number of words in a
13420 region.  Once you have a command to count words in a region, you can,
13421 if you wish, count words in a whole buffer by marking it with
13422 @w{@kbd{C-x h}} (@code{mark-whole-buffer}).
13424 Clearly, counting words is a repetitive act: starting from the
13425 beginning of the region, you count the first word, then the second
13426 word, then the third word, and so on, until you reach the end of the
13427 region.  This means that word counting is ideally suited to recursion
13428 or to a @code{while} loop.
13430 @menu
13431 * Design @value{COUNT-WORDS}::  The definition using a @code{while} loop.
13432 * Whitespace Bug::              The Whitespace Bug in @code{@value{COUNT-WORDS}}.
13433 @end menu
13435 @ifnottex
13436 @node Design @value{COUNT-WORDS}
13437 @unnumberedsubsec Designing @code{@value{COUNT-WORDS}}
13438 @end ifnottex
13440 First, we will implement the word count command with a @code{while}
13441 loop, then with recursion.  The command will, of course, be
13442 interactive.
13444 @need 800
13445 The template for an interactive function definition is, as always:
13447 @smallexample
13448 @group
13449 (defun @var{name-of-function} (@var{argument-list})
13450   "@var{documentation}@dots{}"
13451   (@var{interactive-expression}@dots{})
13452   @var{body}@dots{})
13453 @end group
13454 @end smallexample
13456 What we need to do is fill in the slots.
13458 The name of the function should be self-explanatory and similar to the
13459 existing @code{count-lines-region} name.  This makes the name easier
13460 to remember.  @code{count-words-region} is the obvious choice.  Since
13461 that name is now used for the standard Emacs command to count words, we
13462 will name our implementation @code{@value{COUNT-WORDS}}.
13464 The function counts words within a region.  This means that the
13465 argument list must contain symbols that are bound to the two
13466 positions, the beginning and end of the region.  These two positions
13467 can be called @samp{beginning} and @samp{end} respectively.  The first
13468 line of the documentation should be a single sentence, since that is
13469 all that is printed as documentation by a command such as
13470 @code{apropos}.  The interactive expression will be of the form
13471 @samp{(interactive "r")}, since that will cause Emacs to pass the
13472 beginning and end of the region to the function's argument list.  All
13473 this is routine.
13475 The body of the function needs to be written to do three tasks:
13476 first, to set up conditions under which the @code{while} loop can
13477 count words, second, to run the @code{while} loop, and third, to send
13478 a message to the user.
13480 When a user calls @code{@value{COUNT-WORDS}}, point may be at the
13481 beginning or the end of the region.  However, the counting process
13482 must start at the beginning of the region.  This means we will want
13483 to put point there if it is not already there.  Executing
13484 @code{(goto-char beginning)} ensures this.  Of course, we will want to
13485 return point to its expected position when the function finishes its
13486 work.  For this reason, the body must be enclosed in a
13487 @code{save-excursion} expression.
13489 The central part of the body of the function consists of a
13490 @code{while} loop in which one expression jumps point forward word by
13491 word, and another expression counts those jumps.  The true-or-false-test
13492 of the @code{while} loop should test true so long as point should jump
13493 forward, and false when point is at the end of the region.
13495 We could use @code{(forward-word 1)} as the expression for moving point
13496 forward word by word, but it is easier to see what Emacs identifies as a
13497 ``word'' if we use a regular expression search.
13499 A regular expression search that finds the pattern for which it is
13500 searching leaves point after the last character matched.  This means
13501 that a succession of successful word searches will move point forward
13502 word by word.
13504 As a practical matter, we want the regular expression search to jump
13505 over whitespace and punctuation between words as well as over the
13506 words themselves.  A regexp that refuses to jump over interword
13507 whitespace would never jump more than one word!  This means that
13508 the regexp should include the whitespace and punctuation that follows
13509 a word, if any, as well as the word itself.  (A word may end a buffer
13510 and not have any following whitespace or punctuation, so that part of
13511 the regexp must be optional.)
13513 Thus, what we want for the regexp is a pattern defining one or more
13514 word constituent characters followed, optionally, by one or more
13515 characters that are not word constituents.  The regular expression for
13516 this is:
13518 @smallexample
13519 \w+\W*
13520 @end smallexample
13522 @noindent
13523 The buffer's syntax table determines which characters are and are not
13524 word constituents.  For more information about syntax,
13525 @pxref{Syntax Tables, , Syntax Tables, elisp, The GNU Emacs Lisp
13526 Reference Manual}.
13528 @need 800
13529 The search expression looks like this:
13531 @smallexample
13532 (re-search-forward "\\w+\\W*")
13533 @end smallexample
13535 @noindent
13536 (Note that paired backslashes precede the @samp{w} and @samp{W}.  A
13537 single backslash has special meaning to the Emacs Lisp interpreter.
13538 It indicates that the following character is interpreted differently
13539 than usual.  For example, the two characters, @samp{\n}, stand for
13540 @samp{newline}, rather than for a backslash followed by @samp{n}.  Two
13541 backslashes in a row stand for an ordinary, unspecial backslash, so
13542 Emacs Lisp interpreter ends of seeing a single backslash followed by a
13543 letter.  So it discovers the letter is special.)
13545 We need a counter to count how many words there are; this variable
13546 must first be set to 0 and then incremented each time Emacs goes
13547 around the @code{while} loop.  The incrementing expression is simply:
13549 @smallexample
13550 (setq count (1+ count))
13551 @end smallexample
13553 Finally, we want to tell the user how many words there are in the
13554 region.  The @code{message} function is intended for presenting this
13555 kind of information to the user.  The message has to be phrased so
13556 that it reads properly regardless of how many words there are in the
13557 region: we don't want to say that ``there are 1 words in the region''.
13558 The conflict between singular and plural is ungrammatical.  We can
13559 solve this problem by using a conditional expression that evaluates
13560 different messages depending on the number of words in the region.
13561 There are three possibilities: no words in the region, one word in the
13562 region, and more than one word.  This means that the @code{cond}
13563 special form is appropriate.
13565 @need 1500
13566 All this leads to the following function definition:
13568 @smallexample
13569 @group
13570 ;;; @r{First version; has bugs!}
13571 (defun @value{COUNT-WORDS} (beginning end)
13572   "Print number of words in the region.
13573 Words are defined as at least one word-constituent
13574 character followed by at least one character that
13575 is not a word-constituent.  The buffer's syntax
13576 table determines which characters these are."
13577   (interactive "r")
13578   (message "Counting words in region ... ")
13579 @end group
13581 @group
13582 ;;; @r{1. Set up appropriate conditions.}
13583   (save-excursion
13584     (goto-char beginning)
13585     (let ((count 0))
13586 @end group
13588 @group
13589 ;;; @r{2. Run the} while @r{loop.}
13590       (while (< (point) end)
13591         (re-search-forward "\\w+\\W*")
13592         (setq count (1+ count)))
13593 @end group
13595 @group
13596 ;;; @r{3. Send a message to the user.}
13597       (cond ((zerop count)
13598              (message
13599               "The region does NOT have any words."))
13600             ((= 1 count)
13601              (message
13602               "The region has 1 word."))
13603             (t
13604              (message
13605               "The region has %d words." count))))))
13606 @end group
13607 @end smallexample
13609 @noindent
13610 As written, the function works, but not in all circumstances.
13612 @node Whitespace Bug
13613 @subsection The Whitespace Bug in @code{@value{COUNT-WORDS}}
13615 The @code{@value{COUNT-WORDS}} command described in the preceding
13616 section has two bugs, or rather, one bug with two manifestations.
13617 First, if you mark a region containing only whitespace in the middle
13618 of some text, the @code{@value{COUNT-WORDS}} command tells you that the
13619 region contains one word!  Second, if you mark a region containing
13620 only whitespace at the end of the buffer or the accessible portion of
13621 a narrowed buffer, the command displays an error message that looks
13622 like this:
13624 @smallexample
13625 Search failed: "\\w+\\W*"
13626 @end smallexample
13628 If you are reading this in Info in GNU Emacs, you can test for these
13629 bugs yourself.
13631 First, evaluate the function in the usual manner to install it.
13632 @ifinfo
13633 Here is a copy of the definition.  Place your cursor after the closing
13634 parenthesis and type @kbd{C-x C-e} to install it.
13636 @smallexample
13637 @group
13638 ;; @r{First version; has bugs!}
13639 (defun @value{COUNT-WORDS} (beginning end)
13640   "Print number of words in the region.
13641 Words are defined as at least one word-constituent character followed
13642 by at least one character that is not a word-constituent.  The buffer's
13643 syntax table determines which characters these are."
13644 @end group
13645 @group
13646   (interactive "r")
13647   (message "Counting words in region ... ")
13648 @end group
13650 @group
13651 ;;; @r{1. Set up appropriate conditions.}
13652   (save-excursion
13653     (goto-char beginning)
13654     (let ((count 0))
13655 @end group
13657 @group
13658 ;;; @r{2. Run the} while @r{loop.}
13659       (while (< (point) end)
13660         (re-search-forward "\\w+\\W*")
13661         (setq count (1+ count)))
13662 @end group
13664 @group
13665 ;;; @r{3. Send a message to the user.}
13666       (cond ((zerop count)
13667              (message "The region does NOT have any words."))
13668             ((= 1 count) (message "The region has 1 word."))
13669             (t (message "The region has %d words." count))))))
13670 @end group
13671 @end smallexample
13672 @end ifinfo
13674 @need 1000
13675 If you wish, you can also install this keybinding by evaluating it:
13677 @smallexample
13678 (global-set-key "\C-c=" '@value{COUNT-WORDS})
13679 @end smallexample
13681 To conduct the first test, set mark and point to the beginning and end
13682 of the following line and then type @kbd{C-c =} (or @kbd{M-x
13683 @value{COUNT-WORDS}} if you have not bound @kbd{C-c =}):
13685 @smallexample
13686     one   two  three
13687 @end smallexample
13689 @noindent
13690 Emacs will tell you, correctly, that the region has three words.
13692 Repeat the test, but place mark at the beginning of the line and place
13693 point just @emph{before} the word @samp{one}.  Again type the command
13694 @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}).  Emacs should tell you
13695 that the region has no words, since it is composed only of the
13696 whitespace at the beginning of the line.  But instead Emacs tells you
13697 that the region has one word!
13699 For the third test, copy the sample line to the end of the
13700 @file{*scratch*} buffer and then type several spaces at the end of the
13701 line.  Place mark right after the word @samp{three} and point at the
13702 end of line.  (The end of the line will be the end of the buffer.)
13703 Type @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}) as you did before.
13704 Again, Emacs should tell you that the region has no words, since it is
13705 composed only of the whitespace at the end of the line.  Instead,
13706 Emacs displays an error message saying @samp{Search failed}.
13708 The two bugs stem from the same problem.
13710 Consider the first manifestation of the bug, in which the command
13711 tells you that the whitespace at the beginning of the line contains
13712 one word.  What happens is this: The @code{M-x @value{COUNT-WORDS}}
13713 command moves point to the beginning of the region.  The @code{while}
13714 tests whether the value of point is smaller than the value of
13715 @code{end}, which it is.  Consequently, the regular expression search
13716 looks for and finds the first word.  It leaves point after the word.
13717 @code{count} is set to one.  The @code{while} loop repeats; but this
13718 time the value of point is larger than the value of @code{end}, the
13719 loop is exited; and the function displays a message saying the number
13720 of words in the region is one.  In brief, the regular expression
13721 search looks for and finds the word even though it is outside
13722 the marked region.
13724 In the second manifestation of the bug, the region is whitespace at
13725 the end of the buffer.  Emacs says @samp{Search failed}.  What happens
13726 is that the true-or-false-test in the @code{while} loop tests true, so
13727 the search expression is executed.  But since there are no more words
13728 in the buffer, the search fails.
13730 In both manifestations of the bug, the search extends or attempts to
13731 extend outside of the region.
13733 The solution is to limit the search to the region---this is a fairly
13734 simple action, but as you may have come to expect, it is not quite as
13735 simple as you might think.
13737 As we have seen, the @code{re-search-forward} function takes a search
13738 pattern as its first argument.  But in addition to this first,
13739 mandatory argument, it accepts three optional arguments.  The optional
13740 second argument bounds the search.  The optional third argument, if
13741 @code{t}, causes the function to return @code{nil} rather than signal
13742 an error if the search fails.  The optional fourth argument is a
13743 repeat count.  (In Emacs, you can see a function's documentation by
13744 typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
13746 In the @code{@value{COUNT-WORDS}} definition, the value of the end of
13747 the region is held by the variable @code{end} which is passed as an
13748 argument to the function.  Thus, we can add @code{end} as an argument
13749 to the regular expression search expression:
13751 @smallexample
13752 (re-search-forward "\\w+\\W*" end)
13753 @end smallexample
13755 However, if you make only this change to the @code{@value{COUNT-WORDS}}
13756 definition and then test the new version of the definition on a
13757 stretch of whitespace, you will receive an error message saying
13758 @samp{Search failed}.
13760 What happens is this: the search is limited to the region, and fails
13761 as you expect because there are no word-constituent characters in the
13762 region.  Since it fails, we receive an error message.  But we do not
13763 want to receive an error message in this case; we want to receive the
13764 message ``The region does NOT have any words.''
13766 The solution to this problem is to provide @code{re-search-forward}
13767 with a third argument of @code{t}, which causes the function to return
13768 @code{nil} rather than signal an error if the search fails.
13770 However, if you make this change and try it, you will see the message
13771 ``Counting words in region ... '' and @dots{} you will keep on seeing
13772 that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
13774 Here is what happens: the search is limited to the region, as before,
13775 and it fails because there are no word-constituent characters in the
13776 region, as expected.  Consequently, the @code{re-search-forward}
13777 expression returns @code{nil}.  It does nothing else.  In particular,
13778 it does not move point, which it does as a side effect if it finds the
13779 search target.  After the @code{re-search-forward} expression returns
13780 @code{nil}, the next expression in the @code{while} loop is evaluated.
13781 This expression increments the count.  Then the loop repeats.  The
13782 true-or-false-test tests true because the value of point is still less
13783 than the value of end, since the @code{re-search-forward} expression
13784 did not move point. @dots{} and the cycle repeats @dots{}
13786 The @code{@value{COUNT-WORDS}} definition requires yet another
13787 modification, to cause the true-or-false-test of the @code{while} loop
13788 to test false if the search fails.  Put another way, there are two
13789 conditions that must be satisfied in the true-or-false-test before the
13790 word count variable is incremented: point must still be within the
13791 region and the search expression must have found a word to count.
13793 Since both the first condition and the second condition must be true
13794 together, the two expressions, the region test and the search
13795 expression, can be joined with an @code{and} special form and embedded in
13796 the @code{while} loop as the true-or-false-test, like this:
13798 @smallexample
13799 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
13800 @end smallexample
13802 @c colon in printed section title causes problem in Info cross reference
13803 @c also trouble with an overfull hbox
13804 @iftex
13805 @noindent
13806 (For information about @code{and}, see
13807 @ref{kill-new function, , The @code{kill-new} function}.)
13808 @end iftex
13809 @ifinfo
13810 @noindent
13811 (@xref{kill-new function, , The @code{kill-new} function}, for
13812 information about @code{and}.)
13813 @end ifinfo
13815 The @code{re-search-forward} expression returns @code{t} if the search
13816 succeeds and as a side effect moves point.  Consequently, as words are
13817 found, point is moved through the region.  When the search expression
13818 fails to find another word, or when point reaches the end of the
13819 region, the true-or-false-test tests false, the @code{while} loop
13820 exits, and the @code{@value{COUNT-WORDS}} function displays one or
13821 other of its messages.
13823 After incorporating these final changes, the @code{@value{COUNT-WORDS}}
13824 works without bugs (or at least, without bugs that I have found!).
13825 Here is what it looks like:
13827 @smallexample
13828 @group
13829 ;;; @r{Final version:} @code{while}
13830 (defun @value{COUNT-WORDS} (beginning end)
13831   "Print number of words in the region."
13832   (interactive "r")
13833   (message "Counting words in region ... ")
13834 @end group
13836 @group
13837 ;;; @r{1. Set up appropriate conditions.}
13838   (save-excursion
13839     (let ((count 0))
13840       (goto-char beginning)
13841 @end group
13843 @group
13844 ;;; @r{2. Run the} while @r{loop.}
13845       (while (and (< (point) end)
13846                   (re-search-forward "\\w+\\W*" end t))
13847         (setq count (1+ count)))
13848 @end group
13850 @group
13851 ;;; @r{3. Send a message to the user.}
13852       (cond ((zerop count)
13853              (message
13854               "The region does NOT have any words."))
13855             ((= 1 count)
13856              (message
13857               "The region has 1 word."))
13858             (t
13859              (message
13860               "The region has %d words." count))))))
13861 @end group
13862 @end smallexample
13864 @node recursive-count-words
13865 @section Count Words Recursively
13866 @cindex Count words recursively
13867 @cindex Recursively counting words
13868 @cindex Words, counted recursively
13870 You can write the function for counting words recursively as well as
13871 with a @code{while} loop.  Let's see how this is done.
13873 First, we need to recognize that the @code{@value{COUNT-WORDS}}
13874 function has three jobs: it sets up the appropriate conditions for
13875 counting to occur; it counts the words in the region; and it sends a
13876 message to the user telling how many words there are.
13878 If we write a single recursive function to do everything, we will
13879 receive a message for every recursive call.  If the region contains 13
13880 words, we will receive thirteen messages, one right after the other.
13881 We don't want this!  Instead, we must write two functions to do the
13882 job, one of which (the recursive function) will be used inside of the
13883 other.  One function will set up the conditions and display the
13884 message; the other will return the word count.
13886 Let us start with the function that causes the message to be displayed.
13887 We can continue to call this @code{@value{COUNT-WORDS}}.
13889 This is the function that the user will call.  It will be interactive.
13890 Indeed, it will be similar to our previous versions of this
13891 function, except that it will call @code{recursive-count-words} to
13892 determine how many words are in the region.
13894 @need 1250
13895 We can readily construct a template for this function, based on our
13896 previous versions:
13898 @smallexample
13899 @group
13900 ;; @r{Recursive version; uses regular expression search}
13901 (defun @value{COUNT-WORDS} (beginning end)
13902   "@var{documentation}@dots{}"
13903   (@var{interactive-expression}@dots{})
13904 @end group
13905 @group
13907 ;;; @r{1. Set up appropriate conditions.}
13908   (@var{explanatory message})
13909   (@var{set-up functions}@dots{}
13910 @end group
13911 @group
13913 ;;; @r{2. Count the words.}
13914     @var{recursive call}
13915 @end group
13916 @group
13918 ;;; @r{3. Send a message to the user.}
13919     @var{message providing word count}))
13920 @end group
13921 @end smallexample
13923 The definition looks straightforward, except that somehow the count
13924 returned by the recursive call must be passed to the message
13925 displaying the word count.  A little thought suggests that this can be
13926 done by making use of a @code{let} expression: we can bind a variable
13927 in the varlist of a @code{let} expression to the number of words in
13928 the region, as returned by the recursive call; and then the
13929 @code{cond} expression, using binding, can display the value to the
13930 user.
13932 Often, one thinks of the binding within a @code{let} expression as
13933 somehow secondary to the primary work of a function.  But in this
13934 case, what you might consider the primary job of the function,
13935 counting words, is done within the @code{let} expression.
13937 @need 1250
13938 Using @code{let}, the function definition looks like this:
13940 @smallexample
13941 @group
13942 (defun @value{COUNT-WORDS} (beginning end)
13943   "Print number of words in the region."
13944   (interactive "r")
13945 @end group
13947 @group
13948 ;;; @r{1. Set up appropriate conditions.}
13949   (message "Counting words in region ... ")
13950   (save-excursion
13951     (goto-char beginning)
13952 @end group
13954 @group
13955 ;;; @r{2. Count the words.}
13956     (let ((count (recursive-count-words end)))
13957 @end group
13959 @group
13960 ;;; @r{3. Send a message to the user.}
13961       (cond ((zerop count)
13962              (message
13963               "The region does NOT have any words."))
13964             ((= 1 count)
13965              (message
13966               "The region has 1 word."))
13967             (t
13968              (message
13969               "The region has %d words." count))))))
13970 @end group
13971 @end smallexample
13973 Next, we need to write the recursive counting function.
13975 A recursive function has at least three parts: the do-again-test, the
13976 next-step-expression, and the recursive call.
13978 The do-again-test determines whether the function will or will not be
13979 called again.  Since we are counting words in a region and can use a
13980 function that moves point forward for every word, the do-again-test
13981 can check whether point is still within the region.  The do-again-test
13982 should find the value of point and determine whether point is before,
13983 at, or after the value of the end of the region.  We can use the
13984 @code{point} function to locate point.  Clearly, we must pass the
13985 value of the end of the region to the recursive counting function as an
13986 argument.
13988 In addition, the do-again-test should also test whether the search finds a
13989 word.  If it does not, the function should not call itself again.
13991 The next-step-expression changes a value so that when the recursive
13992 function is supposed to stop calling itself, it stops.  More
13993 precisely, the next-step-expression changes a value so that at the
13994 right time, the do-again-test stops the recursive function from
13995 calling itself again.  In this case, the next-step-expression can be
13996 the expression that moves point forward, word by word.
13998 The third part of a recursive function is the recursive call.
14000 Somewhere, we also need a part that does the work of the
14001 function, a part that does the counting.  A vital part!
14003 @need 1250
14004 But already, we have an outline of the recursive counting function:
14006 @smallexample
14007 @group
14008 (defun recursive-count-words (region-end)
14009   "@var{documentation}@dots{}"
14010    @var{do-again-test}
14011    @var{next-step-expression}
14012    @var{recursive call})
14013 @end group
14014 @end smallexample
14016 Now we need to fill in the slots.  Let's start with the simplest cases
14017 first:  if point is at or beyond the end of the region, there cannot
14018 be any words in the region, so the function should return zero.
14019 Likewise, if the search fails, there are no words to count, so the
14020 function should return zero.
14022 On the other hand, if point is within the region and the search
14023 succeeds, the function should call itself again.
14025 @need 800
14026 Thus, the do-again-test should look like this:
14028 @smallexample
14029 @group
14030 (and (< (point) region-end)
14031      (re-search-forward "\\w+\\W*" region-end t))
14032 @end group
14033 @end smallexample
14035 Note that the search expression is part of the do-again-test---the
14036 function returns @code{t} if its search succeeds and @code{nil} if it
14037 fails.  (@xref{Whitespace Bug, , The Whitespace Bug in
14038 @code{@value{COUNT-WORDS}}}, for an explanation of how
14039 @code{re-search-forward} works.)
14041 The do-again-test is the true-or-false test of an @code{if} clause.
14042 Clearly, if the do-again-test succeeds, the then-part of the @code{if}
14043 clause should call the function again; but if it fails, the else-part
14044 should return zero since either point is outside the region or the
14045 search failed because there were no words to find.
14047 But before considering the recursive call, we need to consider the
14048 next-step-expression.  What is it?  Interestingly, it is the search
14049 part of the do-again-test.
14051 In addition to returning @code{t} or @code{nil} for the
14052 do-again-test, @code{re-search-forward} moves point forward as a side
14053 effect of a successful search.  This is the action that changes the
14054 value of point so that the recursive function stops calling itself
14055 when point completes its movement through the region.  Consequently,
14056 the @code{re-search-forward} expression is the next-step-expression.
14058 @need 1200
14059 In outline, then, the body of the @code{recursive-count-words}
14060 function looks like this:
14062 @smallexample
14063 @group
14064 (if @var{do-again-test-and-next-step-combined}
14065     ;; @r{then}
14066     @var{recursive-call-returning-count}
14067   ;; @r{else}
14068   @var{return-zero})
14069 @end group
14070 @end smallexample
14072 How to incorporate the mechanism that counts?
14074 If you are not used to writing recursive functions, a question like
14075 this can be troublesome.  But it can and should be approached
14076 systematically.
14078 We know that the counting mechanism should be associated in some way
14079 with the recursive call.  Indeed, since the next-step-expression moves
14080 point forward by one word, and since a recursive call is made for
14081 each word, the counting mechanism must be an expression that adds one
14082 to the value returned by a call to @code{recursive-count-words}.
14084 @need 800
14085 Consider several cases:
14087 @itemize @bullet
14088 @item
14089 If there are two words in the region, the function should return
14090 a value resulting from adding one to the value returned when it counts
14091 the first word, plus the number returned when it counts the remaining
14092 words in the region, which in this case is one.
14094 @item
14095 If there is one word in the region, the function should return
14096 a value resulting from adding one to the value returned when it counts
14097 that word, plus the number returned when it counts the remaining
14098 words in the region, which in this case is zero.
14100 @item
14101 If there are no words in the region, the function should return zero.
14102 @end itemize
14104 From the sketch we can see that the else-part of the @code{if} returns
14105 zero for the case of no words.  This means that the then-part of the
14106 @code{if} must return a value resulting from adding one to the value
14107 returned from a count of the remaining words.
14109 @need 1200
14110 The expression will look like this, where @code{1+} is a function that
14111 adds one to its argument.
14113 @smallexample
14114 (1+ (recursive-count-words region-end))
14115 @end smallexample
14117 @need 1200
14118 The whole @code{recursive-count-words} function will then look like
14119 this:
14121 @smallexample
14122 @group
14123 (defun recursive-count-words (region-end)
14124   "@var{documentation}@dots{}"
14126 ;;; @r{1. do-again-test}
14127   (if (and (< (point) region-end)
14128            (re-search-forward "\\w+\\W*" region-end t))
14129 @end group
14131 @group
14132 ;;; @r{2. then-part: the recursive call}
14133       (1+ (recursive-count-words region-end))
14135 ;;; @r{3. else-part}
14136     0))
14137 @end group
14138 @end smallexample
14140 @need 1250
14141 Let's examine how this works:
14143 If there are no words in the region, the else part of the @code{if}
14144 expression is evaluated and consequently the function returns zero.
14146 If there is one word in the region, the value of point is less than
14147 the value of @code{region-end} and the search succeeds.  In this case,
14148 the true-or-false-test of the @code{if} expression tests true, and the
14149 then-part of the @code{if} expression is evaluated.  The counting
14150 expression is evaluated.  This expression returns a value (which will
14151 be the value returned by the whole function) that is the sum of one
14152 added to the value returned by a recursive call.
14154 Meanwhile, the next-step-expression has caused point to jump over the
14155 first (and in this case only) word in the region.  This means that
14156 when @code{(recursive-count-words region-end)} is evaluated a second
14157 time, as a result of the recursive call, the value of point will be
14158 equal to or greater than the value of region end.  So this time,
14159 @code{recursive-count-words} will return zero.  The zero will be added
14160 to one, and the original evaluation of @code{recursive-count-words}
14161 will return one plus zero, which is one, which is the correct amount.
14163 Clearly, if there are two words in the region, the first call to
14164 @code{recursive-count-words} returns one added to the value returned
14165 by calling @code{recursive-count-words} on a region containing the
14166 remaining word---that is, it adds one to one, producing two, which is
14167 the correct amount.
14169 Similarly, if there are three words in the region, the first call to
14170 @code{recursive-count-words} returns one added to the value returned
14171 by calling @code{recursive-count-words} on a region containing the
14172 remaining two words---and so on and so on.
14174 @need 1250
14175 @noindent
14176 With full documentation the two functions look like this:
14178 @need 1250
14179 @noindent
14180 The recursive function:
14182 @findex recursive-count-words
14183 @smallexample
14184 @group
14185 (defun recursive-count-words (region-end)
14186   "Number of words between point and REGION-END."
14187 @end group
14189 @group
14190 ;;; @r{1. do-again-test}
14191   (if (and (< (point) region-end)
14192            (re-search-forward "\\w+\\W*" region-end t))
14193 @end group
14195 @group
14196 ;;; @r{2. then-part: the recursive call}
14197       (1+ (recursive-count-words region-end))
14199 ;;; @r{3. else-part}
14200     0))
14201 @end group
14202 @end smallexample
14204 @need 800
14205 @noindent
14206 The wrapper:
14208 @smallexample
14209 @group
14210 ;;; @r{Recursive version}
14211 (defun @value{COUNT-WORDS} (beginning end)
14212   "Print number of words in the region.
14213 @end group
14215 @group
14216 Words are defined as at least one word-constituent
14217 character followed by at least one character that is
14218 not a word-constituent.  The buffer's syntax table
14219 determines which characters these are."
14220 @end group
14221 @group
14222   (interactive "r")
14223   (message "Counting words in region ... ")
14224   (save-excursion
14225     (goto-char beginning)
14226     (let ((count (recursive-count-words end)))
14227 @end group
14228 @group
14229       (cond ((zerop count)
14230              (message
14231               "The region does NOT have any words."))
14232 @end group
14233 @group
14234             ((= 1 count)
14235              (message "The region has 1 word."))
14236             (t
14237              (message
14238               "The region has %d words." count))))))
14239 @end group
14240 @end smallexample
14242 @node Counting Exercise
14243 @section Exercise: Counting Punctuation
14245 Using a @code{while} loop, write a function to count the number of
14246 punctuation marks in a region---period, comma, semicolon, colon,
14247 exclamation mark, and question mark.  Do the same using recursion.
14249 @node Words in a defun
14250 @chapter Counting Words in a @code{defun}
14251 @cindex Counting words in a @code{defun}
14252 @cindex Word counting in a @code{defun}
14254 Our next project is to count the number of words in a function
14255 definition.  Clearly, this can be done using some variant of
14256 @code{@value{COUNT-WORDS}}.  @xref{Counting Words, , Counting via
14257 Repetition and Regexps}.  If we are just going to count the words in
14258 one definition, it is easy enough to mark the definition with the
14259 @kbd{C-M-h} (@code{mark-defun}) command, and then call
14260 @code{@value{COUNT-WORDS}}.
14262 However, I am more ambitious: I want to count the words and symbols in
14263 every definition in the Emacs sources and then print a graph that
14264 shows how many functions there are of each length: how many contain 40
14265 to 49 words or symbols, how many contain 50 to 59 words or symbols,
14266 and so on.  I have often been curious how long a typical function is,
14267 and this will tell.
14269 @menu
14270 * Divide and Conquer::
14271 * Words and Symbols::           What to count?
14272 * Syntax::                      What constitutes a word or symbol?
14273 * count-words-in-defun::        Very like @code{@value{COUNT-WORDS}}.
14274 * Several defuns::              Counting several defuns in a file.
14275 * Find a File::                 Do you want to look at a file?
14276 * lengths-list-file::           A list of the lengths of many definitions.
14277 * Several files::               Counting in definitions in different files.
14278 * Several files recursively::   Recursively counting in different files.
14279 * Prepare the data::            Prepare the data for display in a graph.
14280 @end menu
14282 @ifnottex
14283 @node Divide and Conquer
14284 @unnumberedsec Divide and Conquer
14285 @end ifnottex
14287 Described in one phrase, the histogram project is daunting; but
14288 divided into numerous small steps, each of which we can take one at a
14289 time, the project becomes less fearsome.  Let us consider what the
14290 steps must be:
14292 @itemize @bullet
14293 @item
14294 First, write a function to count the words in one definition.  This
14295 includes the problem of handling symbols as well as words.
14297 @item
14298 Second, write a function to list the number of words in each function
14299 in a file.  This function can use the @code{count-words-in-defun}
14300 function.
14302 @item
14303 Third, write a function to list the number of words in each function
14304 in each of several files.  This entails automatically finding the
14305 various files, switching to them, and counting the words in the
14306 definitions within them.
14308 @item
14309 Fourth, write a function to convert the list of numbers that we
14310 created in step three to a form that will be suitable for printing as
14311 a graph.
14313 @item
14314 Fifth, write a function to print the results as a graph.
14315 @end itemize
14317 This is quite a project!  But if we take each step slowly, it will not
14318 be difficult.
14320 @node Words and Symbols
14321 @section What to Count?
14322 @cindex Words and symbols in defun
14324 When we first start thinking about how to count the words in a
14325 function definition, the first question is (or ought to be) what are
14326 we going to count?  When we speak of ``words'' with respect to a Lisp
14327 function definition, we are actually speaking, in large part, of
14328 symbols.  For example, the following @code{multiply-by-seven}
14329 function contains the five symbols @code{defun},
14330 @code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}.  In
14331 addition, in the documentation string, it contains the four words
14332 @samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}.  The
14333 symbol @samp{number} is repeated, so the definition contains a total
14334 of ten words and symbols.
14336 @smallexample
14337 @group
14338 (defun multiply-by-seven (number)
14339   "Multiply NUMBER by seven."
14340   (* 7 number))
14341 @end group
14342 @end smallexample
14344 @noindent
14345 However, if we mark the @code{multiply-by-seven} definition with
14346 @kbd{C-M-h} (@code{mark-defun}), and then call
14347 @code{@value{COUNT-WORDS}} on it, we will find that
14348 @code{@value{COUNT-WORDS}} claims the definition has eleven words, not
14349 ten!  Something is wrong!
14351 The problem is twofold: @code{@value{COUNT-WORDS}} does not count the
14352 @samp{*} as a word, and it counts the single symbol,
14353 @code{multiply-by-seven}, as containing three words.  The hyphens are
14354 treated as if they were interword spaces rather than intraword
14355 connectors: @samp{multiply-by-seven} is counted as if it were written
14356 @samp{multiply by seven}.
14358 The cause of this confusion is the regular expression search within
14359 the @code{@value{COUNT-WORDS}} definition that moves point forward word
14360 by word.  In the canonical version of @code{@value{COUNT-WORDS}}, the
14361 regexp is:
14363 @smallexample
14364 "\\w+\\W*"
14365 @end smallexample
14367 @noindent
14368 This regular expression is a pattern defining one or more word
14369 constituent characters possibly followed by one or more characters
14370 that are not word constituents.  What is meant by ``word constituent
14371 characters'' brings us to the issue of syntax, which is worth a section
14372 of its own.
14374 @node Syntax
14375 @section What Constitutes a Word or Symbol?
14376 @cindex Syntax categories and tables
14378 Emacs treats different characters as belonging to different
14379 @dfn{syntax categories}.  For example, the regular expression,
14380 @samp{\\w+}, is a pattern specifying one or more @emph{word
14381 constituent} characters.  Word constituent characters are members of
14382 one syntax category.  Other syntax categories include the class of
14383 punctuation characters, such as the period and the comma, and the
14384 class of whitespace characters, such as the blank space and the tab
14385 character.  (For more information, @pxref{Syntax Tables, , Syntax
14386 Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
14388 Syntax tables specify which characters belong to which categories.
14389 Usually, a hyphen is not specified as a word constituent character.
14390 Instead, it is specified as being in the class of characters that are
14391 part of symbol names but not words.  This means that the
14392 @code{@value{COUNT-WORDS}} function treats it in the same way it treats
14393 an interword white space, which is why @code{@value{COUNT-WORDS}}
14394 counts @samp{multiply-by-seven} as three words.
14396 There are two ways to cause Emacs to count @samp{multiply-by-seven} as
14397 one symbol: modify the syntax table or modify the regular expression.
14399 We could redefine a hyphen as a word constituent character by
14400 modifying the syntax table that Emacs keeps for each mode.  This
14401 action would serve our purpose, except that a hyphen is merely the
14402 most common character within symbols that is not typically a word
14403 constituent character; there are others, too.
14405 Alternatively, we can redefine the regexp used in the
14406 @code{@value{COUNT-WORDS}} definition so as to include symbols.  This
14407 procedure has the merit of clarity, but the task is a little tricky.
14409 @need 1200
14410 The first part is simple enough: the pattern must match at least one
14411 character that is a word or symbol constituent.  Thus:
14413 @smallexample
14414 "\\(\\w\\|\\s_\\)+"
14415 @end smallexample
14417 @noindent
14418 The @samp{\\(} is the first part of the grouping construct that
14419 includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
14420 by the @samp{\\|}.  The @samp{\\w} matches any word-constituent
14421 character and the @samp{\\s_} matches any character that is part of a
14422 symbol name but not a word-constituent character.  The @samp{+}
14423 following the group indicates that the word or symbol constituent
14424 characters must be matched at least once.
14426 However, the second part of the regexp is more difficult to design.
14427 What we want is to follow the first part with optionally one or more
14428 characters that are not constituents of a word or symbol.  At first,
14429 I thought I could define this with the following:
14431 @smallexample
14432 "\\(\\W\\|\\S_\\)*"
14433 @end smallexample
14435 @noindent
14436 The upper case @samp{W} and @samp{S} match characters that are
14437 @emph{not} word or symbol constituents.  Unfortunately, this
14438 expression matches any character that is either not a word constituent
14439 or not a symbol constituent.  This matches any character!
14441 I then noticed that every word or symbol in my test region was
14442 followed by white space (blank space, tab, or newline).  So I tried
14443 placing a pattern to match one or more blank spaces after the pattern
14444 for one or more word or symbol constituents.  This failed, too.  Words
14445 and symbols are often separated by whitespace, but in actual code
14446 parentheses may follow symbols and punctuation may follow words.  So
14447 finally, I designed a pattern in which the word or symbol constituents
14448 are followed optionally by characters that are not white space and
14449 then followed optionally by white space.
14451 @need 800
14452 Here is the full regular expression:
14454 @smallexample
14455 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14456 @end smallexample
14458 @node count-words-in-defun
14459 @section The @code{count-words-in-defun} Function
14460 @cindex Counting words in a @code{defun}
14462 We have seen that there are several ways to write a
14463 @code{count-words-region} function.  To write a
14464 @code{count-words-in-defun}, we need merely adapt one of these
14465 versions.
14467 The version that uses a @code{while} loop is easy to understand, so I
14468 am going to adapt that.  Because @code{count-words-in-defun} will be
14469 part of a more complex program, it need not be interactive and it need
14470 not display a message but just return the count.  These considerations
14471 simplify the definition a little.
14473 On the other hand, @code{count-words-in-defun} will be used within a
14474 buffer that contains function definitions.  Consequently, it is
14475 reasonable to ask that the function determine whether it is called
14476 when point is within a function definition, and if it is, to return
14477 the count for that definition.  This adds complexity to the
14478 definition, but saves us from needing to pass arguments to the
14479 function.
14481 @need 1250
14482 These considerations lead us to prepare the following template:
14484 @smallexample
14485 @group
14486 (defun count-words-in-defun ()
14487   "@var{documentation}@dots{}"
14488   (@var{set up}@dots{}
14489      (@var{while loop}@dots{})
14490    @var{return count})
14491 @end group
14492 @end smallexample
14494 @noindent
14495 As usual, our job is to fill in the slots.
14497 First, the set up.
14499 We are presuming that this function will be called within a buffer
14500 containing function definitions.  Point will either be within a
14501 function definition or not.  For @code{count-words-in-defun} to work,
14502 point must move to the beginning of the definition, a counter must
14503 start at zero, and the counting loop must stop when point reaches the
14504 end of the definition.
14506 The @code{beginning-of-defun} function searches backwards for an
14507 opening delimiter such as a @samp{(} at the beginning of a line, and
14508 moves point to that position, or else to the limit of the search.  In
14509 practice, this means that @code{beginning-of-defun} moves point to the
14510 beginning of an enclosing or preceding function definition, or else to
14511 the beginning of the buffer.  We can use @code{beginning-of-defun} to
14512 place point where we wish to start.
14514 The @code{while} loop requires a counter to keep track of the words or
14515 symbols being counted.  A @code{let} expression can be used to create
14516 a local variable for this purpose, and bind it to an initial value of zero.
14518 The @code{end-of-defun} function works like @code{beginning-of-defun}
14519 except that it moves point to the end of the definition.
14520 @code{end-of-defun} can be used as part of an expression that
14521 determines the position of the end of the definition.
14523 The set up for @code{count-words-in-defun} takes shape rapidly: first
14524 we move point to the beginning of the definition, then we create a
14525 local variable to hold the count, and finally, we record the position
14526 of the end of the definition so the @code{while} loop will know when to stop
14527 looping.
14529 @need 1250
14530 The code looks like this:
14532 @smallexample
14533 @group
14534 (beginning-of-defun)
14535 (let ((count 0)
14536       (end (save-excursion (end-of-defun) (point))))
14537 @end group
14538 @end smallexample
14540 @noindent
14541 The code is simple.  The only slight complication is likely to concern
14542 @code{end}: it is bound to the position of the end of the definition
14543 by a @code{save-excursion} expression that returns the value of point
14544 after @code{end-of-defun} temporarily moves it to the end of the
14545 definition.
14547 The second part of the @code{count-words-in-defun}, after the set up,
14548 is the @code{while} loop.
14550 The loop must contain an expression that jumps point forward word by
14551 word and symbol by symbol, and another expression that counts the
14552 jumps.  The true-or-false-test for the @code{while} loop should test
14553 true so long as point should jump forward, and false when point is at
14554 the end of the definition.  We have already redefined the regular
14555 expression for this, so the loop is straightforward:
14557 @smallexample
14558 @group
14559 (while (and (< (point) end)
14560             (re-search-forward
14561              "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t))
14562   (setq count (1+ count)))
14563 @end group
14564 @end smallexample
14566 The third part of the function definition returns the count of words
14567 and symbols.  This part is the last expression within the body of the
14568 @code{let} expression, and can be, very simply, the local variable
14569 @code{count}, which when evaluated returns the count.
14571 @need 1250
14572 Put together, the @code{count-words-in-defun} definition looks like this:
14574 @findex count-words-in-defun
14575 @smallexample
14576 @group
14577 (defun count-words-in-defun ()
14578   "Return the number of words and symbols in a defun."
14579   (beginning-of-defun)
14580   (let ((count 0)
14581         (end (save-excursion (end-of-defun) (point))))
14582 @end group
14583 @group
14584     (while
14585         (and (< (point) end)
14586              (re-search-forward
14587               "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14588               end t))
14589       (setq count (1+ count)))
14590     count))
14591 @end group
14592 @end smallexample
14594 How to test this?  The function is not interactive, but it is easy to
14595 put a wrapper around the function to make it interactive; we can use
14596 almost the same code as for the recursive version of
14597 @code{@value{COUNT-WORDS}}:
14599 @smallexample
14600 @group
14601 ;;; @r{Interactive version.}
14602 (defun count-words-defun ()
14603   "Number of words and symbols in a function definition."
14604   (interactive)
14605   (message
14606    "Counting words and symbols in function definition ... ")
14607 @end group
14608 @group
14609   (let ((count (count-words-in-defun)))
14610     (cond
14611      ((zerop count)
14612       (message
14613        "The definition does NOT have any words or symbols."))
14614 @end group
14615 @group
14616      ((= 1 count)
14617       (message
14618        "The definition has 1 word or symbol."))
14619      (t
14620       (message
14621        "The definition has %d words or symbols." count)))))
14622 @end group
14623 @end smallexample
14625 @need 800
14626 @noindent
14627 Let's re-use @kbd{C-c =} as a convenient keybinding:
14629 @smallexample
14630 (global-set-key "\C-c=" 'count-words-defun)
14631 @end smallexample
14633 Now we can try out @code{count-words-defun}: install both
14634 @code{count-words-in-defun} and @code{count-words-defun}, and set the
14635 keybinding, and then place the cursor within the following definition:
14637 @smallexample
14638 @group
14639 (defun multiply-by-seven (number)
14640   "Multiply NUMBER by seven."
14641   (* 7 number))
14642      @result{} 10
14643 @end group
14644 @end smallexample
14646 @noindent
14647 Success!  The definition has 10 words and symbols.
14649 The next problem is to count the numbers of words and symbols in
14650 several definitions within a single file.
14652 @node Several defuns
14653 @section Count Several @code{defuns} Within a File
14655 A file such as @file{simple.el} may have a hundred or more function
14656 definitions within it.  Our long term goal is to collect statistics on
14657 many files, but as a first step, our immediate goal is to collect
14658 statistics on one file.
14660 The information will be a series of numbers, each number being the
14661 length of a function definition.  We can store the numbers in a list.
14663 We know that we will want to incorporate the information regarding one
14664 file with information about many other files; this means that the
14665 function for counting definition lengths within one file need only
14666 return the list of lengths.  It need not and should not display any
14667 messages.
14669 The word count commands contain one expression to jump point forward
14670 word by word and another expression to count the jumps.  The function
14671 to return the lengths of definitions can be designed to work the same
14672 way, with one expression to jump point forward definition by
14673 definition and another expression to construct the lengths' list.
14675 This statement of the problem makes it elementary to write the
14676 function definition.  Clearly, we will start the count at the
14677 beginning of the file, so the first command will be @code{(goto-char
14678 (point-min))}.  Next, we start the @code{while} loop; and the
14679 true-or-false test of the loop can be a regular expression search for
14680 the next function definition---so long as the search succeeds, point
14681 is moved forward and then the body of the loop is evaluated.  The body
14682 needs an expression that constructs the lengths' list.  @code{cons},
14683 the list construction command, can be used to create the list.  That
14684 is almost all there is to it.
14686 @need 800
14687 Here is what this fragment of code looks like:
14689 @smallexample
14690 @group
14691 (goto-char (point-min))
14692 (while (re-search-forward "^(defun" nil t)
14693   (setq lengths-list
14694         (cons (count-words-in-defun) lengths-list)))
14695 @end group
14696 @end smallexample
14698 What we have left out is the mechanism for finding the file that
14699 contains the function definitions.
14701 In previous examples, we either used this, the Info file, or we
14702 switched back and forth to some other buffer, such as the
14703 @file{*scratch*} buffer.
14705 Finding a file is a new process that we have not yet discussed.
14707 @node Find a File
14708 @section Find a File
14709 @cindex Find a File
14711 To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
14712 command.  This command is almost, but not quite right for the lengths
14713 problem.
14715 @need 1200
14716 Let's look at the source for @code{find-file}:
14718 @smallexample
14719 @group
14720 (defun find-file (filename)
14721   "Edit file FILENAME.
14722 Switch to a buffer visiting file FILENAME,
14723 creating one if none already exists."
14724   (interactive "FFind file: ")
14725   (switch-to-buffer (find-file-noselect filename)))
14726 @end group
14727 @end smallexample
14729 @noindent
14730 (The most recent version of the @code{find-file} function definition
14731 permits you to specify optional wildcards to visit multiple files; that
14732 makes the definition more complex and we will not discuss it here,
14733 since it is not relevant.  You can see its source using either
14734 @kbd{M-.} (@code{find-tag}) or @kbd{C-h f} (@code{describe-function}).)
14736 @ignore
14737 In Emacs 22
14738 (defun find-file (filename &optional wildcards)
14739   "Edit file FILENAME.
14740 Switch to a buffer visiting file FILENAME,
14741 creating one if none already exists.
14742 Interactively, the default if you just type RET is the current directory,
14743 but the visited file name is available through the minibuffer history:
14744 type M-n to pull it into the minibuffer.
14746 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
14747 expand wildcards (if any) and visit multiple files.  You can
14748 suppress wildcard expansion by setting `find-file-wildcards' to nil.
14750 To visit a file without any kind of conversion and without
14751 automatically choosing a major mode, use \\[find-file-literally]."
14752   (interactive (find-file-read-args "Find file: " nil))
14753   (let ((value (find-file-noselect filename nil nil wildcards)))
14754     (if (listp value)
14755         (mapcar 'switch-to-buffer (nreverse value))
14756       (switch-to-buffer value))))
14757 @end ignore
14759 The definition I am showing possesses short but complete documentation
14760 and an interactive specification that prompts you for a file name when
14761 you use the command interactively.  The body of the definition
14762 contains two functions, @code{find-file-noselect} and
14763 @code{switch-to-buffer}.
14765 According to its documentation as shown by @kbd{C-h f} (the
14766 @code{describe-function} command), the @code{find-file-noselect}
14767 function reads the named file into a buffer and returns the buffer.
14768 (Its most recent version includes an optional @var{wildcards} argument,
14769 too, as well as another to read a file literally and an other you
14770 suppress warning messages.  These optional arguments are irrelevant.)
14772 However, the @code{find-file-noselect} function does not select the
14773 buffer in which it puts the file.  Emacs does not switch its attention
14774 (or yours if you are using @code{find-file-noselect}) to the selected
14775 buffer.  That is what @code{switch-to-buffer} does: it switches the
14776 buffer to which Emacs attention is directed; and it switches the
14777 buffer displayed in the window to the new buffer.  We have discussed
14778 buffer switching elsewhere.  (@xref{Switching Buffers}.)
14780 In this histogram project, we do not need to display each file on the
14781 screen as the program determines the length of each definition within
14782 it.  Instead of employing @code{switch-to-buffer}, we can work with
14783 @code{set-buffer}, which redirects the attention of the computer
14784 program to a different buffer but does not redisplay it on the screen.
14785 So instead of calling on @code{find-file} to do the job, we must write
14786 our own expression.
14788 The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
14790 @node lengths-list-file
14791 @section @code{lengths-list-file} in Detail
14793 The core of the @code{lengths-list-file} function is a @code{while}
14794 loop containing a function to move point forward defun by defun, and
14795 a function to count the number of words and symbols in each defun.
14796 This core must be surrounded by functions that do various other tasks,
14797 including finding the file, and ensuring that point starts out at the
14798 beginning of the file.  The function definition looks like this:
14799 @findex lengths-list-file
14801 @smallexample
14802 @group
14803 (defun lengths-list-file (filename)
14804   "Return list of definitions' lengths within FILE.
14805 The returned list is a list of numbers.
14806 Each number is the number of words or
14807 symbols in one function definition."
14808 @end group
14809 @group
14810   (message "Working on `%s' ... " filename)
14811   (save-excursion
14812     (let ((buffer (find-file-noselect filename))
14813           (lengths-list))
14814       (set-buffer buffer)
14815       (setq buffer-read-only t)
14816       (widen)
14817       (goto-char (point-min))
14818       (while (re-search-forward "^(defun" nil t)
14819         (setq lengths-list
14820               (cons (count-words-in-defun) lengths-list)))
14821       (kill-buffer buffer)
14822       lengths-list)))
14823 @end group
14824 @end smallexample
14826 @noindent
14827 The function is passed one argument, the name of the file on which it
14828 will work.  It has four lines of documentation, but no interactive
14829 specification.  Since people worry that a computer is broken if they
14830 don't see anything going on, the first line of the body is a
14831 message.
14833 The next line contains a @code{save-excursion} that returns Emacs's
14834 attention to the current buffer when the function completes.  This is
14835 useful in case you embed this function in another function that
14836 presumes point is restored to the original buffer.
14838 In the varlist of the @code{let} expression, Emacs finds the file and
14839 binds the local variable @code{buffer} to the buffer containing the
14840 file.  At the same time, Emacs creates @code{lengths-list} as a local
14841 variable.
14843 Next, Emacs switches its attention to the buffer.
14845 In the following line, Emacs makes the buffer read-only.  Ideally,
14846 this line is not necessary.  None of the functions for counting words
14847 and symbols in a function definition should change the buffer.
14848 Besides, the buffer is not going to be saved, even if it were changed.
14849 This line is entirely the consequence of great, perhaps excessive,
14850 caution.  The reason for the caution is that this function and those
14851 it calls work on the sources for Emacs and it is inconvenient if they
14852 are inadvertently modified.  It goes without saying that I did not
14853 realize a need for this line until an experiment went awry and started
14854 to modify my Emacs source files @dots{}
14856 Next comes a call to widen the buffer if it is narrowed.  This
14857 function is usually not needed---Emacs creates a fresh buffer if none
14858 already exists; but if a buffer visiting the file already exists Emacs
14859 returns that one.  In this case, the buffer may be narrowed and must
14860 be widened.  If we wanted to be fully user-friendly, we would
14861 arrange to save the restriction and the location of point, but we
14862 won't.
14864 The @code{(goto-char (point-min))} expression moves point to the
14865 beginning of the buffer.
14867 Then comes a @code{while} loop in which the work of the function is
14868 carried out.  In the loop, Emacs determines the length of each
14869 definition and constructs a lengths' list containing the information.
14871 Emacs kills the buffer after working through it.  This is to save
14872 space inside of Emacs.  My version of GNU Emacs 19 contained over 300
14873 source files of interest; GNU Emacs 22 contains over a thousand source
14874 files.  Another function will apply @code{lengths-list-file} to each
14875 of the files.
14877 Finally, the last expression within the @code{let} expression is the
14878 @code{lengths-list} variable; its value is returned as the value of
14879 the whole function.
14881 You can try this function by installing it in the usual fashion.  Then
14882 place your cursor after the following expression and type @kbd{C-x
14883 C-e} (@code{eval-last-sexp}).
14885 @c !!! 22.1.1 lisp sources location here
14886 @smallexample
14887 (lengths-list-file
14888  "/usr/local/share/emacs/22.1/lisp/emacs-lisp/debug.el")
14889 @end smallexample
14891 @noindent
14892 You may need to change the pathname of the file; the one here is for
14893 GNU Emacs version 22.1.  To change the expression, copy it to
14894 the @file{*scratch*} buffer and edit it.
14896 @need 1200
14897 @noindent
14898 Also, to see the full length of the list, rather than a truncated
14899 version, you may have to evaluate the following:
14900 @c We do not want to insert, so do not mention the zero prefix argument.
14902 @smallexample
14903 (custom-set-variables '(eval-expression-print-length nil))
14904 @end smallexample
14906 @noindent
14907 (@xref{defcustom, , Specifying Variables using @code{defcustom}}.
14908 Then evaluate the @code{lengths-list-file} expression.)
14910 @need 1200
14911 The lengths' list for @file{debug.el} takes less than a second to
14912 produce and looks like this in GNU Emacs 22:
14914 @smallexample
14915 (83 113 105 144 289 22 30 97 48 89 25 52 52 88 28 29 77 49 43 290 232 587)
14916 @end smallexample
14918 @need 1500
14919 (Using my old machine, the version 19 lengths' list for @file{debug.el}
14920 took seven seconds to produce and looked like this:
14922 @smallexample
14923 (75 41 80 62 20 45 44 68 45 12 34 235)
14924 @end smallexample
14926 @noindent
14927 The newer version of @file{debug.el} contains more defuns than the
14928 earlier one; and my new machine is much faster than the old one.)
14930 Note that the length of the last definition in the file is first in
14931 the list.
14933 @node Several files
14934 @section Count Words in @code{defuns} in Different Files
14936 In the previous section, we created a function that returns a list of
14937 the lengths of each definition in a file.  Now, we want to define a
14938 function to return a master list of the lengths of the definitions in
14939 a list of files.
14941 Working on each of a list of files is a repetitious act, so we can use
14942 either a @code{while} loop or recursion.
14944 @menu
14945 * lengths-list-many-files::     Return a list of the lengths of defuns.
14946 * append::                      Attach one list to another.
14947 @end menu
14949 @ifnottex
14950 @node lengths-list-many-files
14951 @unnumberedsubsec Determine the lengths of @code{defuns}
14952 @end ifnottex
14954 The design using a @code{while} loop is routine.  The argument passed
14955 to the function is a list of files.  As we saw earlier (@pxref{Loop
14956 Example}), you can write a @code{while} loop so that the body of the
14957 loop is evaluated if such a list contains elements, but to exit the
14958 loop if the list is empty.  For this design to work, the body of the
14959 loop must contain an expression that shortens the list each time the
14960 body is evaluated, so that eventually the list is empty.  The usual
14961 technique is to set the value of the list to the value of the @sc{cdr}
14962 of the list each time the body is evaluated.
14964 @need 800
14965 The template looks like this:
14967 @smallexample
14968 @group
14969 (while @var{test-whether-list-is-empty}
14970   @var{body}@dots{}
14971   @var{set-list-to-cdr-of-list})
14972 @end group
14973 @end smallexample
14975 Also, we remember that a @code{while} loop returns @code{nil} (the
14976 result of evaluating the true-or-false-test), not the result of any
14977 evaluation within its body.  (The evaluations within the body of the
14978 loop are done for their side effects.)  However, the expression that
14979 sets the lengths' list is part of the body---and that is the value
14980 that we want returned by the function as a whole.  To do this, we
14981 enclose the @code{while} loop within a @code{let} expression, and
14982 arrange that the last element of the @code{let} expression contains
14983 the value of the lengths' list.  (@xref{Incrementing Example, , Loop
14984 Example with an Incrementing Counter}.)
14986 @findex lengths-list-many-files
14987 @need 1250
14988 These considerations lead us directly to the function itself:
14990 @smallexample
14991 @group
14992 ;;; @r{Use @code{while} loop.}
14993 (defun lengths-list-many-files (list-of-files)
14994   "Return list of lengths of defuns in LIST-OF-FILES."
14995 @end group
14996 @group
14997   (let (lengths-list)
14999 ;;; @r{true-or-false-test}
15000     (while list-of-files
15001       (setq lengths-list
15002             (append
15003              lengths-list
15005 ;;; @r{Generate a lengths' list.}
15006              (lengths-list-file
15007               (expand-file-name (car list-of-files)))))
15008 @end group
15010 @group
15011 ;;; @r{Make files' list shorter.}
15012       (setq list-of-files (cdr list-of-files)))
15014 ;;; @r{Return final value of lengths' list.}
15015     lengths-list))
15016 @end group
15017 @end smallexample
15019 @code{expand-file-name} is a built-in function that converts a file
15020 name to the absolute, long, path name form.  The function employs the
15021 name of the directory in which the function is called.
15023 @c !!! 22.1.1 lisp sources location here
15024 @need 1500
15025 Thus, if @code{expand-file-name} is called on @code{debug.el} when
15026 Emacs is visiting the
15027 @file{/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/} directory,
15029 @smallexample
15030 debug.el
15031 @end smallexample
15033 @need 800
15034 @noindent
15035 becomes
15037 @c !!! 22.1.1 lisp sources location here
15038 @smallexample
15039 /usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el
15040 @end smallexample
15042 The only other new element of this function definition is the as yet
15043 unstudied function @code{append}, which merits a short section for
15044 itself.
15046 @node append
15047 @subsection The @code{append} Function
15049 @need 800
15050 The @code{append} function attaches one list to another.  Thus,
15052 @smallexample
15053 (append '(1 2 3 4) '(5 6 7 8))
15054 @end smallexample
15056 @need 800
15057 @noindent
15058 produces the list
15060 @smallexample
15061 (1 2 3 4 5 6 7 8)
15062 @end smallexample
15064 This is exactly how we want to attach two lengths' lists produced by
15065 @code{lengths-list-file} to each other.  The results contrast with
15066 @code{cons},
15068 @smallexample
15069 (cons '(1 2 3 4) '(5 6 7 8))
15070 @end smallexample
15072 @need 1250
15073 @noindent
15074 which constructs a new list in which the first argument to @code{cons}
15075 becomes the first element of the new list:
15077 @smallexample
15078 ((1 2 3 4) 5 6 7 8)
15079 @end smallexample
15081 @node Several files recursively
15082 @section Recursively Count Words in Different Files
15084 Besides a @code{while} loop, you can work on each of a list of files
15085 with recursion.  A recursive version of @code{lengths-list-many-files}
15086 is short and simple.
15088 The recursive function has the usual parts: the do-again-test, the
15089 next-step-expression, and the recursive call.  The do-again-test
15090 determines whether the function should call itself again, which it
15091 will do if the @code{list-of-files} contains any remaining elements;
15092 the next-step-expression resets the @code{list-of-files} to the
15093 @sc{cdr} of itself, so eventually the list will be empty; and the
15094 recursive call calls itself on the shorter list.  The complete
15095 function is shorter than this description!
15096 @findex recursive-lengths-list-many-files
15098 @smallexample
15099 @group
15100 (defun recursive-lengths-list-many-files (list-of-files)
15101   "Return list of lengths of each defun in LIST-OF-FILES."
15102   (if list-of-files                     ; @r{do-again-test}
15103       (append
15104        (lengths-list-file
15105         (expand-file-name (car list-of-files)))
15106        (recursive-lengths-list-many-files
15107         (cdr list-of-files)))))
15108 @end group
15109 @end smallexample
15111 @noindent
15112 In a sentence, the function returns the lengths' list for the first of
15113 the @code{list-of-files} appended to the result of calling itself on
15114 the rest of the @code{list-of-files}.
15116 Here is a test of @code{recursive-lengths-list-many-files}, along with
15117 the results of running @code{lengths-list-file} on each of the files
15118 individually.
15120 Install @code{recursive-lengths-list-many-files} and
15121 @code{lengths-list-file}, if necessary, and then evaluate the
15122 following expressions.  You may need to change the files' pathnames;
15123 those here work when this Info file and the Emacs sources are located
15124 in their customary places.  To change the expressions, copy them to
15125 the @file{*scratch*} buffer, edit them, and then evaluate them.
15127 The results are shown after the @samp{@result{}}.  (These results are
15128 for files from Emacs version 22.1.1; files from other versions of
15129 Emacs may produce different results.)
15131 @c !!! 22.1.1 lisp sources location here
15132 @smallexample
15133 @group
15134 (cd "/usr/local/share/emacs/22.1.1/")
15136 (lengths-list-file "./lisp/macros.el")
15137      @result{} (283 263 480 90)
15138 @end group
15140 @group
15141 (lengths-list-file "./lisp/mail/mailalias.el")
15142      @result{} (38 32 29 95 178 180 321 218 324)
15143 @end group
15145 @group
15146 (lengths-list-file "./lisp/makesum.el")
15147      @result{} (85 181)
15148 @end group
15150 @group
15151   (recursive-lengths-list-many-files
15152    '("./lisp/macros.el"
15153      "./lisp/mail/mailalias.el"
15154      "./lisp/makesum.el"))
15155        @result{} (283 263 480 90 38 32 29 95 178 180 321 218 324 85 181)
15156 @end group
15157 @end smallexample
15159 The @code{recursive-lengths-list-many-files} function produces the
15160 output we want.
15162 The next step is to prepare the data in the list for display in a graph.
15164 @node Prepare the data
15165 @section Prepare the Data for Display in a Graph
15167 The @code{recursive-lengths-list-many-files} function returns a list
15168 of numbers.  Each number records the length of a function definition.
15169 What we need to do now is transform this data into a list of numbers
15170 suitable for generating a graph.  The new list will tell how many
15171 functions definitions contain less than 10 words and
15172 symbols, how many contain between 10 and 19 words and symbols, how
15173 many contain between 20 and 29 words and symbols, and so on.
15175 In brief, we need to go through the lengths' list produced by the
15176 @code{recursive-lengths-list-many-files} function and count the number
15177 of defuns within each range of lengths, and produce a list of those
15178 numbers.
15180 @menu
15181 * Data for Display in Detail::
15182 * Sorting::                     Sorting lists.
15183 * Files List::                  Making a list of files.
15184 * Counting function definitions::
15185 @end menu
15187 @ifnottex
15188 @node Data for Display in Detail
15189 @unnumberedsubsec The Data for Display in Detail
15190 @end ifnottex
15192 Based on what we have done before, we can readily foresee that it
15193 should not be too hard to write a function that @sc{cdr}s down the
15194 lengths' list, looks at each element, determines which length range it
15195 is in, and increments a counter for that range.
15197 However, before beginning to write such a function, we should consider
15198 the advantages of sorting the lengths' list first, so the numbers are
15199 ordered from smallest to largest.  First, sorting will make it easier
15200 to count the numbers in each range, since two adjacent numbers will
15201 either be in the same length range or in adjacent ranges.  Second, by
15202 inspecting a sorted list, we can discover the highest and lowest
15203 number, and thereby determine the largest and smallest length range
15204 that we will need.
15206 @node Sorting
15207 @subsection Sorting Lists
15208 @findex sort
15210 Emacs contains a function to sort lists, called (as you might guess)
15211 @code{sort}.  The @code{sort} function takes two arguments, the list
15212 to be sorted, and a predicate that determines whether the first of
15213 two list elements is less than the second.
15215 As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
15216 Type Object as an Argument}), a predicate is a function that
15217 determines whether some property is true or false.  The @code{sort}
15218 function will reorder a list according to whatever property the
15219 predicate uses; this means that @code{sort} can be used to sort
15220 non-numeric lists by non-numeric criteria---it can, for example,
15221 alphabetize a list.
15223 @need 1250
15224 The @code{<} function is used when sorting a numeric list.  For example,
15226 @smallexample
15227 (sort '(4 8 21 17 33 7 21 7) '<)
15228 @end smallexample
15230 @need 800
15231 @noindent
15232 produces this:
15234 @smallexample
15235 (4 7 7 8 17 21 21 33)
15236 @end smallexample
15238 @noindent
15239 (Note that in this example, both the arguments are quoted so that the
15240 symbols are not evaluated before being passed to @code{sort} as
15241 arguments.)
15243 Sorting the list returned by the
15244 @code{recursive-lengths-list-many-files} function is straightforward;
15245 it uses the @code{<} function:
15247 @ignore
15248 2006 Oct 29
15249 In GNU Emacs 22,  eval
15250 (progn
15251   (cd "/usr/local/share/emacs/22.0.50/")
15252   (sort
15253    (recursive-lengths-list-many-files
15254     '("./lisp/macros.el"
15255       "./lisp/mail/mailalias.el"
15256       "./lisp/makesum.el"))
15257    '<))
15259 @end ignore
15261 @smallexample
15262 @group
15263 (sort
15264  (recursive-lengths-list-many-files
15265   '("./lisp/macros.el"
15266     "./lisp/mailalias.el"
15267     "./lisp/makesum.el"))
15268  '<)
15269 @end group
15270 @end smallexample
15272 @need 800
15273 @noindent
15274 which produces:
15276 @smallexample
15277 (29 32 38 85 90 95 178 180 181 218 263 283 321 324 480)
15278 @end smallexample
15280 @noindent
15281 (Note that in this example, the first argument to @code{sort} is not
15282 quoted, since the expression must be evaluated so as to produce the
15283 list that is passed to @code{sort}.)
15285 @node Files List
15286 @subsection Making a List of Files
15288 The @code{recursive-lengths-list-many-files} function requires a list
15289 of files as its argument.  For our test examples, we constructed such
15290 a list by hand; but the Emacs Lisp source directory is too large for
15291 us to do for that.  Instead, we will write a function to do the job
15292 for us.  In this function, we will use both a @code{while} loop and a
15293 recursive call.
15295 @findex directory-files
15296 We did not have to write a function like this for older versions of
15297 GNU Emacs, since they placed all the @samp{.el} files in one
15298 directory.  Instead, we were able to use the @code{directory-files}
15299 function, which lists the names of files that match a specified
15300 pattern within a single directory.
15302 However, recent versions of Emacs place Emacs Lisp files in
15303 sub-directories of the top level @file{lisp} directory.  This
15304 re-arrangement eases navigation.  For example, all the mail related
15305 files are in a @file{lisp} sub-directory called @file{mail}.  But at
15306 the same time, this arrangement forces us to create a file listing
15307 function that descends into the sub-directories.
15309 @findex files-in-below-directory
15310 We can create this function, called @code{files-in-below-directory},
15311 using familiar functions such as @code{car}, @code{nthcdr}, and
15312 @code{substring} in conjunction with an existing function called
15313 @code{directory-files-and-attributes}.  This latter function not only
15314 lists all the filenames in a directory, including the names
15315 of sub-directories, but also their attributes.
15317 To restate our goal: to create a function that will enable us
15318 to feed filenames to @code{recursive-lengths-list-many-files}
15319 as a list that looks like this (but with more elements):
15321 @smallexample
15322 @group
15323 ("./lisp/macros.el"
15324  "./lisp/mail/rmail.el"
15325  "./lisp/makesum.el")
15326 @end group
15327 @end smallexample
15329 The @code{directory-files-and-attributes} function returns a list of
15330 lists.  Each of the lists within the main list consists of 13
15331 elements.  The first element is a string that contains the name of the
15332 file---which, in GNU/Linux, may be a @dfn{directory file}, that is to
15333 say, a file with the special attributes of a directory.  The second
15334 element of the list is @code{t} for a directory, a string
15335 for symbolic link (the string is the name linked to), or @code{nil}.
15337 For example, the first @samp{.el} file in the @file{lisp/} directory
15338 is @file{abbrev.el}.  Its name is
15339 @file{/usr/local/share/emacs/22.1.1/lisp/abbrev.el} and it is not a
15340 directory or a symbolic link.
15342 @need 1000
15343 This is how @code{directory-files-and-attributes} lists that file and
15344 its attributes:
15346 @smallexample
15347 @group
15348 ("abbrev.el"
15351 1000
15353 @end group
15354 @group
15355 (20615 27034 579989 697000)
15356 (17905 55681 0 0)
15357 (20615 26327 734791 805000)
15358 13188
15359 "-rw-r--r--"
15360 @end group
15361 @group
15363 2971624
15364 773)
15365 @end group
15366 @end smallexample
15368 @need 1200
15369 On the other hand, @file{mail/} is a directory within the @file{lisp/}
15370 directory.  The beginning of its listing looks like this:
15372 @smallexample
15373 @group
15374 ("mail"
15376 @dots{}
15378 @end group
15379 @end smallexample
15381 (To learn about the different attributes, look at the documentation of
15382 @code{file-attributes}.  Bear in mind that the @code{file-attributes}
15383 function does not list the filename, so its first element is
15384 @code{directory-files-and-attributes}'s second element.)
15386 We will want our new function, @code{files-in-below-directory}, to
15387 list the @samp{.el} files in the directory it is told to check, and in
15388 any directories below that directory.
15390 This gives us a hint on how to construct
15391 @code{files-in-below-directory}:  within a directory, the function
15392 should add @samp{.el} filenames to a list; and if, within a directory,
15393 the function comes upon a sub-directory, it should go into that
15394 sub-directory and repeat its actions.
15396 However, we should note that every directory contains a name that
15397 refers to itself, called @file{.} (``dot''), and a name that refers to
15398 its parent directory, called @file{..} (``dot dot'').  (In
15399 @file{/}, the root directory, @file{..} refers to itself, since
15400 @file{/} has no parent.)  Clearly, we do not want our
15401 @code{files-in-below-directory} function to enter those directories,
15402 since they always lead us, directly or indirectly, to the current
15403 directory.
15405 Consequently, our @code{files-in-below-directory} function must do
15406 several tasks:
15408 @itemize @bullet
15409 @item
15410 Check to see whether it is looking at a filename that ends in
15411 @samp{.el}; and if so, add its name to a list.
15413 @item
15414 Check to see whether it is looking at a filename that is the name of a
15415 directory; and if so,
15417 @itemize @minus
15418 @item
15419 Check to see whether it is looking at @file{.}  or @file{..}; and if
15420 so skip it.
15422 @item
15423 Or else, go into that directory and repeat the process.
15424 @end itemize
15425 @end itemize
15427 Let's write a function definition to do these tasks.  We will use a
15428 @code{while} loop to move from one filename to another within a
15429 directory, checking what needs to be done; and we will use a recursive
15430 call to repeat the actions on each sub-directory.  The recursive
15431 pattern is Accumulate
15432 (@pxref{Accumulate}),
15433 using @code{append} as the combiner.
15435 @ignore
15436 (directory-files "/usr/local/src/emacs/lisp/" t "\\.el$")
15437 (shell-command "find /usr/local/src/emacs/lisp/ -name '*.el'")
15439 (directory-files "/usr/local/share/emacs/22.1.1/lisp/" t "\\.el$")
15440 (shell-command "find /usr/local/share/emacs/22.1.1/lisp/ -name '*.el'")
15441 @end ignore
15443 @c  /usr/local/share/emacs/22.1.1/lisp/
15445 @need 800
15446 Here is the function:
15448 @smallexample
15449 @group
15450 (defun files-in-below-directory (directory)
15451   "List the .el files in DIRECTORY and in its sub-directories."
15452   ;; Although the function will be used non-interactively,
15453   ;; it will be easier to test if we make it interactive.
15454   ;; The directory will have a name such as
15455   ;;  "/usr/local/share/emacs/22.1.1/lisp/"
15456   (interactive "DDirectory name: ")
15457 @end group
15458 @group
15459   (let (el-files-list
15460         (current-directory-list
15461          (directory-files-and-attributes directory t)))
15462     ;; while we are in the current directory
15463     (while current-directory-list
15464 @end group
15465 @group
15466       (cond
15467        ;; check to see whether filename ends in '.el'
15468        ;; and if so, add its name to a list.
15469        ((equal ".el" (substring (car (car current-directory-list)) -3))
15470         (setq el-files-list
15471               (cons (car (car current-directory-list)) el-files-list)))
15472 @end group
15473 @group
15474        ;; check whether filename is that of a directory
15475        ((eq t (car (cdr (car current-directory-list))))
15476         ;; decide whether to skip or recurse
15477         (if
15478             (equal "."
15479                    (substring (car (car current-directory-list)) -1))
15480             ;; then do nothing since filename is that of
15481             ;;   current directory or parent, "." or ".."
15482             ()
15483 @end group
15484 @group
15485           ;; else descend into the directory and repeat the process
15486           (setq el-files-list
15487                 (append
15488                  (files-in-below-directory
15489                   (car (car current-directory-list)))
15490                  el-files-list)))))
15491       ;; move to the next filename in the list; this also
15492       ;; shortens the list so the while loop eventually comes to an end
15493       (setq current-directory-list (cdr current-directory-list)))
15494     ;; return the filenames
15495     el-files-list))
15496 @end group
15497 @end smallexample
15499 @c (files-in-below-directory "/usr/local/src/emacs/lisp/")
15500 @c (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15502 The @code{files-in-below-directory} @code{directory-files} function
15503 takes one argument, the name of a directory.
15505 @need 1250
15506 Thus, on my system,
15508 @c (length (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15510 @c !!! 22.1.1 lisp sources location here
15511 @smallexample
15512 @group
15513 (length
15514  (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/"))
15515 @end group
15516 @end smallexample
15518 @noindent
15519 tells me that in and below my Lisp sources directory are 1031
15520 @samp{.el} files.
15522 @code{files-in-below-directory} returns a list in reverse alphabetical
15523 order.  An expression to sort the list in alphabetical order looks
15524 like this:
15526 @smallexample
15527 @group
15528 (sort
15529  (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15530  'string-lessp)
15531 @end group
15532 @end smallexample
15534 @ignore
15535 (defun test ()
15536   "Test how long it takes to find lengths of all sorted elisp defuns."
15537   (insert "\n" (current-time-string) "\n")
15538   (sit-for 0)
15539   (sort
15540    (recursive-lengths-list-many-files
15541     (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15542    '<)
15543   (insert (format "%s" (current-time-string))))
15544 @end ignore
15546 @node Counting function definitions
15547 @subsection Counting function definitions
15549 Our immediate goal is to generate a list that tells us how many
15550 function definitions contain fewer than 10 words and symbols, how many
15551 contain between 10 and 19 words and symbols, how many contain between
15552 20 and 29 words and symbols, and so on.
15554 With a sorted list of numbers, this is easy: count how many elements
15555 of the list are smaller than 10, then, after moving past the numbers
15556 just counted, count how many are smaller than 20, then, after moving
15557 past the numbers just counted, count how many are smaller than 30, and
15558 so on.  Each of the numbers, 10, 20, 30, 40, and the like, is one
15559 larger than the top of that range.  We can call the list of such
15560 numbers the @code{top-of-ranges} list.
15562 @need 1200
15563 If we wished, we could generate this list automatically, but it is
15564 simpler to write a list manually.  Here it is:
15565 @vindex top-of-ranges
15567 @smallexample
15568 @group
15569 (defvar top-of-ranges
15570  '(10  20  30  40  50
15571    60  70  80  90 100
15572   110 120 130 140 150
15573   160 170 180 190 200
15574   210 220 230 240 250
15575   260 270 280 290 300)
15576  "List specifying ranges for `defuns-per-range'.")
15577 @end group
15578 @end smallexample
15580 To change the ranges, we edit this list.
15582 Next, we need to write the function that creates the list of the
15583 number of definitions within each range.  Clearly, this function must
15584 take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15585 as arguments.
15587 The @code{defuns-per-range} function must do two things again and
15588 again: it must count the number of definitions within a range
15589 specified by the current top-of-range value; and it must shift to the
15590 next higher value in the @code{top-of-ranges} list after counting the
15591 number of definitions in the current range.  Since each of these
15592 actions is repetitive, we can use @code{while} loops for the job.
15593 One loop counts the number of definitions in the range defined by the
15594 current top-of-range value, and the other loop selects each of the
15595 top-of-range values in turn.
15597 Several entries of the @code{sorted-lengths} list are counted for each
15598 range; this means that the loop for the @code{sorted-lengths} list
15599 will be inside the loop for the @code{top-of-ranges} list, like a
15600 small gear inside a big gear.
15602 The inner loop counts the number of definitions within the range.  It
15603 is a simple counting loop of the type we have seen before.
15604 (@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15605 The true-or-false test of the loop tests whether the value from the
15606 @code{sorted-lengths} list is smaller than the current value of the
15607 top of the range.  If it is, the function increments the counter and
15608 tests the next value from the @code{sorted-lengths} list.
15610 @need 1250
15611 The inner loop looks like this:
15613 @smallexample
15614 @group
15615 (while @var{length-element-smaller-than-top-of-range}
15616   (setq number-within-range (1+ number-within-range))
15617   (setq sorted-lengths (cdr sorted-lengths)))
15618 @end group
15619 @end smallexample
15621 The outer loop must start with the lowest value of the
15622 @code{top-of-ranges} list, and then be set to each of the succeeding
15623 higher values in turn.  This can be done with a loop like this:
15625 @smallexample
15626 @group
15627 (while top-of-ranges
15628   @var{body-of-loop}@dots{}
15629   (setq top-of-ranges (cdr top-of-ranges)))
15630 @end group
15631 @end smallexample
15633 @need 1200
15634 Put together, the two loops look like this:
15636 @smallexample
15637 @group
15638 (while top-of-ranges
15640   ;; @r{Count the number of elements within the current range.}
15641   (while @var{length-element-smaller-than-top-of-range}
15642     (setq number-within-range (1+ number-within-range))
15643     (setq sorted-lengths (cdr sorted-lengths)))
15645   ;; @r{Move to next range.}
15646   (setq top-of-ranges (cdr top-of-ranges)))
15647 @end group
15648 @end smallexample
15650 In addition, in each circuit of the outer loop, Emacs should record
15651 the number of definitions within that range (the value of
15652 @code{number-within-range}) in a list.  We can use @code{cons} for
15653 this purpose.  (@xref{cons, , @code{cons}}.)
15655 The @code{cons} function works fine, except that the list it
15656 constructs will contain the number of definitions for the highest
15657 range at its beginning and the number of definitions for the lowest
15658 range at its end.  This is because @code{cons} attaches new elements
15659 of the list to the beginning of the list, and since the two loops are
15660 working their way through the lengths' list from the lower end first,
15661 the @code{defuns-per-range-list} will end up largest number first.
15662 But we will want to print our graph with smallest values first and the
15663 larger later.  The solution is to reverse the order of the
15664 @code{defuns-per-range-list}.  We can do this using the
15665 @code{nreverse} function, which reverses the order of a list.
15666 @findex nreverse
15668 @need 800
15669 For example,
15671 @smallexample
15672 (nreverse '(1 2 3 4))
15673 @end smallexample
15675 @need 800
15676 @noindent
15677 produces:
15679 @smallexample
15680 (4 3 2 1)
15681 @end smallexample
15683 Note that the @code{nreverse} function is destructive---that is,
15684 it changes the list to which it is applied; this contrasts with the
15685 @code{car} and @code{cdr} functions, which are non-destructive.  In
15686 this case, we do not want the original @code{defuns-per-range-list},
15687 so it does not matter that it is destroyed.  (The @code{reverse}
15688 function provides a reversed copy of a list, leaving the original list
15689 as is.)
15690 @findex reverse
15692 @need 1250
15693 Put all together, the @code{defuns-per-range} looks like this:
15695 @smallexample
15696 @group
15697 (defun defuns-per-range (sorted-lengths top-of-ranges)
15698   "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
15699   (let ((top-of-range (car top-of-ranges))
15700         (number-within-range 0)
15701         defuns-per-range-list)
15702 @end group
15704 @group
15705     ;; @r{Outer loop.}
15706     (while top-of-ranges
15707 @end group
15709 @group
15710       ;; @r{Inner loop.}
15711       (while (and
15712               ;; @r{Need number for numeric test.}
15713               (car sorted-lengths)
15714               (< (car sorted-lengths) top-of-range))
15715 @end group
15717 @group
15718         ;; @r{Count number of definitions within current range.}
15719         (setq number-within-range (1+ number-within-range))
15720         (setq sorted-lengths (cdr sorted-lengths)))
15722       ;; @r{Exit inner loop but remain within outer loop.}
15723 @end group
15725 @group
15726       (setq defuns-per-range-list
15727             (cons number-within-range defuns-per-range-list))
15728       (setq number-within-range 0)      ; @r{Reset count to zero.}
15729 @end group
15731 @group
15732       ;; @r{Move to next range.}
15733       (setq top-of-ranges (cdr top-of-ranges))
15734       ;; @r{Specify next top of range value.}
15735       (setq top-of-range (car top-of-ranges)))
15736 @end group
15738 @group
15739     ;; @r{Exit outer loop and count the number of defuns larger than}
15740     ;; @r{  the largest top-of-range value.}
15741     (setq defuns-per-range-list
15742           (cons
15743            (length sorted-lengths)
15744            defuns-per-range-list))
15745 @end group
15747 @group
15748     ;; @r{Return a list of the number of definitions within each range,}
15749     ;; @r{  smallest to largest.}
15750     (nreverse defuns-per-range-list)))
15751 @end group
15752 @end smallexample
15754 @need 1200
15755 @noindent
15756 The function is straightforward except for one subtle feature.  The
15757 true-or-false test of the inner loop looks like this:
15759 @smallexample
15760 @group
15761 (and (car sorted-lengths)
15762      (< (car sorted-lengths) top-of-range))
15763 @end group
15764 @end smallexample
15766 @need 800
15767 @noindent
15768 instead of like this:
15770 @smallexample
15771 (< (car sorted-lengths) top-of-range)
15772 @end smallexample
15774 The purpose of the test is to determine whether the first item in the
15775 @code{sorted-lengths} list is less than the value of the top of the
15776 range.
15778 The simple version of the test works fine unless the
15779 @code{sorted-lengths} list has a @code{nil} value.  In that case, the
15780 @code{(car sorted-lengths)} expression function returns
15781 @code{nil}.  The @code{<} function cannot compare a number to
15782 @code{nil}, which is an empty list, so Emacs signals an error and
15783 stops the function from attempting to continue to execute.
15785 The @code{sorted-lengths} list always becomes @code{nil} when the
15786 counter reaches the end of the list.  This means that any attempt to
15787 use the @code{defuns-per-range} function with the simple version of
15788 the test will fail.
15790 We solve the problem by using the @code{(car sorted-lengths)}
15791 expression in conjunction with the @code{and} expression.  The
15792 @code{(car sorted-lengths)} expression returns a non-@code{nil}
15793 value so long as the list has at least one number within it, but
15794 returns @code{nil} if the list is empty.  The @code{and} expression
15795 first evaluates the @code{(car sorted-lengths)} expression, and
15796 if it is @code{nil}, returns false @emph{without} evaluating the
15797 @code{<} expression.  But if the @code{(car sorted-lengths)}
15798 expression returns a non-@code{nil} value, the @code{and} expression
15799 evaluates the @code{<} expression, and returns that value as the value
15800 of the @code{and} expression.
15802 @c colon in printed section title causes problem in Info cross reference
15803 This way, we avoid an error.
15804 @iftex
15805 @noindent
15806 (For information about @code{and}, see
15807 @ref{kill-new function, , The @code{kill-new} function}.)
15808 @end iftex
15809 @ifinfo
15810 @noindent
15811 (@xref{kill-new function, , The @code{kill-new} function}, for
15812 information about @code{and}.)
15813 @end ifinfo
15815 Here is a short test of the @code{defuns-per-range} function.  First,
15816 evaluate the expression that binds (a shortened)
15817 @code{top-of-ranges} list to the list of values, then evaluate the
15818 expression for binding the @code{sorted-lengths} list, and then
15819 evaluate the @code{defuns-per-range} function.
15821 @smallexample
15822 @group
15823 ;; @r{(Shorter list than we will use later.)}
15824 (setq top-of-ranges
15825  '(110 120 130 140 150
15826    160 170 180 190 200))
15828 (setq sorted-lengths
15829       '(85 86 110 116 122 129 154 176 179 200 265 300 300))
15831 (defuns-per-range sorted-lengths top-of-ranges)
15832 @end group
15833 @end smallexample
15835 @need 800
15836 @noindent
15837 The list returned looks like this:
15839 @smallexample
15840 (2 2 2 0 0 1 0 2 0 0 4)
15841 @end smallexample
15843 @noindent
15844 Indeed, there are two elements of the @code{sorted-lengths} list
15845 smaller than 110, two elements between 110 and 119, two elements
15846 between 120 and 129, and so on.  There are four elements with a value
15847 of 200 or larger.
15849 @c The next step is to turn this numbers' list into a graph.
15850 @node Readying a Graph
15851 @chapter Readying a Graph
15852 @cindex Readying a graph
15853 @cindex Graph prototype
15854 @cindex Prototype graph
15855 @cindex Body of graph
15857 Our goal is to construct a graph showing the numbers of function
15858 definitions of various lengths in the Emacs lisp sources.
15860 As a practical matter, if you were creating a graph, you would
15861 probably use a program such as @code{gnuplot} to do the job.
15862 (@code{gnuplot} is nicely integrated into GNU Emacs.)  In this case,
15863 however, we create one from scratch, and in the process we will
15864 re-acquaint ourselves with some of what we learned before and learn
15865 more.
15867 In this chapter, we will first write a simple graph printing function.
15868 This first definition will be a @dfn{prototype}, a rapidly written
15869 function that enables us to reconnoiter this unknown graph-making
15870 territory.  We will discover dragons, or find that they are myth.
15871 After scouting the terrain, we will feel more confident and enhance
15872 the function to label the axes automatically.
15874 @menu
15875 * Columns of a graph::
15876 * graph-body-print::            How to print the body of a graph.
15877 * recursive-graph-body-print::
15878 * Printed Axes::
15879 * Line Graph Exercise::
15880 @end menu
15882 @ifnottex
15883 @node Columns of a graph
15884 @unnumberedsec Printing the Columns of a Graph
15885 @end ifnottex
15887 Since Emacs is designed to be flexible and work with all kinds of
15888 terminals, including character-only terminals, the graph will need to
15889 be made from one of the typewriter symbols.  An asterisk will do; as
15890 we enhance the graph-printing function, we can make the choice of
15891 symbol a user option.
15893 We can call this function @code{graph-body-print}; it will take a
15894 @code{numbers-list} as its only argument.  At this stage, we will not
15895 label the graph, but only print its body.
15897 The @code{graph-body-print} function inserts a vertical column of
15898 asterisks for each element in the @code{numbers-list}.  The height of
15899 each line is determined by the value of that element of the
15900 @code{numbers-list}.
15902 Inserting columns is a repetitive act; that means that this function can
15903 be written either with a @code{while} loop or recursively.
15905 Our first challenge is to discover how to print a column of asterisks.
15906 Usually, in Emacs, we print characters onto a screen horizontally,
15907 line by line, by typing.  We have two routes we can follow: write our
15908 own column-insertion function or discover whether one exists in Emacs.
15910 To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
15911 command.  This command is like the @kbd{C-h a} (@code{command-apropos})
15912 command, except that the latter finds only those functions that are
15913 commands.  The @kbd{M-x apropos} command lists all symbols that match
15914 a regular expression, including functions that are not interactive.
15915 @findex apropos
15917 What we want to look for is some command that prints or inserts
15918 columns.  Very likely, the name of the function will contain either
15919 the word ``print'' or the word ``insert'' or the word ``column''.
15920 Therefore, we can simply type @kbd{M-x apropos RET
15921 print\|insert\|column RET} and look at the result.  On my system, this
15922 command once took quite some time, and then produced a list of 79
15923 functions and variables.  Now it does not take much time at all and
15924 produces a list of 211 functions and variables.  Scanning down the
15925 list, the only function that looks as if it might do the job is
15926 @code{insert-rectangle}.
15928 @need 1200
15929 Indeed, this is the function we want; its documentation says:
15931 @smallexample
15932 @group
15933 insert-rectangle:
15934 Insert text of RECTANGLE with upper left corner at point.
15935 RECTANGLE's first line is inserted at point,
15936 its second line is inserted at a point vertically under point, etc.
15937 RECTANGLE should be a list of strings.
15938 After this command, the mark is at the upper left corner
15939 and point is at the lower right corner.
15940 @end group
15941 @end smallexample
15943 We can run a quick test, to make sure it does what we expect of it.
15945 Here is the result of placing the cursor after the
15946 @code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
15947 (@code{eval-last-sexp}).  The function inserts the strings
15948 @samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
15949 point.  Also the function returns @code{nil}.
15951 @smallexample
15952 @group
15953 (insert-rectangle '("first" "second" "third"))first
15954                                               second
15955                                               thirdnil
15956 @end group
15957 @end smallexample
15959 @noindent
15960 Of course, we won't be inserting the text of the
15961 @code{insert-rectangle} expression itself into the buffer in which we
15962 are making the graph, but will call the function from our program.  We
15963 shall, however, have to make sure that point is in the buffer at the
15964 place where the @code{insert-rectangle} function will insert its
15965 column of strings.
15967 If you are reading this in Info, you can see how this works by
15968 switching to another buffer, such as the @file{*scratch*} buffer,
15969 placing point somewhere in the buffer, typing @kbd{M-:}, typing the
15970 @code{insert-rectangle} expression into the minibuffer at the prompt,
15971 and then typing @key{RET}.  This causes Emacs to evaluate the
15972 expression in the minibuffer, but to use as the value of point the
15973 position of point in the @file{*scratch*} buffer.  (@kbd{M-:}  is the
15974 keybinding for @code{eval-expression}. Also, @code{nil} does not
15975 appear in the @file{*scratch*} buffer since the expression is
15976 evaluated in the minibuffer.)
15978 We find when we do this that point ends up at the end of the last
15979 inserted line---that is to say, this function moves point as a
15980 side-effect.  If we were to repeat the command, with point at this
15981 position, the next insertion would be below and to the right of the
15982 previous insertion.  We don't want this!  If we are going to make a
15983 bar graph, the columns need to be beside each other.
15985 So we discover that each cycle of the column-inserting @code{while}
15986 loop must reposition point to the place we want it, and that place
15987 will be at the top, not the bottom, of the column.  Moreover, we
15988 remember that when we print a graph, we do not expect all the columns
15989 to be the same height.  This means that the top of each column may be
15990 at a different height from the previous one.  We cannot simply
15991 reposition point to the same line each time, but moved over to the
15992 right---or perhaps we can@dots{}
15994 We are planning to make the columns of the bar graph out of asterisks.
15995 The number of asterisks in the column is the number specified by the
15996 current element of the @code{numbers-list}.  We need to construct a
15997 list of asterisks of the right length for each call to
15998 @code{insert-rectangle}.  If this list consists solely of the requisite
15999 number of asterisks, then we will have to position point the right number
16000 of lines above the base for the graph to print correctly.  This could
16001 be difficult.
16003 Alternatively, if we can figure out some way to pass
16004 @code{insert-rectangle} a list of the same length each time, then we
16005 can place point on the same line each time, but move it over one
16006 column to the right for each new column.  If we do this, however, some
16007 of the entries in the list passed to @code{insert-rectangle} must be
16008 blanks rather than asterisks.  For example, if the maximum height of
16009 the graph is 5, but the height of the column is 3, then
16010 @code{insert-rectangle} requires an argument that looks like this:
16012 @smallexample
16013 (" " " " "*" "*" "*")
16014 @end smallexample
16016 This last proposal is not so difficult, so long as we can determine
16017 the column height.  There are two ways for us to specify the column
16018 height: we can arbitrarily state what it will be, which would work
16019 fine for graphs of that height; or we can search through the list of
16020 numbers and use the maximum height of the list as the maximum height
16021 of the graph.  If the latter operation were difficult, then the former
16022 procedure would be easiest, but there is a function built into Emacs
16023 that determines the maximum of its arguments.  We can use that
16024 function.  The function is called @code{max} and it returns the
16025 largest of all its arguments, which must be numbers.  Thus, for
16026 example,
16028 @smallexample
16029 (max  3 4 6 5 7 3)
16030 @end smallexample
16032 @noindent
16033 returns 7.  (A corresponding function called @code{min} returns the
16034 smallest of all its arguments.)
16035 @findex max
16036 @findex min
16038 However, we cannot simply call @code{max} on the @code{numbers-list};
16039 the @code{max} function expects numbers as its argument, not a list of
16040 numbers.  Thus, the following expression,
16042 @smallexample
16043 (max  '(3 4 6 5 7 3))
16044 @end smallexample
16046 @need 800
16047 @noindent
16048 produces the following error message;
16050 @smallexample
16051 Wrong type of argument:  number-or-marker-p, (3 4 6 5 7 3)
16052 @end smallexample
16054 @findex apply
16055 We need a function that passes a list of arguments to a function.
16056 This function is @code{apply}.  This function applies its first
16057 argument (a function) to its remaining arguments, the last of which
16058 may be a list.
16060 @need 1250
16061 For example,
16063 @smallexample
16064 (apply 'max 3 4 7 3 '(4 8 5))
16065 @end smallexample
16067 @noindent
16068 returns 8.
16070 (Incidentally, I don't know how you would learn of this function
16071 without a book such as this.  It is possible to discover other
16072 functions, like @code{search-forward} or @code{insert-rectangle}, by
16073 guessing at a part of their names and then using @code{apropos}.  Even
16074 though its base in metaphor is clear---apply its first argument to
16075 the rest---I doubt a novice would come up with that particular word
16076 when using @code{apropos} or other aid.  Of course, I could be wrong;
16077 after all, the function was first named by someone who had to invent
16078 it.)
16080 The second and subsequent arguments to @code{apply} are optional, so
16081 we can use @code{apply} to call a function and pass the elements of a
16082 list to it, like this, which also returns 8:
16084 @smallexample
16085 (apply 'max '(4 8 5))
16086 @end smallexample
16088 This latter way is how we will use @code{apply}.  The
16089 @code{recursive-lengths-list-many-files} function returns a numbers'
16090 list to which we can apply @code{max} (we could also apply @code{max} to
16091 the sorted numbers' list; it does not matter whether the list is
16092 sorted or not.)
16094 @need 800
16095 Hence, the operation for finding the maximum height of the graph is this:
16097 @smallexample
16098 (setq max-graph-height (apply 'max numbers-list))
16099 @end smallexample
16101 Now we can return to the question of how to create a list of strings
16102 for a column of the graph.  Told the maximum height of the graph
16103 and the number of asterisks that should appear in the column, the
16104 function should return a list of strings for the
16105 @code{insert-rectangle} command to insert.
16107 Each column is made up of asterisks or blanks.  Since the function is
16108 passed the value of the height of the column and the number of
16109 asterisks in the column, the number of blanks can be found by
16110 subtracting the number of asterisks from the height of the column.
16111 Given the number of blanks and the number of asterisks, two
16112 @code{while} loops can be used to construct the list:
16114 @smallexample
16115 @group
16116 ;;; @r{First version.}
16117 (defun column-of-graph (max-graph-height actual-height)
16118   "Return list of strings that is one column of a graph."
16119   (let ((insert-list nil)
16120         (number-of-top-blanks
16121          (- max-graph-height actual-height)))
16122 @end group
16124 @group
16125     ;; @r{Fill in asterisks.}
16126     (while (> actual-height 0)
16127       (setq insert-list (cons "*" insert-list))
16128       (setq actual-height (1- actual-height)))
16129 @end group
16131 @group
16132     ;; @r{Fill in blanks.}
16133     (while (> number-of-top-blanks 0)
16134       (setq insert-list (cons " " insert-list))
16135       (setq number-of-top-blanks
16136             (1- number-of-top-blanks)))
16137 @end group
16139 @group
16140     ;; @r{Return whole list.}
16141     insert-list))
16142 @end group
16143 @end smallexample
16145 If you install this function and then evaluate the following
16146 expression you will see that it returns the list as desired:
16148 @smallexample
16149 (column-of-graph 5 3)
16150 @end smallexample
16152 @need 800
16153 @noindent
16154 returns
16156 @smallexample
16157 (" " " " "*" "*" "*")
16158 @end smallexample
16160 As written, @code{column-of-graph} contains a major flaw: the symbols
16161 used for the blank and for the marked entries in the column are
16162 hard-coded as a space and asterisk.  This is fine for a prototype,
16163 but you, or another user, may wish to use other symbols.  For example,
16164 in testing the graph function, you may want to use a period in place
16165 of the space, to make sure the point is being repositioned properly
16166 each time the @code{insert-rectangle} function is called; or you might
16167 want to substitute a @samp{+} sign or other symbol for the asterisk.
16168 You might even want to make a graph-column that is more than one
16169 display column wide.  The program should be more flexible.  The way to
16170 do that is to replace the blank and the asterisk with two variables
16171 that we can call @code{graph-blank} and @code{graph-symbol} and define
16172 those variables separately.
16174 Also, the documentation is not well written.  These considerations
16175 lead us to the second version of the function:
16177 @smallexample
16178 @group
16179 (defvar graph-symbol "*"
16180   "String used as symbol in graph, usually an asterisk.")
16181 @end group
16183 @group
16184 (defvar graph-blank " "
16185   "String used as blank in graph, usually a blank space.
16186 graph-blank must be the same number of columns wide
16187 as graph-symbol.")
16188 @end group
16189 @end smallexample
16191 @noindent
16192 (For an explanation of @code{defvar}, see
16193 @ref{defvar, , Initializing a Variable with @code{defvar}}.)
16195 @smallexample
16196 @group
16197 ;;; @r{Second version.}
16198 (defun column-of-graph (max-graph-height actual-height)
16199   "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
16201 @end group
16202 @group
16203 The graph-symbols are contiguous entries at the end
16204 of the list.
16205 The list will be inserted as one column of a graph.
16206 The strings are either graph-blank or graph-symbol."
16207 @end group
16209 @group
16210   (let ((insert-list nil)
16211         (number-of-top-blanks
16212          (- max-graph-height actual-height)))
16213 @end group
16215 @group
16216     ;; @r{Fill in @code{graph-symbols}.}
16217     (while (> actual-height 0)
16218       (setq insert-list (cons graph-symbol insert-list))
16219       (setq actual-height (1- actual-height)))
16220 @end group
16222 @group
16223     ;; @r{Fill in @code{graph-blanks}.}
16224     (while (> number-of-top-blanks 0)
16225       (setq insert-list (cons graph-blank insert-list))
16226       (setq number-of-top-blanks
16227             (1- number-of-top-blanks)))
16229     ;; @r{Return whole list.}
16230     insert-list))
16231 @end group
16232 @end smallexample
16234 If we wished, we could rewrite @code{column-of-graph} a third time to
16235 provide optionally for a line graph as well as for a bar graph.  This
16236 would not be hard to do.  One way to think of a line graph is that it
16237 is no more than a bar graph in which the part of each bar that is
16238 below the top is blank.  To construct a column for a line graph, the
16239 function first constructs a list of blanks that is one shorter than
16240 the value, then it uses @code{cons} to attach a graph symbol to the
16241 list; then it uses @code{cons} again to attach the top blanks to
16242 the list.
16244 It is easy to see how to write such a function, but since we don't
16245 need it, we will not do it.  But the job could be done, and if it were
16246 done, it would be done with @code{column-of-graph}.  Even more
16247 important, it is worth noting that few changes would have to be made
16248 anywhere else.  The enhancement, if we ever wish to make it, is
16249 simple.
16251 Now, finally, we come to our first actual graph printing function.
16252 This prints the body of a graph, not the labels for the vertical and
16253 horizontal axes, so we can call this @code{graph-body-print}.
16255 @node graph-body-print
16256 @section The @code{graph-body-print} Function
16257 @findex graph-body-print
16259 After our preparation in the preceding section, the
16260 @code{graph-body-print} function is straightforward.  The function
16261 will print column after column of asterisks and blanks, using the
16262 elements of a numbers' list to specify the number of asterisks in each
16263 column.  This is a repetitive act, which means we can use a
16264 decrementing @code{while} loop or recursive function for the job.  In
16265 this section, we will write the definition using a @code{while} loop.
16267 The @code{column-of-graph} function requires the height of the graph
16268 as an argument, so we should determine and record that as a local variable.
16270 This leads us to the following template for the @code{while} loop
16271 version of this function:
16273 @smallexample
16274 @group
16275 (defun graph-body-print (numbers-list)
16276   "@var{documentation}@dots{}"
16277   (let ((height  @dots{}
16278          @dots{}))
16279 @end group
16281 @group
16282     (while numbers-list
16283       @var{insert-columns-and-reposition-point}
16284       (setq numbers-list (cdr numbers-list)))))
16285 @end group
16286 @end smallexample
16288 @noindent
16289 We need to fill in the slots of the template.
16291 Clearly, we can use the @code{(apply 'max numbers-list)} expression to
16292 determine the height of the graph.
16294 The @code{while} loop will cycle through the @code{numbers-list} one
16295 element at a time.  As it is shortened by the @code{(setq numbers-list
16296 (cdr numbers-list))} expression, the @sc{car} of each instance of the
16297 list is the value of the argument for @code{column-of-graph}.
16299 At each cycle of the @code{while} loop, the @code{insert-rectangle}
16300 function inserts the list returned by @code{column-of-graph}.  Since
16301 the @code{insert-rectangle} function moves point to the lower right of
16302 the inserted rectangle, we need to save the location of point at the
16303 time the rectangle is inserted, move back to that position after the
16304 rectangle is inserted, and then move horizontally to the next place
16305 from which @code{insert-rectangle} is called.
16307 If the inserted columns are one character wide, as they will be if
16308 single blanks and asterisks are used, the repositioning command is
16309 simply @code{(forward-char 1)}; however, the width of a column may be
16310 greater than one.  This means that the repositioning command should be
16311 written @code{(forward-char symbol-width)}.  The @code{symbol-width}
16312 itself is the length of a @code{graph-blank} and can be found using
16313 the expression @code{(length graph-blank)}.  The best place to bind
16314 the @code{symbol-width} variable to the value of the width of graph
16315 column is in the varlist of the @code{let} expression.
16317 @need 1250
16318 These considerations lead to the following function definition:
16320 @smallexample
16321 @group
16322 (defun graph-body-print (numbers-list)
16323   "Print a bar graph of the NUMBERS-LIST.
16324 The numbers-list consists of the Y-axis values."
16326   (let ((height (apply 'max numbers-list))
16327         (symbol-width (length graph-blank))
16328         from-position)
16329 @end group
16331 @group
16332     (while numbers-list
16333       (setq from-position (point))
16334       (insert-rectangle
16335        (column-of-graph height (car numbers-list)))
16336       (goto-char from-position)
16337       (forward-char symbol-width)
16338 @end group
16339 @group
16340       ;; @r{Draw graph column by column.}
16341       (sit-for 0)
16342       (setq numbers-list (cdr numbers-list)))
16343 @end group
16344 @group
16345     ;; @r{Place point for X axis labels.}
16346     (forward-line height)
16347     (insert "\n")
16349 @end group
16350 @end smallexample
16352 @noindent
16353 The one unexpected expression in this function is the
16354 @w{@code{(sit-for 0)}} expression in the @code{while} loop.  This
16355 expression makes the graph printing operation more interesting to
16356 watch than it would be otherwise.  The expression causes Emacs to
16357 @dfn{sit} or do nothing for a zero length of time and then redraw the
16358 screen.  Placed here, it causes Emacs to redraw the screen column by
16359 column.  Without it, Emacs would not redraw the screen until the
16360 function exits.
16362 We can test @code{graph-body-print} with a short list of numbers.
16364 @enumerate
16365 @item
16366 Install @code{graph-symbol}, @code{graph-blank},
16367 @code{column-of-graph}, which are in
16368 @iftex
16369 @ref{Readying a Graph, , Readying a Graph},
16370 @end iftex
16371 @ifinfo
16372 @ref{Columns of a graph},
16373 @end ifinfo
16374 and @code{graph-body-print}.
16376 @need 800
16377 @item
16378 Copy the following expression:
16380 @smallexample
16381 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
16382 @end smallexample
16384 @item
16385 Switch to the @file{*scratch*} buffer and place the cursor where you
16386 want the graph to start.
16388 @item
16389 Type @kbd{M-:} (@code{eval-expression}).
16391 @item
16392 Yank the @code{graph-body-print} expression into the minibuffer
16393 with @kbd{C-y} (@code{yank)}.
16395 @item
16396 Press @key{RET} to evaluate the @code{graph-body-print} expression.
16397 @end enumerate
16399 @need 800
16400 Emacs will print a graph like this:
16402 @smallexample
16403 @group
16404                     *
16405                 *   **
16406                 *  ****
16407                *** ****
16408               ********* *
16409              ************
16410             *************
16411 @end group
16412 @end smallexample
16414 @node recursive-graph-body-print
16415 @section The @code{recursive-graph-body-print} Function
16416 @findex recursive-graph-body-print
16418 The @code{graph-body-print} function may also be written recursively.
16419 The recursive solution is divided into two parts: an outside wrapper
16420 that uses a @code{let} expression to determine the values of several
16421 variables that need only be found once, such as the maximum height of
16422 the graph, and an inside function that is called recursively to print
16423 the graph.
16425 @need 1250
16426 The wrapper is uncomplicated:
16428 @smallexample
16429 @group
16430 (defun recursive-graph-body-print (numbers-list)
16431   "Print a bar graph of the NUMBERS-LIST.
16432 The numbers-list consists of the Y-axis values."
16433   (let ((height (apply 'max numbers-list))
16434         (symbol-width (length graph-blank))
16435         from-position)
16436     (recursive-graph-body-print-internal
16437      numbers-list
16438      height
16439      symbol-width)))
16440 @end group
16441 @end smallexample
16443 The recursive function is a little more difficult.  It has four parts:
16444 the do-again-test, the printing code, the recursive call, and the
16445 next-step-expression.  The do-again-test is a @code{when}
16446 expression that determines whether the @code{numbers-list} contains
16447 any remaining elements; if it does, the function prints one column of
16448 the graph using the printing code and calls itself again.  The
16449 function calls itself again according to the value produced by the
16450 next-step-expression which causes the call to act on a shorter
16451 version of the @code{numbers-list}.
16453 @smallexample
16454 @group
16455 (defun recursive-graph-body-print-internal
16456   (numbers-list height symbol-width)
16457   "Print a bar graph.
16458 Used within recursive-graph-body-print function."
16459 @end group
16461 @group
16462   (when numbers-list
16463         (setq from-position (point))
16464         (insert-rectangle
16465          (column-of-graph height (car numbers-list)))
16466 @end group
16467 @group
16468         (goto-char from-position)
16469         (forward-char symbol-width)
16470         (sit-for 0)     ; @r{Draw graph column by column.}
16471         (recursive-graph-body-print-internal
16472          (cdr numbers-list) height symbol-width)))
16473 @end group
16474 @end smallexample
16476 @need 1250
16477 After installation, this expression can be tested; here is a sample:
16479 @smallexample
16480 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
16481 @end smallexample
16483 @need 800
16484 Here is what @code{recursive-graph-body-print} produces:
16486 @smallexample
16487 @group
16488                 *
16489                **   *
16490               ****  *
16491               **** ***
16492             * *********
16493             ************
16494             *************
16495 @end group
16496 @end smallexample
16498 Either of these two functions, @code{graph-body-print} or
16499 @code{recursive-graph-body-print}, create the body of a graph.
16501 @node Printed Axes
16502 @section Need for Printed Axes
16504 A graph needs printed axes, so you can orient yourself.  For a do-once
16505 project, it may be reasonable to draw the axes by hand using Emacs's
16506 Picture mode; but a graph drawing function may be used more than once.
16508 For this reason, I have written enhancements to the basic
16509 @code{print-graph-body} function that automatically print labels for
16510 the horizontal and vertical axes.  Since the label printing functions
16511 do not contain much new material, I have placed their description in
16512 an appendix.  @xref{Full Graph, , A Graph with Labeled Axes}.
16514 @node Line Graph Exercise
16515 @section Exercise
16517 Write a line graph version of the graph printing functions.
16519 @node Emacs Initialization
16520 @chapter Your @file{.emacs} File
16521 @cindex @file{.emacs} file
16522 @cindex Customizing your @file{.emacs} file
16523 @cindex Initialization file
16525 ``You don't have to like Emacs to like it''---this seemingly
16526 paradoxical statement is the secret of GNU Emacs.  The plain, out-of-the-box
16527 Emacs is a generic tool.  Most people who use it customize
16528 it to suit themselves.
16530 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
16531 expressions in Emacs Lisp you can change or extend Emacs.
16533 @menu
16534 * Default Configuration::
16535 * Site-wide Init::              You can write site-wide init files.
16536 * defcustom::                   Emacs will write code for you.
16537 * Beginning init File::         How to write a @file{.emacs} init file.
16538 * Text and Auto-fill::          Automatically wrap lines.
16539 * Mail Aliases::                Use abbreviations for email addresses.
16540 * Indent Tabs Mode::            Don't use tabs with @TeX{}
16541 * Keybindings::                 Create some personal keybindings.
16542 * Keymaps::                     More about key binding.
16543 * Loading Files::               Load (i.e., evaluate) files automatically.
16544 * Autoload::                    Make functions available.
16545 * Simple Extension::            Define a function; bind it to a key.
16546 * X11 Colors::                  Colors in X.
16547 * Miscellaneous::
16548 * Mode Line::                   How to customize your mode line.
16549 @end menu
16551 @ifnottex
16552 @node Default Configuration
16553 @unnumberedsec Emacs's Default Configuration
16554 @end ifnottex
16556 There are those who appreciate Emacs's default configuration.  After
16557 all, Emacs starts you in C mode when you edit a C file, starts you in
16558 Fortran mode when you edit a Fortran file, and starts you in
16559 Fundamental mode when you edit an unadorned file.  This all makes
16560 sense, if you do not know who is going to use Emacs.  Who knows what a
16561 person hopes to do with an unadorned file?  Fundamental mode is the
16562 right default for such a file, just as C mode is the right default for
16563 editing C code.  (Enough programming languages have syntaxes
16564 that enable them to share or nearly share features, so C mode is
16565 now provided by CC mode, the C Collection.)
16567 But when you do know who is going to use Emacs---you,
16568 yourself---then it makes sense to customize Emacs.
16570 For example, I seldom want Fundamental mode when I edit an
16571 otherwise undistinguished file; I want Text mode.  This is why I
16572 customize Emacs: so it suits me.
16574 You can customize and extend Emacs by writing or adapting a
16575 @file{~/.emacs} file.  This is your personal initialization file; its
16576 contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16577 may also add @file{.el} to @file{~/.emacs} and call it a
16578 @file{~/.emacs.el} file.  In the past, you were forbidden to type the
16579 extra keystrokes that the name @file{~/.emacs.el} requires, but now
16580 you may.  The new format is consistent with the Emacs Lisp file
16581 naming conventions; the old format saves typing.}
16583 A @file{~/.emacs} file contains Emacs Lisp code.  You can write this
16584 code yourself; or you can use Emacs's @code{customize} feature to write
16585 the code for you.  You can combine your own expressions and
16586 auto-written Customize expressions in your @file{.emacs} file.
16588 (I myself prefer to write my own expressions, except for those,
16589 particularly fonts, that I find easier to manipulate using the
16590 @code{customize} command.  I combine the two methods.)
16592 Most of this chapter is about writing expressions yourself.  It
16593 describes a simple @file{.emacs} file; for more information, see
16594 @ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16595 @ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16596 Manual}.
16598 @node Site-wide Init
16599 @section Site-wide Initialization Files
16601 @cindex @file{default.el} init file
16602 @cindex @file{site-init.el} init file
16603 @cindex @file{site-load.el} init file
16604 In addition to your personal initialization file, Emacs automatically
16605 loads various site-wide initialization files, if they exist.  These
16606 have the same form as your @file{.emacs} file, but are loaded by
16607 everyone.
16609 Two site-wide initialization files, @file{site-load.el} and
16610 @file{site-init.el}, are loaded into Emacs and then dumped if a
16611 dumped version of Emacs is created, as is most common.  (Dumped
16612 copies of Emacs load more quickly.  However, once a file is loaded and
16613 dumped, a change to it does not lead to a change in Emacs unless you
16614 load it yourself or re-dump Emacs.  @xref{Building Emacs, , Building
16615 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16616 @file{INSTALL} file.)
16618 Three other site-wide initialization files are loaded automatically
16619 each time you start Emacs, if they exist.  These are
16620 @file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16621 file, and @file{default.el}, and the terminal type file, which are both
16622 loaded @emph{after} your @file{.emacs} file.
16624 Settings and definitions in your @file{.emacs} file will overwrite
16625 conflicting settings and definitions in a @file{site-start.el} file,
16626 if it exists; but the settings and definitions in a @file{default.el}
16627 or terminal type file will overwrite those in your @file{.emacs} file.
16628 (You can prevent interference from a terminal type file by setting
16629 @code{term-file-prefix} to @code{nil}.  @xref{Simple Extension, , A
16630 Simple Extension}.)
16632 @c Rewritten to avoid overfull hbox.
16633 The @file{INSTALL} file that comes in the distribution contains
16634 descriptions of the @file{site-init.el} and @file{site-load.el} files.
16636 The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16637 control loading.  These files are in the @file{lisp} directory of the
16638 Emacs distribution and are worth perusing.
16640 The @file{loaddefs.el} file contains a good many suggestions as to
16641 what to put into your own @file{.emacs} file, or into a site-wide
16642 initialization file.
16644 @node defcustom
16645 @section Specifying Variables using @code{defcustom}
16646 @findex defcustom
16648 You can specify variables using @code{defcustom} so that you and
16649 others can then use Emacs's @code{customize} feature to set their
16650 values.  (You cannot use @code{customize} to write function
16651 definitions; but you can write @code{defuns} in your @file{.emacs}
16652 file.  Indeed, you can write any Lisp expression in your @file{.emacs}
16653 file.)
16655 The @code{customize} feature depends on the @code{defcustom} macro.
16656 Although you can use @code{defvar} or @code{setq} for variables that
16657 users set, the @code{defcustom} macro is designed for the job.
16659 You can use your knowledge of @code{defvar} for writing the
16660 first three arguments for @code{defcustom}.  The first argument to
16661 @code{defcustom} is the name of the variable.  The second argument is
16662 the variable's initial value, if any; and this value is set only if
16663 the value has not already been set.  The third argument is the
16664 documentation.
16666 The fourth and subsequent arguments to @code{defcustom} specify types
16667 and options; these are not featured in @code{defvar}.  (These
16668 arguments are optional.)
16670 Each of these arguments consists of a keyword followed by a value.
16671 Each keyword starts with the colon character @samp{:}.
16673 @need 1250
16674 For example, the customizable user option variable
16675 @code{text-mode-hook} looks like this:
16677 @smallexample
16678 @group
16679 (defcustom text-mode-hook nil
16680   "Normal hook run when entering Text mode and many related modes."
16681   :type 'hook
16682   :options '(turn-on-auto-fill flyspell-mode)
16683   :group 'wp)
16684 @end group
16685 @end smallexample
16687 @noindent
16688 The name of the variable is @code{text-mode-hook}; it has no default
16689 value; and its documentation string tells you what it does.
16691 The @code{:type} keyword tells Emacs the kind of data to which
16692 @code{text-mode-hook} should be set and how to display the value in a
16693 Customization buffer.
16695 The @code{:options} keyword specifies a suggested list of values for
16696 the variable.  Usually, @code{:options} applies to a hook.
16697 The list is only a suggestion; it is not exclusive; a person who sets
16698 the variable may set it to other values; the list shown following the
16699 @code{:options} keyword is intended to offer convenient choices to a
16700 user.
16702 Finally, the @code{:group} keyword tells the Emacs Customization
16703 command in which group the variable is located.  This tells where to
16704 find it.
16706 The @code{defcustom} macro recognizes more than a dozen keywords.
16707 For more information, see @ref{Customization, , Writing Customization
16708 Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
16710 Consider @code{text-mode-hook} as an example.
16712 There are two ways to customize this variable.  You can use the
16713 customization command or write the appropriate expressions yourself.
16715 @need 800
16716 Using the customization command,  you can type:
16718 @smallexample
16719 M-x customize
16720 @end smallexample
16722 @noindent
16723 and find that the group for editing files of text is called ``Text''.
16724 Enter that group.  Text Mode Hook is the first member.  You can click
16725 on its various options, such as @code{turn-on-auto-fill}, to set the
16726 values.  After you click on the button to
16728 @smallexample
16729 Save for Future Sessions
16730 @end smallexample
16732 @noindent
16733 Emacs will write an expression into your @file{.emacs} file.
16734 It will look like this:
16736 @smallexample
16737 @group
16738 (custom-set-variables
16739   ;; custom-set-variables was added by Custom.
16740   ;; If you edit it by hand, you could mess it up, so be careful.
16741   ;; Your init file should contain only one such instance.
16742   ;; If there is more than one, they won't work right.
16743  '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
16744 @end group
16745 @end smallexample
16747 @noindent
16748 (The @code{text-mode-hook-identify} function tells
16749 @code{toggle-text-mode-auto-fill} which buffers are in Text mode.
16750 It comes on automatically.)
16752 The @code{custom-set-variables} function works somewhat differently
16753 than a @code{setq}.  While I have never learned the differences, I
16754 modify the @code{custom-set-variables} expressions in my @file{.emacs}
16755 file by hand:  I make the changes in what appears to me to be a
16756 reasonable manner and have not had any problems.  Others prefer to use
16757 the Customization command and let Emacs do the work for them.
16759 Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
16760 This function sets the various font faces.  Over time, I have set a
16761 considerable number of faces.  Some of the time, I re-set them using
16762 @code{customize}; other times, I simply edit the
16763 @code{custom-set-faces} expression in my @file{.emacs} file itself.
16765 The second way to customize your @code{text-mode-hook} is to set it
16766 yourself in your @file{.emacs} file using code that has nothing to do
16767 with the @code{custom-set-@dots{}} functions.
16769 @need 800
16770 When you do this, and later use @code{customize}, you will see a
16771 message that says
16773 @smallexample
16774 CHANGED outside Customize; operating on it here may be unreliable.
16775 @end smallexample
16777 @need 800
16778 This message is only a warning.  If you click on the button to
16780 @smallexample
16781 Save for Future Sessions
16782 @end smallexample
16784 @noindent
16785 Emacs will write a @code{custom-set-@dots{}} expression near the end
16786 of your @file{.emacs} file that will be evaluated after your
16787 hand-written expression.  It will, therefore, overrule your
16788 hand-written expression.  No harm will be done.  When you do this,
16789 however, be careful to remember which expression is active; if you
16790 forget, you may confuse yourself.
16792 So long as you remember where the values are set, you will have no
16793 trouble.  In any event, the values are always set in your
16794 initialization file, which is usually called @file{.emacs}.
16796 I myself use @code{customize} for hardly anything.  Mostly, I write
16797 expressions myself.
16799 @findex defsubst
16800 @findex defconst
16801 Incidentally, to be more complete concerning defines:  @code{defsubst}
16802 defines an inline function.  The syntax is just like that of
16803 @code{defun}.  @code{defconst} defines a symbol as a constant.  The
16804 intent is that neither programs nor users should ever change a value
16805 set by @code{defconst}.  (You can change it; the value set is a
16806 variable; but please do not.)
16808 @node Beginning init File
16809 @section Beginning a @file{.emacs} File
16810 @cindex @file{.emacs} file, beginning of
16812 When you start Emacs, it loads your @file{.emacs} file unless you tell
16813 it not to by specifying @samp{-q} on the command line.  (The
16814 @code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
16816 A @file{.emacs} file contains Lisp expressions.  Often, these are no
16817 more than expressions to set values; sometimes they are function
16818 definitions.
16820 @xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
16821 Manual}, for a short description of initialization files.
16823 This chapter goes over some of the same ground, but is a walk among
16824 extracts from a complete, long-used @file{.emacs} file---my own.
16826 The first part of the file consists of comments: reminders to myself.
16827 By now, of course, I remember these things, but when I started, I did
16828 not.
16830 @need 1200
16831 @smallexample
16832 @group
16833 ;;;; Bob's .emacs file
16834 ; Robert J. Chassell
16835 ; 26 September 1985
16836 @end group
16837 @end smallexample
16839 @noindent
16840 Look at that date!  I started this file a long time ago.  I have been
16841 adding to it ever since.
16843 @smallexample
16844 @group
16845 ; Each section in this file is introduced by a
16846 ; line beginning with four semicolons; and each
16847 ; entry is introduced by a line beginning with
16848 ; three semicolons.
16849 @end group
16850 @end smallexample
16852 @noindent
16853 This describes the usual conventions for comments in Emacs Lisp.
16854 Everything on a line that follows a semicolon is a comment.  Two,
16855 three, and four semicolons are used as subsection and section markers.
16856 (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference Manual}, for
16857 more about comments.)
16859 @smallexample
16860 @group
16861 ;;;; The Help Key
16862 ; Control-h is the help key;
16863 ; after typing control-h, type a letter to
16864 ; indicate the subject about which you want help.
16865 ; For an explanation of the help facility,
16866 ; type control-h two times in a row.
16867 @end group
16868 @end smallexample
16870 @noindent
16871 Just remember: type @kbd{C-h} two times for help.
16873 @smallexample
16874 @group
16875 ; To find out about any mode, type control-h m
16876 ; while in that mode.  For example, to find out
16877 ; about mail mode, enter mail mode and then type
16878 ; control-h m.
16879 @end group
16880 @end smallexample
16882 @noindent
16883 ``Mode help'', as I call this, is very helpful.  Usually, it tells you
16884 all you need to know.
16886 Of course, you don't need to include comments like these in your
16887 @file{.emacs} file.  I included them in mine because I kept forgetting
16888 about Mode help or the conventions for comments---but I was able to
16889 remember to look here to remind myself.
16891 @node Text and Auto-fill
16892 @section Text and Auto Fill Mode
16894 Now we come to the part that turns on Text mode and
16895 Auto Fill mode.
16897 @smallexample
16898 @group
16899 ;;; Text mode and Auto Fill mode
16900 ;; The next two lines put Emacs into Text mode
16901 ;; and Auto Fill mode, and are for writers who
16902 ;; want to start writing prose rather than code.
16903 (setq-default major-mode 'text-mode)
16904 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16905 @end group
16906 @end smallexample
16908 Here is the first part of this @file{.emacs} file that does something
16909 besides remind a forgetful human!
16911 The first of the two lines in parentheses tells Emacs to turn on Text
16912 mode when you find a file, @emph{unless} that file should go into some
16913 other mode, such as C mode.
16915 @cindex Per-buffer, local variables list
16916 @cindex Local variables list, per-buffer,
16917 @cindex Automatic mode selection
16918 @cindex Mode selection, automatic
16919 When Emacs reads a file, it looks at the extension to the file name,
16920 if any.  (The extension is the part that comes after a @samp{.}.)  If
16921 the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
16922 on C mode.  Also, Emacs looks at first nonblank line of the file; if
16923 the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode.  Emacs
16924 possesses a list of extensions and specifications that it uses
16925 automatically.  In addition, Emacs looks near the last page for a
16926 per-buffer, local variables list, if any.
16928 @ifinfo
16929 @xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
16930 Emacs Manual}.
16932 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16933 Manual}.
16934 @end ifinfo
16935 @iftex
16936 See sections ``How Major Modes are Chosen'' and ``Local Variables in
16937 Files'' in @cite{The GNU Emacs Manual}.
16938 @end iftex
16940 Now, back to the @file{.emacs} file.
16942 @need 800
16943 Here is the line again; how does it work?
16945 @cindex Text Mode turned on
16946 @smallexample
16947 (setq major-mode 'text-mode)
16948 @end smallexample
16950 @noindent
16951 This line is a short, but complete Emacs Lisp expression.
16953 We are already familiar with @code{setq}.  It sets the following variable,
16954 @code{major-mode}, to the subsequent value, which is @code{text-mode}.
16955 The single-quote before @code{text-mode} tells Emacs to deal directly
16956 with the @code{text-mode} symbol, not with whatever it might stand for.
16957 @xref{set & setq, , Setting the Value of a Variable},
16958 for a reminder of how @code{setq} works.
16959 The main point is that there is no difference between the procedure you
16960 use to set a value in your @file{.emacs} file and the procedure you use
16961 anywhere else in Emacs.
16963 @need 800
16964 Here is the next line:
16966 @cindex Auto Fill mode turned on
16967 @findex add-hook
16968 @smallexample
16969 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16970 @end smallexample
16972 @noindent
16973 In this line, the @code{add-hook} command adds
16974 @code{turn-on-auto-fill} to the variable.
16976 @code{turn-on-auto-fill} is the name of a program, that, you guessed
16977 it!, turns on Auto Fill mode.
16979 Every time Emacs turns on Text mode, Emacs runs the commands hooked
16980 onto Text mode.  So every time Emacs turns on Text mode, Emacs also
16981 turns on Auto Fill mode.
16983 In brief, the first line causes Emacs to enter Text mode when you edit a
16984 file, unless the file name extension, a first non-blank line, or local
16985 variables to tell Emacs otherwise.
16987 Text mode among other actions, sets the syntax table to work
16988 conveniently for writers.  In Text mode, Emacs considers an apostrophe
16989 as part of a word like a letter; but Emacs does not consider a period
16990 or a space as part of a word.  Thus, @kbd{M-f} moves you over
16991 @samp{it's}.  On the other hand, in C mode, @kbd{M-f} stops just after
16992 the @samp{t} of @samp{it's}.
16994 The second line causes Emacs to turn on Auto Fill mode when it turns
16995 on Text mode.  In Auto Fill mode, Emacs automatically breaks a line
16996 that is too wide and brings the excessively wide part of the line down
16997 to the next line.  Emacs breaks lines between words, not within them.
16999 When Auto Fill mode is turned off, lines continue to the right as you
17000 type them.  Depending on how you set the value of
17001 @code{truncate-lines}, the words you type either disappear off the
17002 right side of the screen, or else are shown, in a rather ugly and
17003 unreadable manner, as a continuation line on the screen.
17005 @need 1250
17006 In addition, in this part of my @file{.emacs} file, I tell the Emacs
17007 fill commands to insert two spaces after a colon:
17009 @smallexample
17010 (setq colon-double-space t)
17011 @end smallexample
17013 @node Mail Aliases
17014 @section Mail Aliases
17016 Here is a @code{setq} that turns on mail aliases, along with more
17017 reminders.
17019 @smallexample
17020 @group
17021 ;;; Mail mode
17022 ; To enter mail mode, type 'C-x m'
17023 ; To enter RMAIL (for reading mail),
17024 ; type 'M-x rmail'
17025 (setq mail-aliases t)
17026 @end group
17027 @end smallexample
17029 @cindex Mail aliases
17030 @noindent
17031 This @code{setq} command sets the value of the variable
17032 @code{mail-aliases} to @code{t}.  Since @code{t} means true, the line
17033 says, in effect, ``Yes, use mail aliases.''
17035 Mail aliases are convenient short names for long email addresses or
17036 for lists of email addresses.  The file where you keep your aliases
17037 is @file{~/.mailrc}.  You write an alias like this:
17039 @smallexample
17040 alias geo george@@foobar.wiz.edu
17041 @end smallexample
17043 @noindent
17044 When you write a message to George, address it to @samp{geo}; the
17045 mailer will automatically expand @samp{geo} to the full address.
17047 @node Indent Tabs Mode
17048 @section Indent Tabs Mode
17049 @cindex Tabs, preventing
17050 @findex indent-tabs-mode
17052 By default, Emacs inserts tabs in place of multiple spaces when it
17053 formats a region.  (For example, you might indent many lines of text
17054 all at once with the @code{indent-region} command.)  Tabs look fine on
17055 a terminal or with ordinary printing, but they produce badly indented
17056 output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
17058 @need 1250
17059 The following turns off Indent Tabs mode:
17061 @smallexample
17062 @group
17063 ;;; Prevent Extraneous Tabs
17064 (setq-default indent-tabs-mode nil)
17065 @end group
17066 @end smallexample
17068 Note that this line uses @code{setq-default} rather than the
17069 @code{setq} command that we have seen before.  The @code{setq-default}
17070 command sets values only in buffers that do not have their own local
17071 values for the variable.
17073 @ifinfo
17074 @xref{Just Spaces, , Tabs vs.@: Spaces, emacs, The GNU Emacs Manual}.
17076 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17077 Manual}.
17078 @end ifinfo
17079 @iftex
17080 See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
17081 Files'' in @cite{The GNU Emacs Manual}.
17082 @end iftex
17084 @need 1700
17085 @node Keybindings
17086 @section Some Keybindings
17088 Now for some personal keybindings:
17090 @smallexample
17091 @group
17092 ;;; Compare windows
17093 (global-set-key "\C-cw" 'compare-windows)
17094 @end group
17095 @end smallexample
17097 @findex compare-windows
17098 @code{compare-windows} is a nifty command that compares the text in
17099 your current window with text in the next window.  It makes the
17100 comparison by starting at point in each window, moving over text in
17101 each window as far as they match.  I use this command all the time.
17103 This also shows how to set a key globally, for all modes.
17105 @cindex Setting a key globally
17106 @cindex Global set key
17107 @cindex Key setting globally
17108 @findex global-set-key
17109 The command is @code{global-set-key}.  It is followed by the
17110 keybinding.  In a @file{.emacs} file, the keybinding is written as
17111 shown: @code{\C-c} stands for Control-C, which means to press the
17112 control key and the @key{c} key at the same time.  The @code{w} means
17113 to press the @key{w} key.  The keybinding is surrounded by double
17114 quotation marks.  In documentation, you would write this as
17115 @w{@kbd{C-c w}}.  (If you were binding a @key{META} key, such as
17116 @kbd{M-c}, rather than a @key{CTRL} key, you would write
17117 @w{@code{\M-c}} in your @file{.emacs} file.  @xref{Init Rebinding, ,
17118 Rebinding Keys in Your Init File, emacs, The GNU Emacs Manual}, for
17119 details.)
17121 The command invoked by the keys is @code{compare-windows}.  Note that
17122 @code{compare-windows} is preceded by a single-quote; otherwise, Emacs
17123 would first try to evaluate the symbol to determine its value.
17125 These three things, the double quotation marks, the backslash before
17126 the @samp{C}, and the single-quote are necessary parts of
17127 keybinding that I tend to forget.  Fortunately, I have come to
17128 remember that I should look at my existing @file{.emacs} file, and
17129 adapt what is there.
17131 As for the keybinding itself: @kbd{C-c w}.  This combines the prefix
17132 key, @kbd{C-c}, with a single character, in this case, @kbd{w}.  This
17133 set of keys, @kbd{C-c} followed by a single character, is strictly
17134 reserved for individuals' own use.  (I call these @dfn{own} keys, since
17135 these are for my own use.)  You should always be able to create such a
17136 keybinding for your own use without stomping on someone else's
17137 keybinding.  If you ever write an extension to Emacs, please avoid
17138 taking any of these keys for public use.  Create a key like @kbd{C-c
17139 C-w} instead.  Otherwise, we will run out of own keys.
17141 @need 1250
17142 Here is another keybinding, with a comment:
17144 @smallexample
17145 @group
17146 ;;; Keybinding for 'occur'
17147 ; I use occur a lot, so let's bind it to a key:
17148 (global-set-key "\C-co" 'occur)
17149 @end group
17150 @end smallexample
17152 @findex occur
17153 The @code{occur} command shows all the lines in the current buffer
17154 that contain a match for a regular expression.  When the region is
17155 active, @code{occur} restricts matches to such region.  Otherwise it
17156 uses the entire buffer.
17157 Matching lines are shown in a buffer called @file{*Occur*}.
17158 That buffer serves as a menu to jump to occurrences.
17160 @findex global-unset-key
17161 @cindex Unbinding key
17162 @cindex Key unbinding
17163 @need 1250
17164 Here is how to unbind a key, so it does not
17165 work:
17167 @smallexample
17168 @group
17169 ;;; Unbind 'C-x f'
17170 (global-unset-key "\C-xf")
17171 @end group
17172 @end smallexample
17174 There is a reason for this unbinding: I found I inadvertently typed
17175 @w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}.  Rather than find a
17176 file, as I intended, I accidentally set the width for filled text,
17177 almost always to a width I did not want.  Since I hardly ever reset my
17178 default width, I simply unbound the key.
17180 @findex list-buffers, @r{rebound}
17181 @findex buffer-menu, @r{bound to key}
17182 @need 1250
17183 The following rebinds an existing key:
17185 @smallexample
17186 @group
17187 ;;; Rebind 'C-x C-b' for 'buffer-menu'
17188 (global-set-key "\C-x\C-b" 'buffer-menu)
17189 @end group
17190 @end smallexample
17192 By default, @kbd{C-x C-b} runs the
17193 @code{list-buffers} command.  This command lists
17194 your buffers in @emph{another} window.  Since I
17195 almost always want to do something in that
17196 window, I prefer the  @code{buffer-menu}
17197 command, which not only lists the buffers,
17198 but moves point into that window.
17200 @node Keymaps
17201 @section Keymaps
17202 @cindex Keymaps
17203 @cindex Rebinding keys
17205 Emacs uses @dfn{keymaps} to record which keys call which commands.
17206 When you use @code{global-set-key} to set the keybinding for a single
17207 command in all parts of Emacs, you are specifying the keybinding in
17208 @code{current-global-map}.
17210 Specific modes, such as C mode or Text mode, have their own keymaps;
17211 the mode-specific keymaps override the global map that is shared by
17212 all buffers.
17214 The @code{global-set-key} function binds, or rebinds, the global
17215 keymap.  For example, the following binds the key @kbd{C-x C-b} to the
17216 function @code{buffer-menu}:
17218 @smallexample
17219 (global-set-key "\C-x\C-b" 'buffer-menu)
17220 @end smallexample
17222 Mode-specific keymaps are bound using the @code{define-key} function,
17223 which takes a specific keymap as an argument, as well as the key and
17224 the command.  For example, my @file{.emacs} file contains the
17225 following expression to bind the @code{texinfo-insert-@@group} command
17226 to @kbd{C-c C-c g}:
17228 @smallexample
17229 @group
17230 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
17231 @end group
17232 @end smallexample
17234 @noindent
17235 The @code{texinfo-insert-@@group} function itself is a little extension
17236 to Texinfo mode that inserts @samp{@@group} into a Texinfo file.  I
17237 use this command all the time and prefer to type the three strokes
17238 @kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
17239 (@samp{@@group} and its matching @samp{@@end group} are commands that
17240 keep all enclosed text together on one page; many multi-line examples
17241 in this book are surrounded by @samp{@@group @dots{} @@end group}.)
17243 @need 1250
17244 Here is the @code{texinfo-insert-@@group} function definition:
17246 @smallexample
17247 @group
17248 (defun texinfo-insert-@@group ()
17249   "Insert the string @@group in a Texinfo buffer."
17250   (interactive)
17251   (beginning-of-line)
17252   (insert "@@group\n"))
17253 @end group
17254 @end smallexample
17256 (Of course, I could have used Abbrev mode to save typing, rather than
17257 write a function to insert a word; but I prefer key strokes consistent
17258 with other Texinfo mode key bindings.)
17260 You will see numerous @code{define-key} expressions in
17261 @file{loaddefs.el} as well as in the various mode libraries, such as
17262 @file{cc-mode.el} and @file{lisp-mode.el}.
17264 @xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
17265 Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
17266 Reference Manual}, for more information about keymaps.
17268 @node Loading Files
17269 @section Loading Files
17270 @cindex Loading files
17271 @c findex load
17273 Many people in the GNU Emacs community have written extensions to
17274 Emacs.  As time goes by, these extensions are often included in new
17275 releases.  For example, the Calendar and Diary packages are now part
17276 of the standard GNU Emacs, as is Calc.
17278 You can use a @code{load} command to evaluate a complete file and
17279 thereby install all the functions and variables in the file into Emacs.
17280 For example:
17282 @c (auto-compression-mode t)
17284 @smallexample
17285 (load "~/emacs/slowsplit")
17286 @end smallexample
17288 This evaluates, i.e., loads, the @file{slowsplit.el} file or if it
17289 exists, the faster, byte compiled @file{slowsplit.elc} file from the
17290 @file{emacs} sub-directory of your home directory.  The file contains
17291 the function @code{split-window-quietly}, which John Robinson wrote in
17292 1989.
17294 The @code{split-window-quietly} function splits a window with the
17295 minimum of redisplay.  I installed it in 1989 because it worked well
17296 with the slow 1200 baud terminals I was then using.  Nowadays, I only
17297 occasionally come across such a slow connection, but I continue to use
17298 the function because I like the way it leaves the bottom half of a
17299 buffer in the lower of the new windows and the top half in the upper
17300 window.
17302 @need 1250
17303 To replace the key binding for the default
17304 @code{split-window-vertically}, you must also unset that key and bind
17305 the keys to @code{split-window-quietly}, like this:
17307 @smallexample
17308 @group
17309 (global-unset-key "\C-x2")
17310 (global-set-key "\C-x2" 'split-window-quietly)
17311 @end group
17312 @end smallexample
17314 @vindex load-path
17315 If you load many extensions, as I do, then instead of specifying the
17316 exact location of the extension file, as shown above, you can specify
17317 that directory as part of Emacs's @code{load-path}.  Then, when Emacs
17318 loads a file, it will search that directory as well as its default
17319 list of directories.  (The default list is specified in @file{paths.h}
17320 when Emacs is built.)
17322 @need 1250
17323 The following command adds your @file{~/emacs} directory to the
17324 existing load path:
17326 @smallexample
17327 @group
17328 ;;; Emacs Load Path
17329 (setq load-path (cons "~/emacs" load-path))
17330 @end group
17331 @end smallexample
17333 Incidentally, @code{load-library} is an interactive interface to the
17334 @code{load} function.  The complete function looks like this:
17336 @findex load-library
17337 @smallexample
17338 @group
17339 (defun load-library (library)
17340   "Load the Emacs Lisp library named LIBRARY.
17341 This is an interface to the function `load'.  LIBRARY is searched
17342 for in `load-path', both with and without `load-suffixes' (as
17343 well as `load-file-rep-suffixes').
17345 See Info node `(emacs)Lisp Libraries' for more details.
17346 See `load-file' for a different interface to `load'."
17347   (interactive
17348    (list (completing-read "Load library: "
17349                           (apply-partially 'locate-file-completion-table
17350                                            load-path
17351                                            (get-load-suffixes)))))
17352   (load library))
17353 @end group
17354 @end smallexample
17356 The name of the function, @code{load-library}, comes from the use of
17357 ``library'' as a conventional synonym for ``file''.  The source for the
17358 @code{load-library} command is in the @file{files.el} library.
17360 Another interactive command that does a slightly different job is
17361 @code{load-file}.  @xref{Lisp Libraries, , Libraries of Lisp Code for
17362 Emacs, emacs, The GNU Emacs Manual}, for information on the
17363 distinction between @code{load-library} and this command.
17365 @node Autoload
17366 @section Autoloading
17367 @findex autoload
17369 Instead of installing a function by loading the file that contains it,
17370 or by evaluating the function definition, you can make the function
17371 available but not actually install it until it is first called.  This
17372 is called @dfn{autoloading}.
17374 When you execute an autoloaded function, Emacs automatically evaluates
17375 the file that contains the definition, and then calls the function.
17377 Emacs starts quicker with autoloaded functions, since their libraries
17378 are not loaded right away; but you need to wait a moment when you
17379 first use such a function, while its containing file is evaluated.
17381 Rarely used functions are frequently autoloaded.  The
17382 @file{loaddefs.el} library contains thousands of autoloaded functions,
17383 from @code{5x5} to @code{zone}.  Of course, you may
17384 come to use a rare function frequently.  When you do, you should
17385 load that function's file with a @code{load} expression in your
17386 @file{.emacs} file.
17388 In my @file{.emacs} file, I load 14 libraries that contain functions
17389 that would otherwise be autoloaded.  (Actually, it would have been
17390 better to include these files in my dumped Emacs, but I forgot.
17391 @xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17392 Reference Manual}, and the @file{INSTALL} file for more about
17393 dumping.)
17395 You may also want to include autoloaded expressions in your @file{.emacs}
17396 file.  @code{autoload} is a built-in function that takes up to five
17397 arguments, the final three of which are optional.  The first argument
17398 is the name of the function to be autoloaded; the second is the name
17399 of the file to be loaded.  The third argument is documentation for the
17400 function, and the fourth tells whether the function can be called
17401 interactively.  The fifth argument tells what type of
17402 object---@code{autoload} can handle a keymap or macro as well as a
17403 function (the default is a function).
17405 @need 800
17406 Here is a typical example:
17408 @smallexample
17409 @group
17410 (autoload 'html-helper-mode
17411   "html-helper-mode" "Edit HTML documents" t)
17412 @end group
17413 @end smallexample
17415 @noindent
17416 (@code{html-helper-mode} is an older alternative to @code{html-mode},
17417 which is a standard part of the distribution.)
17419 @noindent
17420 This expression autoloads the @code{html-helper-mode} function.  It
17421 takes it from the @file{html-helper-mode.el} file (or from the byte
17422 compiled version @file{html-helper-mode.elc}, if that exists.)  The
17423 file must be located in a directory specified by @code{load-path}.
17424 The documentation says that this is a mode to help you edit documents
17425 written in the HyperText Markup Language.  You can call this mode
17426 interactively by typing @kbd{M-x html-helper-mode}.  (You need to
17427 duplicate the function's regular documentation in the autoload
17428 expression because the regular function is not yet loaded, so its
17429 documentation is not available.)
17431 @xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
17432 Manual}, for more information.
17434 @node Simple Extension
17435 @section A Simple Extension: @code{line-to-top-of-window}
17436 @findex line-to-top-of-window
17437 @cindex Simple extension in @file{.emacs} file
17439 Here is a simple extension to Emacs that moves the line point is on to
17440 the top of the window.  I use this all the time, to make text easier
17441 to read.
17443 You can put the following code into a separate file and then load it
17444 from your @file{.emacs} file, or you can include it within your
17445 @file{.emacs} file.
17447 @need 1250
17448 Here is the definition:
17450 @smallexample
17451 @group
17452 ;;; Line to top of window;
17453 ;;; replace three keystroke sequence  C-u 0 C-l
17454 (defun line-to-top-of-window ()
17455   "Move the line point is on to top of window."
17456   (interactive)
17457   (recenter 0))
17458 @end group
17459 @end smallexample
17461 @need 1250
17462 Now for the keybinding.
17464 Nowadays, function keys as well as mouse button events and
17465 non-@sc{ascii} characters are written within square brackets, without
17466 quotation marks.  (In Emacs version 18 and before, you had to write
17467 different function key bindings for each different make of terminal.)
17469 I bind @code{line-to-top-of-window} to my @key{F6} function key like
17470 this:
17472 @smallexample
17473 (global-set-key [f6] 'line-to-top-of-window)
17474 @end smallexample
17476 For more information, see @ref{Init Rebinding, , Rebinding Keys in
17477 Your Init File, emacs, The GNU Emacs Manual}.
17479 @cindex Conditional 'twixt two versions of Emacs
17480 @cindex Version of Emacs, choosing
17481 @cindex Emacs version, choosing
17482 If you run two versions of GNU Emacs, such as versions 22 and 23, and
17483 use one @file{.emacs} file, you can select which code to evaluate with
17484 the following conditional:
17486 @smallexample
17487 @group
17488 (cond
17489  ((= 22 emacs-major-version)
17490   ;; evaluate version 22 code
17491   ( @dots{} ))
17492  ((= 23 emacs-major-version)
17493   ;; evaluate version 23 code
17494   ( @dots{} )))
17495 @end group
17496 @end smallexample
17498 For example, recent versions blink
17499 their cursors by default.  I hate such blinking, as well as other
17500 features, so I placed the following in my @file{.emacs}
17501 file@footnote{When I start instances of Emacs that do not load my
17502 @file{.emacs} file or any site file, I also turn off blinking:
17504 @smallexample
17505 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
17507 @exdent Or nowadays, using an even more sophisticated set of options,
17509 emacs -Q -D
17510 @end smallexample
17513 @smallexample
17514 @group
17515 (when (>= emacs-major-version 21)
17516   (blink-cursor-mode 0)
17517   ;; Insert newline when you press 'C-n' (next-line)
17518   ;; at the end of the buffer
17519   (setq next-line-add-newlines t)
17520 @end group
17521 @group
17522   ;; Turn on image viewing
17523   (auto-image-file-mode t)
17524 @end group
17525 @group
17526   ;; Turn on menu bar (this bar has text)
17527   ;; (Use numeric argument to turn on)
17528   (menu-bar-mode 1)
17529 @end group
17530 @group
17531   ;; Turn off tool bar (this bar has icons)
17532   ;; (Use numeric argument to turn on)
17533   (tool-bar-mode nil)
17534 @end group
17535 @group
17536   ;; Turn off tooltip mode for tool bar
17537   ;; (This mode causes icon explanations to pop up)
17538   ;; (Use numeric argument to turn on)
17539   (tooltip-mode nil)
17540   ;; If tooltips turned on, make tips appear promptly
17541   (setq tooltip-delay 0.1)  ; default is 0.7 second
17542    )
17543 @end group
17544 @end smallexample
17546 @node X11 Colors
17547 @section X11 Colors
17549 You can specify colors when you use Emacs with the MIT X Windowing
17550 system.
17552 I dislike the default colors and specify my own.
17554 @need 1250
17555 Here are the expressions in my @file{.emacs}
17556 file that set values:
17558 @smallexample
17559 @group
17560 ;; Set cursor color
17561 (set-cursor-color "white")
17563 ;; Set mouse color
17564 (set-mouse-color "white")
17566 ;; Set foreground and background
17567 (set-foreground-color "white")
17568 (set-background-color "darkblue")
17569 @end group
17571 @group
17572 ;;; Set highlighting colors for isearch and drag
17573 (set-face-foreground 'highlight "white")
17574 (set-face-background 'highlight "blue")
17575 @end group
17577 @group
17578 (set-face-foreground 'region "cyan")
17579 (set-face-background 'region "blue")
17580 @end group
17582 @group
17583 (set-face-foreground 'secondary-selection "skyblue")
17584 (set-face-background 'secondary-selection "darkblue")
17585 @end group
17587 @group
17588 ;; Set calendar highlighting colors
17589 (with-eval-after-load 'calendar
17590   (set-face-foreground 'diary   "skyblue")
17591   (set-face-background 'holiday "slate blue")
17592   (set-face-foreground 'holiday "white"))
17593 @end group
17594 @end smallexample
17596 The various shades of blue soothe my eye and prevent me from seeing
17597 the screen flicker.
17599 Alternatively, I could have set my specifications in various X
17600 initialization files.  For example, I could set the foreground,
17601 background, cursor, and pointer (i.e., mouse) colors in my
17602 @file{~/.Xresources} file like this:
17604 @smallexample
17605 @group
17606 Emacs*foreground:   white
17607 Emacs*background:   darkblue
17608 Emacs*cursorColor:  white
17609 Emacs*pointerColor: white
17610 @end group
17611 @end smallexample
17613 In any event, since it is not part of Emacs, I set the root color of
17614 my X window in my @file{~/.xinitrc} file, like this@footnote{I also
17615 run more modern window managers, such as Enlightenment, Gnome, or KDE;
17616 in those cases, I often specify an image rather than a plain color.}:
17618 @smallexample
17619 xsetroot -solid Navy -fg white &
17620 @end smallexample
17622 @need 1700
17623 @node Miscellaneous
17624 @section Miscellaneous Settings for a @file{.emacs} File
17626 @need 1250
17627 Here are a few miscellaneous settings:
17628 @sp 1
17630 @itemize @minus
17631 @item
17632 Set the shape and color of the mouse cursor:
17634 @smallexample
17635 @group
17636 ; Cursor shapes are defined in
17637 ; '/usr/include/X11/cursorfont.h';
17638 ; for example, the 'target' cursor is number 128;
17639 ; the 'top_left_arrow' cursor is number 132.
17640 @end group
17642 @group
17643 (let ((mpointer (x-get-resource "*mpointer"
17644                                 "*emacs*mpointer")))
17645   ;; If you have not set your mouse pointer
17646   ;;     then set it, otherwise leave as is:
17647   (if (eq mpointer nil)
17648       (setq mpointer "132")) ; top_left_arrow
17649 @end group
17650 @group
17651   (setq x-pointer-shape (string-to-number mpointer))
17652   (set-mouse-color "white"))
17653 @end group
17654 @end smallexample
17656 @item
17657 Or you can set the values of a variety of features in an alist, like
17658 this:
17660 @smallexample
17661 @group
17662 (setq-default
17663  default-frame-alist
17664  '((cursor-color . "white")
17665    (mouse-color . "white")
17666    (foreground-color . "white")
17667    (background-color . "DodgerBlue4")
17668    ;; (cursor-type . bar)
17669    (cursor-type . box)
17670 @end group
17671 @group
17672    (tool-bar-lines . 0)
17673    (menu-bar-lines . 1)
17674    (width . 80)
17675    (height . 58)
17676    (font .
17677          "-Misc-Fixed-Medium-R-Normal--20-200-75-75-C-100-ISO8859-1")
17678    ))
17679 @end group
17680 @end smallexample
17682 @item
17683 Convert @kbd{@key{CTRL}-h} into @key{DEL} and @key{DEL}
17684 into @kbd{@key{CTRL}-h}.@*
17685 (Some older keyboards needed this, although I have not seen the
17686 problem recently.)
17688 @smallexample
17689 @group
17690 ;; Translate 'C-h' to <DEL>.
17691 ; (keyboard-translate ?\C-h ?\C-?)
17693 ;; Translate <DEL> to 'C-h'.
17694 (keyboard-translate ?\C-? ?\C-h)
17695 @end group
17696 @end smallexample
17698 @item Turn off a blinking cursor!
17700 @smallexample
17701 @group
17702 (if (fboundp 'blink-cursor-mode)
17703     (blink-cursor-mode -1))
17704 @end group
17705 @end smallexample
17707 @noindent
17708 or start GNU Emacs with the command @code{emacs -nbc}.
17710 @need 1250
17711 @item When using @command{grep}@*
17712 @samp{-i}@w{  }   Ignore case distinctions@*
17713 @samp{-n}@w{  }   Prefix each line of output with line number@*
17714 @samp{-H}@w{  }   Print the filename for each match.@*
17715 @samp{-e}@w{  }   Protect patterns beginning with a hyphen character, @samp{-}
17717 @smallexample
17718 (setq grep-command "grep -i -nH -e ")
17719 @end smallexample
17721 @ignore
17722 @c Evidently, no longer needed in GNU Emacs 22
17724 item Automatically uncompress compressed files when visiting them
17726 smallexample
17727 (load "uncompress")
17728 end smallexample
17730 @end ignore
17732 @item Find an existing buffer, even if it has a different name@*
17733 This avoids problems with symbolic links.
17735 @smallexample
17736 (setq find-file-existing-other-name t)
17737 @end smallexample
17739 @item Set your language environment and default input method
17741 @smallexample
17742 @group
17743 (set-language-environment "latin-1")
17744 ;; Remember you can enable or disable multilingual text input
17745 ;; with the @code{toggle-input-method'} (@kbd{C-\}) command
17746 (setq default-input-method "latin-1-prefix")
17747 @end group
17748 @end smallexample
17750 If you want to write with Chinese GB characters, set this instead:
17752 @smallexample
17753 @group
17754 (set-language-environment "Chinese-GB")
17755 (setq default-input-method "chinese-tonepy")
17756 @end group
17757 @end smallexample
17758 @end itemize
17760 @subsubheading Fixing Unpleasant Key Bindings
17761 @cindex Key bindings, fixing
17762 @cindex Bindings, key, fixing unpleasant
17764 Some systems bind keys unpleasantly.  Sometimes, for example, the
17765 @key{CTRL} key appears in an awkward spot rather than at the far left
17766 of the home row.
17768 Usually, when people fix these sorts of keybindings, they do not
17769 change their @file{~/.emacs} file.  Instead, they bind the proper keys
17770 on their consoles with the @code{loadkeys} or @code{install-keymap}
17771 commands in their boot script and then include @code{xmodmap} commands
17772 in their @file{.xinitrc} or @file{.Xsession} file for X Windows.
17774 @need 1250
17775 @noindent
17776 For a boot script:
17778 @smallexample
17779 @group
17780 loadkeys /usr/share/keymaps/i386/qwerty/emacs2.kmap.gz
17781 @exdent or
17782 install-keymap emacs2
17783 @end group
17784 @end smallexample
17786 @need 1250
17787 @noindent
17788 For a @file{.xinitrc} or @file{.Xsession} file when the @key{Caps
17789 Lock} key is at the far left of the home row:
17791 @smallexample
17792 @group
17793 # Bind the key labeled 'Caps Lock' to 'Control'
17794 # (Such a broken user interface suggests that keyboard manufacturers
17795 # think that computers are typewriters from 1885.)
17797 xmodmap -e "clear Lock"
17798 xmodmap -e "add Control = Caps_Lock"
17799 @end group
17800 @end smallexample
17802 @need 1250
17803 @noindent
17804 In a @file{.xinitrc} or @file{.Xsession} file, to convert an @key{ALT}
17805 key to a @key{META} key:
17807 @smallexample
17808 @group
17809 # Some ill designed keyboards have a key labeled ALT and no Meta
17810 xmodmap -e "keysym Alt_L = Meta_L Alt_L"
17811 @end group
17812 @end smallexample
17814 @need 1700
17815 @node Mode Line
17816 @section A Modified Mode Line
17817 @vindex mode-line-format
17818 @cindex Mode line format
17820 Finally, a feature I really like: a modified mode line.
17822 When I work over a network, I forget which machine I am using.  Also,
17823 I tend to I lose track of where I am, and which line point is on.
17825 So I reset my mode line to look like this:
17827 @smallexample
17828 -:-- foo.texi   rattlesnake:/home/bob/  Line 1  (Texinfo Fill) Top
17829 @end smallexample
17831 I am visiting a file called @file{foo.texi}, on my machine
17832 @file{rattlesnake} in my @file{/home/bob} buffer.  I am on line 1, in
17833 Texinfo mode, and am at the top of the buffer.
17835 @need 1200
17836 My @file{.emacs} file has a section that looks like this:
17838 @smallexample
17839 @group
17840 ;; Set a Mode Line that tells me which machine, which directory,
17841 ;; and which line I am on, plus the other customary information.
17842 (setq-default mode-line-format
17843  (quote
17844   (#("-" 0 1
17845      (help-echo
17846       "mouse-1: select window, mouse-2: delete others ..."))
17847    mode-line-mule-info
17848    mode-line-modified
17849    mode-line-frame-identification
17850    "    "
17851 @end group
17852 @group
17853    mode-line-buffer-identification
17854    "    "
17855    (:eval (substring
17856            (system-name) 0 (string-match "\\..+" (system-name))))
17857    ":"
17858    default-directory
17859    #(" " 0 1
17860      (help-echo
17861       "mouse-1: select window, mouse-2: delete others ..."))
17862    (line-number-mode " Line %l ")
17863    global-mode-string
17864 @end group
17865 @group
17866    #("   %[(" 0 6
17867      (help-echo
17868       "mouse-1: select window, mouse-2: delete others ..."))
17869    (:eval (mode-line-mode-name))
17870    mode-line-process
17871    minor-mode-alist
17872    #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
17873    ")%] "
17874    (-3 . "%P")
17875    ;;   "-%-"
17876    )))
17877 @end group
17878 @end smallexample
17880 @noindent
17881 Here, I redefine the default mode line.  Most of the parts are from
17882 the original; but I make a few changes.  I set the @emph{default} mode
17883 line format so as to permit various modes, such as Info, to override
17886 Many elements in the list are self-explanatory:
17887 @code{mode-line-modified} is a variable that tells whether the buffer
17888 has been modified, @code{mode-name} tells the name of the mode, and so
17889 on.  However, the format looks complicated because of two features we
17890 have not discussed.
17892 @cindex Properties, in mode line example
17893 The first string in the mode line is a dash or hyphen, @samp{-}.  In
17894 the old days, it would have been specified simply as @code{"-"}.  But
17895 nowadays, Emacs can add properties to a string, such as highlighting
17896 or, as in this case, a help feature.  If you place your mouse cursor
17897 over the hyphen, some help information appears (By default, you must
17898 wait seven-tenths of a second before the information appears.  You can
17899 change that timing by changing the value of @code{tooltip-delay}.)
17901 @need 1000
17902 The new string format has a special syntax:
17904 @smallexample
17905 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
17906 @end smallexample
17908 @noindent
17909 The @code{#(} begins a list.  The first element of the list is the
17910 string itself, just one @samp{-}.  The second and third
17911 elements specify the range over which the fourth element applies.  A
17912 range starts @emph{after} a character, so a zero means the range
17913 starts just before the first character; a 1 means that the range ends
17914 just after the first character.  The third element is the property for
17915 the range.  It consists of a property list,  a
17916 property name, in this case, @samp{help-echo}, followed by a value, in this
17917 case, a string.  The second, third, and fourth elements of this new
17918 string format can be repeated.
17920 @xref{Text Properties, , Text Properties, elisp, The GNU Emacs Lisp
17921 Reference Manual}, and see @ref{Mode Line Format, , Mode Line Format,
17922 elisp, The GNU Emacs Lisp Reference Manual}, for more information.
17924 @code{mode-line-buffer-identification}
17925 displays the current buffer name.  It is a list
17926 beginning @code{(#("%12b" 0 4 @dots{}}.
17927 The @code{#(} begins the list.
17929 The @samp{"%12b"} displays the current buffer name, using the
17930 @code{buffer-name} function with which we are familiar; the @samp{12}
17931 specifies the maximum number of characters that will be displayed.
17932 When a name has fewer characters, whitespace is added to fill out to
17933 this number.  (Buffer names can and often should be longer than 12
17934 characters; this length works well in a typical 80 column wide
17935 window.)
17937 @code{:eval} says to evaluate the following form and use the result as
17938 a string to display.  In this case, the expression displays the first
17939 component of the full system name.  The end of the first component is
17940 a @samp{.} (period), so I use the @code{string-match} function to
17941 tell me the length of the first component.  The substring from the
17942 zeroth character to that length is the name of the machine.
17944 @need 1250
17945 This is the expression:
17947 @smallexample
17948 @group
17949 (:eval (substring
17950         (system-name) 0 (string-match "\\..+" (system-name))))
17951 @end group
17952 @end smallexample
17954 @samp{%[} and @samp{%]} cause a pair of square brackets
17955 to appear for each recursive editing level.  @samp{%n} says ``Narrow''
17956 when narrowing is in effect.  @samp{%P} tells you the percentage of
17957 the buffer that is above the bottom of the window, or ``Top'', ``Bottom'',
17958 or ``All''.  (A lower case @samp{p} tell you the percentage above the
17959 @emph{top} of the window.)  @samp{%-} inserts enough dashes to fill
17960 out the line.
17962 Remember, you don't have to like Emacs to like it---your own
17963 Emacs can have different colors, different commands, and different
17964 keys than a default Emacs.
17966 On the other hand, if you want to bring up a plain out-of-the-box
17967 Emacs, with no customization, type:
17969 @smallexample
17970 emacs -q
17971 @end smallexample
17973 @noindent
17974 This will start an Emacs that does @emph{not} load your
17975 @file{~/.emacs} initialization file.  A plain, default Emacs.  Nothing
17976 more.
17978 @node Debugging
17979 @chapter Debugging
17980 @cindex debugging
17982 GNU Emacs has two debuggers, @code{debug} and @code{edebug}.  The
17983 first is built into the internals of Emacs and is always with you;
17984 the second requires that you instrument a function before you can use it.
17986 Both debuggers are described extensively in @ref{Debugging, ,
17987 Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
17988 In this chapter, I will walk through a short example of each.
17990 @menu
17991 * debug::                       How to use the built-in debugger.
17992 * debug-on-entry::              Start debugging when you call a function.
17993 * debug-on-quit::               Start debugging when you quit with @kbd{C-g}.
17994 * edebug::                      How to use Edebug, a source level debugger.
17995 * Debugging Exercises::
17996 @end menu
17998 @node debug
17999 @section @code{debug}
18000 @findex debug
18002 Suppose you have written a function definition that is intended to
18003 return the sum of the numbers 1 through a given number.  (This is the
18004 @code{triangle} function discussed earlier.  @xref{Decrementing
18005 Example, , Example with Decrementing Counter}, for a discussion.)
18006 @c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
18008 However, your function definition has a bug.  You have mistyped
18009 @samp{1=} for @samp{1-}.  Here is the broken definition:
18011 @findex triangle-bugged
18012 @smallexample
18013 @group
18014 (defun triangle-bugged (number)
18015   "Return sum of numbers 1 through NUMBER inclusive."
18016   (let ((total 0))
18017     (while (> number 0)
18018       (setq total (+ total number))
18019       (setq number (1= number)))      ; @r{Error here.}
18020     total))
18021 @end group
18022 @end smallexample
18024 If you are reading this in Info, you can evaluate this definition in
18025 the normal fashion.  You will see @code{triangle-bugged} appear in the
18026 echo area.
18028 @need 1250
18029 Now evaluate the @code{triangle-bugged} function with an
18030 argument of 4:
18032 @smallexample
18033 (triangle-bugged 4)
18034 @end smallexample
18036 @noindent
18037 In a recent GNU Emacs, you will create and enter a @file{*Backtrace*}
18038 buffer that says:
18040 @noindent
18041 @smallexample
18042 @group
18043 ---------- Buffer: *Backtrace* ----------
18044 Debugger entered--Lisp error: (void-function 1=)
18045   (1= number)
18046   (setq number (1= number))
18047   (while (> number 0) (setq total (+ total number))
18048         (setq number (1= number)))
18049   (let ((total 0)) (while (> number 0) (setq total ...)
18050     (setq number ...)) total)
18051   triangle-bugged(4)
18052 @end group
18053 @group
18054   eval((triangle-bugged 4))
18055   eval-last-sexp-1(nil)
18056   eval-last-sexp(nil)
18057   call-interactively(eval-last-sexp)
18058 ---------- Buffer: *Backtrace* ----------
18059 @end group
18060 @end smallexample
18062 @noindent
18063 (I have reformatted this example slightly; the debugger does not fold
18064 long lines.  As usual, you can quit the debugger by typing @kbd{q} in
18065 the @file{*Backtrace*} buffer.)
18067 In practice, for a bug as simple as this, the Lisp error line will
18068 tell you what you need to know to correct the definition.  The
18069 function @code{1=} is void.
18071 @ignore
18072 @need 800
18073 In GNU Emacs 20 and before, you will see:
18075 @smallexample
18076 Symbol's function definition is void:@: 1=
18077 @end smallexample
18079 @noindent
18080 which has the same meaning as the @file{*Backtrace*} buffer line in
18081 version 21.
18082 @end ignore
18084 However, suppose you are not quite certain what is going on?
18085 You can read the complete backtrace.
18087 In this case, you need to run a recent GNU Emacs, which automatically
18088 starts the debugger that puts you in the @file{*Backtrace*} buffer; or
18089 else, you need to start the debugger manually as described below.
18091 Read the @file{*Backtrace*} buffer from the bottom up; it tells you
18092 what Emacs did that led to the error.  Emacs made an interactive call
18093 to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
18094 of the @code{triangle-bugged} expression.  Each line above tells you
18095 what the Lisp interpreter evaluated next.
18097 @need 1250
18098 The third line from the top of the buffer is
18100 @smallexample
18101 (setq number (1= number))
18102 @end smallexample
18104 @noindent
18105 Emacs tried to evaluate this expression; in order to do so, it tried
18106 to evaluate the inner expression shown on the second line from the
18107 top:
18109 @smallexample
18110 (1= number)
18111 @end smallexample
18113 @need 1250
18114 @noindent
18115 This is where the error occurred; as the top line says:
18117 @smallexample
18118 Debugger entered--Lisp error: (void-function 1=)
18119 @end smallexample
18121 @noindent
18122 You can correct the mistake, re-evaluate the function definition, and
18123 then run your test again.
18125 @node debug-on-entry
18126 @section @code{debug-on-entry}
18127 @findex debug-on-entry
18129 A recent GNU Emacs starts the debugger automatically when your
18130 function has an error.
18132 @ignore
18133 GNU Emacs version 20 and before did not; it simply
18134 presented you with an error message.  You had to start the debugger
18135 manually.
18136 @end ignore
18138 Incidentally, you can start the debugger manually for all versions of
18139 Emacs; the advantage is that the debugger runs even if you do not have
18140 a bug in your code.  Sometimes your code will be free of bugs!
18142 You can enter the debugger when you call the function by calling
18143 @code{debug-on-entry}.
18145 @need 1250
18146 @noindent
18147 Type:
18149 @smallexample
18150 M-x debug-on-entry RET triangle-bugged RET
18151 @end smallexample
18153 @need 1250
18154 @noindent
18155 Now, evaluate the following:
18157 @smallexample
18158 (triangle-bugged 5)
18159 @end smallexample
18161 @noindent
18162 All versions of Emacs will create a @file{*Backtrace*} buffer and tell
18163 you that it is beginning to evaluate the @code{triangle-bugged}
18164 function:
18166 @smallexample
18167 @group
18168 ---------- Buffer: *Backtrace* ----------
18169 Debugger entered--entering a function:
18170 * triangle-bugged(5)
18171   eval((triangle-bugged 5))
18172 @end group
18173 @group
18174   eval-last-sexp-1(nil)
18175   eval-last-sexp(nil)
18176   call-interactively(eval-last-sexp)
18177 ---------- Buffer: *Backtrace* ----------
18178 @end group
18179 @end smallexample
18181 In the @file{*Backtrace*} buffer, type @kbd{d}.  Emacs will evaluate
18182 the first expression in @code{triangle-bugged}; the buffer will look
18183 like this:
18185 @smallexample
18186 @group
18187 ---------- Buffer: *Backtrace* ----------
18188 Debugger entered--beginning evaluation of function call form:
18189 * (let ((total 0)) (while (> number 0) (setq total ...)
18190         (setq number ...)) total)
18191 * triangle-bugged(5)
18192   eval((triangle-bugged 5))
18193 @end group
18194 @group
18195   eval-last-sexp-1(nil)
18196   eval-last-sexp(nil)
18197   call-interactively(eval-last-sexp)
18198 ---------- Buffer: *Backtrace* ----------
18199 @end group
18200 @end smallexample
18202 @noindent
18203 Now, type @kbd{d} again, eight times, slowly.  Each time you type
18204 @kbd{d}, Emacs will evaluate another expression in the function
18205 definition.
18207 @need 1750
18208 Eventually, the buffer will look like this:
18210 @smallexample
18211 @group
18212 ---------- Buffer: *Backtrace* ----------
18213 Debugger entered--beginning evaluation of function call form:
18214 * (setq number (1= number))
18215 * (while (> number 0) (setq total (+ total number))
18216         (setq number (1= number)))
18217 @group
18218 @end group
18219 * (let ((total 0)) (while (> number 0) (setq total ...)
18220         (setq number ...)) total)
18221 * triangle-bugged(5)
18222   eval((triangle-bugged 5))
18223 @group
18224 @end group
18225   eval-last-sexp-1(nil)
18226   eval-last-sexp(nil)
18227   call-interactively(eval-last-sexp)
18228 ---------- Buffer: *Backtrace* ----------
18229 @end group
18230 @end smallexample
18232 @need 1500
18233 @noindent
18234 Finally, after you type @kbd{d} two more times, Emacs will reach the
18235 error, and the top two lines of the @file{*Backtrace*} buffer will look
18236 like this:
18238 @smallexample
18239 @group
18240 ---------- Buffer: *Backtrace* ----------
18241 Debugger entered--Lisp error: (void-function 1=)
18242 * (1= number)
18243 @dots{}
18244 ---------- Buffer: *Backtrace* ----------
18245 @end group
18246 @end smallexample
18248 By typing @kbd{d}, you were able to step through the function.
18250 You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
18251 quits the trace, but does not cancel @code{debug-on-entry}.
18253 @findex cancel-debug-on-entry
18254 To cancel the effect of @code{debug-on-entry}, call
18255 @code{cancel-debug-on-entry} and the name of the function, like this:
18257 @smallexample
18258 M-x cancel-debug-on-entry RET triangle-bugged RET
18259 @end smallexample
18261 @noindent
18262 (If you are reading this in Info, cancel @code{debug-on-entry} now.)
18264 @node debug-on-quit
18265 @section @code{debug-on-quit} and @code{(debug)}
18267 In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
18268 there are two other ways to start @code{debug}.
18270 @findex debug-on-quit
18271 You can start @code{debug} whenever you type @kbd{C-g}
18272 (@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
18273 @code{t}.  This is useful for debugging infinite loops.
18275 @need 1500
18276 @cindex @code{(debug)} in code
18277 Or, you can insert a line that says @code{(debug)} into your code
18278 where you want the debugger to start, like this:
18280 @smallexample
18281 @group
18282 (defun triangle-bugged (number)
18283   "Return sum of numbers 1 through NUMBER inclusive."
18284   (let ((total 0))
18285     (while (> number 0)
18286       (setq total (+ total number))
18287       (debug)                         ; @r{Start debugger.}
18288       (setq number (1= number)))      ; @r{Error here.}
18289     total))
18290 @end group
18291 @end smallexample
18293 The @code{debug} function is described in detail in @ref{Debugger, ,
18294 The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
18296 @node edebug
18297 @section The @code{edebug} Source Level Debugger
18298 @cindex Source level debugger
18299 @findex edebug
18301 Edebug is a source level debugger.  Edebug normally displays the
18302 source of the code you are debugging, with an arrow at the left that
18303 shows which line you are currently executing.
18305 You can walk through the execution of a function, line by line, or run
18306 quickly until reaching a @dfn{breakpoint} where execution stops.
18308 Edebug is described in @ref{Edebug, , , elisp, The GNU Emacs
18309 Lisp Reference Manual}.
18311 @need 1250
18312 Here is a bugged function definition for @code{triangle-recursively}.
18313 @xref{Recursive triangle function, , Recursion in place of a counter},
18314 for a review of it.
18316 @smallexample
18317 @group
18318 (defun triangle-recursively-bugged (number)
18319   "Return sum of numbers 1 through NUMBER inclusive.
18320 Uses recursion."
18321   (if (= number 1)
18322       1
18323     (+ number
18324        (triangle-recursively-bugged
18325         (1= number)))))               ; @r{Error here.}
18326 @end group
18327 @end smallexample
18329 @noindent
18330 Normally, you would install this definition by positioning your cursor
18331 after the function's closing parenthesis and typing @kbd{C-x C-e}
18332 (@code{eval-last-sexp}) or else by positioning your cursor within the
18333 definition and typing @kbd{C-M-x} (@code{eval-defun}).  (By default,
18334 the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
18335 Interaction mode.)
18337 @need 1500
18338 However, to prepare this function definition for Edebug, you must
18339 first @dfn{instrument} the code using a different command.  You can do
18340 this by positioning your cursor within or just after the definition
18341 and typing
18343 @smallexample
18344 M-x edebug-defun RET
18345 @end smallexample
18347 @noindent
18348 This will cause Emacs to load Edebug automatically if it is not
18349 already loaded, and properly instrument the function.
18351 After instrumenting the function, place your cursor after the
18352 following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
18354 @smallexample
18355 (triangle-recursively-bugged 3)
18356 @end smallexample
18358 @noindent
18359 You will be jumped back to the source for
18360 @code{triangle-recursively-bugged} and the cursor positioned at the
18361 beginning of the @code{if} line of the function.  Also, you will see
18362 an arrowhead at the left hand side of that line.  The arrowhead marks
18363 the line where the function is executing.  (In the following examples,
18364 we show the arrowhead with @samp{=>}; in a windowing system, you may
18365 see the arrowhead as a solid triangle in the window fringe.)
18367 @smallexample
18368 =>@point{}(if (= number 1)
18369 @end smallexample
18371 @noindent
18372 @iftex
18373 In the example, the location of point is displayed with a star,
18374 @samp{@point{}} (in Info, it is displayed as @samp{-!-}).
18375 @end iftex
18376 @ifnottex
18377 In the example, the location of point is displayed as @samp{@point{}}
18378 (in a printed book, it is displayed with a five pointed star).
18379 @end ifnottex
18381 If you now press @key{SPC}, point will move to the next expression to
18382 be executed; the line will look like this:
18384 @smallexample
18385 =>(if @point{}(= number 1)
18386 @end smallexample
18388 @noindent
18389 As you continue to press @key{SPC}, point will move from expression to
18390 expression.  At the same time, whenever an expression returns a value,
18391 that value will be displayed in the echo area.  For example, after you
18392 move point past @code{number}, you will see the following:
18394 @smallexample
18395 Result: 3 (#o3, #x3, ?\C-c)
18396 @end smallexample
18398 @noindent
18399 This means the value of @code{number} is 3, which is octal three,
18400 hexadecimal three, and @sc{ascii} Control-C (the third letter of the
18401 alphabet, in case you need to know this information).
18403 You can continue moving through the code until you reach the line with
18404 the error.  Before evaluation, that line looks like this:
18406 @smallexample
18407 =>        @point{}(1= number)))))               ; @r{Error here.}
18408 @end smallexample
18410 @need 1250
18411 @noindent
18412 When you press @key{SPC} once again, you will produce an error message
18413 that says:
18415 @smallexample
18416 Symbol's function definition is void:@: 1=
18417 @end smallexample
18419 @noindent
18420 This is the bug.
18422 Press @kbd{q} to quit Edebug.
18424 To remove instrumentation from a function definition, simply
18425 re-evaluate it with a command that does not instrument it.
18426 For example, you could place your cursor after the definition's
18427 closing parenthesis and type @kbd{C-x C-e}.
18429 Edebug does a great deal more than walk with you through a function.
18430 You can set it so it races through on its own, stopping only at an
18431 error or at specified stopping points; you can cause it to display the
18432 changing values of various expressions; you can find out how many
18433 times a function is called, and more.
18435 Edebug is described in @ref{Edebug, , , elisp, The GNU Emacs
18436 Lisp Reference Manual}.
18438 @need 1500
18439 @node Debugging Exercises
18440 @section Debugging Exercises
18442 @itemize @bullet
18443 @item
18444 Install the @code{@value{COUNT-WORDS}} function and then cause it to
18445 enter the built-in debugger when you call it.  Run the command on a
18446 region containing two words.  You will need to press @kbd{d} a
18447 remarkable number of times.  On your system, is a hook called after
18448 the command finishes?  (For information on hooks, see @ref{Command
18449 Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
18450 Manual}.)
18452 @item
18453 Copy @code{@value{COUNT-WORDS}} into the @file{*scratch*} buffer,
18454 instrument the function for Edebug, and walk through its execution.
18455 The function does not need to have a bug, although you can introduce
18456 one if you wish.  If the function lacks a bug, the walk-through
18457 completes without problems.
18459 @item
18460 While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
18461 (The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.,
18462 @kbd{@key{CTRL}-x} followed by an upper case @kbd{X}; use this prefix
18463 for commands made outside of the Edebug debugging buffer.)
18465 @item
18466 In the Edebug debugging buffer, use the @kbd{p}
18467 (@code{edebug-bounce-point}) command to see where in the region the
18468 @code{@value{COUNT-WORDS}} is working.
18470 @item
18471 Move point to some spot further down the function and then type the
18472 @kbd{h} (@code{edebug-goto-here}) command to jump to that location.
18474 @item
18475 Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
18476 walk through the function on its own; use an upper case @kbd{T} for
18477 @code{edebug-Trace-fast-mode}.
18479 @item
18480 Set a breakpoint, then run Edebug in Trace mode until it reaches the
18481 stopping point.
18482 @end itemize
18484 @node Conclusion
18485 @chapter Conclusion
18487 We have now reached the end of this Introduction.  You have now
18488 learned enough about programming in Emacs Lisp to set values, to write
18489 simple @file{.emacs} files for yourself and your friends, and write
18490 simple customizations and extensions to Emacs.
18492 This is a place to stop.  Or, if you wish, you can now go onward, and
18493 teach yourself.
18495 You have learned some of the basic nuts and bolts of programming.  But
18496 only some.  There are a great many more brackets and hinges that are
18497 easy to use that we have not touched.
18499 A path you can follow right now lies among the sources to GNU Emacs
18500 and in
18501 @ifnotinfo
18502 @cite{The GNU Emacs Lisp Reference Manual}.
18503 @end ifnotinfo
18504 @ifinfo
18505 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
18506 Emacs Lisp Reference Manual}.
18507 @end ifinfo
18509 The Emacs Lisp sources are an adventure.  When you read the sources and
18510 come across a function or expression that is unfamiliar, you need to
18511 figure out or find out what it does.
18513 Go to the Reference Manual.  It is a thorough, complete, and fairly
18514 easy-to-read description of Emacs Lisp.  It is written not only for
18515 experts, but for people who know what you know.  (The @cite{Reference
18516 Manual} comes with the standard GNU Emacs distribution.  Like this
18517 introduction, it comes as a Texinfo source file, so you can read it
18518 on your computer and as a typeset, printed book.)
18520 Go to the other built-in help that is part of GNU Emacs: the built-in
18521 documentation for all functions and variables, and @code{find-tag},
18522 the program that takes you to sources.
18524 Here is an example of how I explore the sources.  Because of its name,
18525 @file{simple.el} is the file I looked at first, a long time ago.  As
18526 it happens some of the functions in @file{simple.el} are complicated,
18527 or at least look complicated at first sight.  The @code{open-line}
18528 function, for example, looks complicated.
18530 You may want to walk through this function slowly, as we did with the
18531 @code{forward-sentence} function.  (@xref{forward-sentence, The
18532 @code{forward-sentence} function}.)  Or you may want to skip that
18533 function and look at another, such as @code{split-line}.  You don't
18534 need to read all the functions.  According to
18535 @code{count-words-in-defun}, the @code{split-line} function contains
18536 102 words and symbols.
18538 Even though it is short, @code{split-line} contains  expressions
18539 we have not studied: @code{skip-chars-forward}, @code{indent-to},
18540 @code{current-column} and @code{insert-and-inherit}.
18542 Consider the @code{skip-chars-forward} function.
18543 In GNU Emacs, you can find out more about @code{skip-chars-forward} by
18544 typing @kbd{C-h f} (@code{describe-function}) and the name of the
18545 function.  This gives you the function documentation.
18547 You may be able to guess what is done by a well named function such as
18548 @code{indent-to}; or you can look it up, too.  Incidentally, the
18549 @code{describe-function} function itself is in @file{help.el}; it is
18550 one of those long, but decipherable functions.  You can look up
18551 @code{describe-function} using the @kbd{C-h f} command!
18553 In this instance, since the code is Lisp, the @file{*Help*} buffer
18554 contains the name of the library containing the function's source.
18555 You can put point over the name of the library and press the RET key,
18556 which in this situation is bound to @code{help-follow}, and be taken
18557 directly to the source, in the same way as @kbd{M-.}
18558 (@code{find-tag}).
18560 The definition for @code{describe-function} illustrates how to
18561 customize the @code{interactive} expression without using the standard
18562 character codes; and it shows how to create a temporary buffer.
18564 (The @code{indent-to} function is written in C rather than Emacs Lisp;
18565 it is a built-in function.  @code{help-follow} takes you to its
18566 source as does @code{find-tag}, when properly set up.)
18568 You can look at a function's source using @code{find-tag}, which is
18569 bound to @kbd{M-.}  Finally, you can find out what the Reference
18570 Manual has to say by visiting the manual in Info, and typing @kbd{i}
18571 (@code{Info-index}) and the name of the function, or by looking up the
18572 function in the index to a printed copy of the manual.
18574 Similarly, you can find out what is meant by
18575 @code{insert-and-inherit}.
18577 Other interesting source files include @file{paragraphs.el},
18578 @file{loaddefs.el}, and @file{loadup.el}.  The @file{paragraphs.el}
18579 file includes short, easily understood functions as well as longer
18580 ones.  The @file{loaddefs.el} file contains the many standard
18581 autoloads and many keymaps.  I have never looked at it all; only at
18582 parts.  @file{loadup.el} is the file that loads the standard parts of
18583 Emacs; it tells you a great deal about how Emacs is built.
18584 (@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
18585 Reference Manual}, for more about building.)
18587 As I said, you have learned some nuts and bolts; however, and very
18588 importantly, we have hardly touched major aspects of programming; I
18589 have said nothing about how to sort information, except to use the
18590 predefined @code{sort} function; I have said nothing about how to store
18591 information, except to use variables and lists; I have said nothing
18592 about how to write programs that write programs.  These are topics for
18593 another, and different kind of book, a different kind of learning.
18595 What you have done is learn enough for much practical work with GNU
18596 Emacs.  What you have done is get started.  This is the end of a
18597 beginning.
18599 @c ================ Appendix ================
18601 @node the-the
18602 @appendix The @code{the-the} Function
18603 @findex the-the
18604 @cindex Duplicated words function
18605 @cindex Words, duplicated
18607 Sometimes when you you write text, you duplicate words---as with ``you
18608 you'' near the beginning of this sentence.  I find that most
18609 frequently, I duplicate ``the''; hence, I call the function for
18610 detecting duplicated words, @code{the-the}.
18612 @need 1250
18613 As a first step, you could use the following regular expression to
18614 search for duplicates:
18616 @smallexample
18617 \\(\\w+[ \t\n]+\\)\\1
18618 @end smallexample
18620 @noindent
18621 This regexp matches one or more word-constituent characters followed
18622 by one or more spaces, tabs, or newlines.  However, it does not detect
18623 duplicated words on different lines, since the ending of the first
18624 word, the end of the line, is different from the ending of the second
18625 word, a space.  (For more information about regular expressions, see
18626 @ref{Regexp Search, , Regular Expression Searches}, as well as
18627 @ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
18628 Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
18629 The GNU Emacs Lisp Reference Manual}.)
18631 You might try searching just for duplicated word-constituent
18632 characters but that does not work since the pattern detects doubles
18633 such as the two occurrences of ``th'' in ``with the''.
18635 Another possible regexp searches for word-constituent characters
18636 followed by non-word-constituent characters, reduplicated.  Here,
18637 @w{@samp{\\w+}} matches one or more word-constituent characters and
18638 @w{@samp{\\W*}} matches zero or more non-word-constituent characters.
18640 @smallexample
18641 \\(\\(\\w+\\)\\W*\\)\\1
18642 @end smallexample
18644 @noindent
18645 Again, not useful.
18647 Here is the pattern that I use.  It is not perfect, but good enough.
18648 @w{@samp{\\b}} matches the empty string, provided it is at the beginning
18649 or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
18650 any characters that are @emph{not} an @@-sign, space, newline, or tab.
18652 @smallexample
18653 \\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
18654 @end smallexample
18656 One can write more complicated expressions, but I found that this
18657 expression is good enough, so I use it.
18659 Here is the @code{the-the} function, as I include it in my
18660 @file{.emacs} file, along with a handy global key binding:
18662 @smallexample
18663 @group
18664 (defun the-the ()
18665   "Search forward for for a duplicated word."
18666   (interactive)
18667   (message "Searching for for duplicated words ...")
18668   (push-mark)
18669 @end group
18670 @group
18671   ;; This regexp is not perfect
18672   ;; but is fairly good over all:
18673   (if (re-search-forward
18674        "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
18675       (message "Found duplicated word.")
18676     (message "End of buffer")))
18677 @end group
18679 @group
18680 ;; Bind 'the-the' to  C-c \
18681 (global-set-key "\C-c\\" 'the-the)
18682 @end group
18683 @end smallexample
18685 @sp 1
18686 Here is test text:
18688 @smallexample
18689 @group
18690 one two two three four five
18691 five six seven
18692 @end group
18693 @end smallexample
18695 You can substitute the other regular expressions shown above in the
18696 function definition and try each of them on this list.
18698 @node Kill Ring
18699 @appendix Handling the Kill Ring
18700 @cindex Kill ring handling
18701 @cindex Handling the kill ring
18702 @cindex Ring, making a list like a
18704 The kill ring is a list that is transformed into a ring by the
18705 workings of the @code{current-kill} function.  The @code{yank} and
18706 @code{yank-pop} commands use the @code{current-kill} function.
18708 This appendix describes the @code{current-kill} function as well as
18709 both the @code{yank} and the @code{yank-pop} commands, but first,
18710 consider the workings of the kill ring.
18712 @menu
18713 * What the Kill Ring Does::
18714 * current-kill::
18715 * yank::                        Paste a copy of a clipped element.
18716 * yank-pop::                    Insert element pointed to.
18717 * ring file::
18718 @end menu
18720 @ifnottex
18721 @node What the Kill Ring Does
18722 @unnumberedsec What the Kill Ring Does
18723 @end ifnottex
18725 @need 1250
18726 The kill ring has a default maximum length of sixty items; this number
18727 is too large for an explanation.  Instead, set it to four.  Please
18728 evaluate the following:
18730 @smallexample
18731 @group
18732 (setq old-kill-ring-max kill-ring-max)
18733 (setq kill-ring-max 4)
18734 @end group
18735 @end smallexample
18737 @noindent
18738 Then, please copy each line of the following indented example into the
18739 kill ring.  You may kill each line with @kbd{C-k} or mark it and copy
18740 it with @kbd{M-w}.
18742 @noindent
18743 (In a read-only buffer, such as the @file{*info*} buffer, the kill
18744 command, @kbd{C-k} (@code{kill-line}), will not remove the text,
18745 merely copy it to the kill ring.  However, your machine may beep at
18746 you.  Alternatively, for silence, you may copy the region of each line
18747 with the @kbd{M-w} (@code{kill-ring-save}) command.  You must mark
18748 each line for this command to succeed, but it does not matter at which
18749 end you put point or mark.)
18751 @need 1250
18752 @noindent
18753 Please invoke the calls in order, so that five elements attempt to
18754 fill the kill ring:
18756 @smallexample
18757 @group
18758 first some text
18759 second piece of text
18760 third line
18761 fourth line of text
18762 fifth bit of text
18763 @end group
18764 @end smallexample
18766 @need 1250
18767 @noindent
18768 Then find the value of @code{kill-ring} by evaluating
18770 @smallexample
18771 kill-ring
18772 @end smallexample
18774 @need 800
18775 @noindent
18776 It is:
18778 @smallexample
18779 @group
18780 ("fifth bit of text" "fourth line of text"
18781 "third line" "second piece of text")
18782 @end group
18783 @end smallexample
18785 @noindent
18786 The first element, @samp{first some text}, was dropped.
18788 @need 1250
18789 To return to the old value for the length of the kill ring, evaluate:
18791 @smallexample
18792 (setq kill-ring-max old-kill-ring-max)
18793 @end smallexample
18795 @node current-kill
18796 @appendixsec The @code{current-kill} Function
18797 @findex current-kill
18799 The @code{current-kill} function changes the element in the kill ring
18800 to which @code{kill-ring-yank-pointer} points.  (Also, the
18801 @code{kill-new} function sets @code{kill-ring-yank-pointer} to point
18802 to the latest element of the kill ring.  The @code{kill-new}
18803 function is used directly or indirectly by @code{kill-append},
18804 @code{copy-region-as-kill}, @code{kill-ring-save}, @code{kill-line},
18805 and @code{kill-region}.)
18807 @menu
18808 * Code for current-kill::
18809 * Understanding current-kill::
18810 @end menu
18812 @ifnottex
18813 @node Code for current-kill
18814 @unnumberedsubsec The code for @code{current-kill}
18815 @end ifnottex
18818 @need 1500
18819 The @code{current-kill} function is used by @code{yank} and by
18820 @code{yank-pop}.  Here is the code for @code{current-kill}:
18822 @smallexample
18823 @group
18824 (defun current-kill (n &optional do-not-move)
18825   "Rotate the yanking point by N places, and then return that kill.
18826 If N is zero and `interprogram-paste-function' is set to a
18827 function that returns a string or a list of strings, and if that
18828 function doesn't return nil, then that string (or list) is added
18829 to the front of the kill ring and the string (or first string in
18830 the list) is returned as the latest kill.
18831 @end group
18832 @group
18833 If N is not zero, and if `yank-pop-change-selection' is
18834 non-nil, use `interprogram-cut-function' to transfer the
18835 kill at the new yank point into the window system selection.
18836 @end group
18837 @group
18838 If optional arg DO-NOT-MOVE is non-nil, then don't actually
18839 move the yanking point; just return the Nth kill forward."
18841   (let ((interprogram-paste (and (= n 0)
18842                                  interprogram-paste-function
18843                                  (funcall interprogram-paste-function))))
18844 @end group
18845 @group
18846     (if interprogram-paste
18847         (progn
18848           ;; Disable the interprogram cut function when we add the new
18849           ;; text to the kill ring, so Emacs doesn't try to own the
18850           ;; selection, with identical text.
18851           (let ((interprogram-cut-function nil))
18852             (if (listp interprogram-paste)
18853               (mapc 'kill-new (nreverse interprogram-paste))
18854               (kill-new interprogram-paste)))
18855           (car kill-ring))
18856 @end group
18857 @group
18858       (or kill-ring (error "Kill ring is empty"))
18859       (let ((ARGth-kill-element
18860              (nthcdr (mod (- n (length kill-ring-yank-pointer))
18861                           (length kill-ring))
18862                      kill-ring)))
18863         (unless do-not-move
18864           (setq kill-ring-yank-pointer ARGth-kill-element)
18865           (when (and yank-pop-change-selection
18866                      (> n 0)
18867                      interprogram-cut-function)
18868             (funcall interprogram-cut-function (car ARGth-kill-element))))
18869         (car ARGth-kill-element)))))
18870 @end group
18871 @end smallexample
18873 Remember also that the @code{kill-new} function sets
18874 @code{kill-ring-yank-pointer} to the latest element of the kill
18875 ring, which means that all the functions that call it set the value
18876 indirectly: @code{kill-append}, @code{copy-region-as-kill},
18877 @code{kill-ring-save}, @code{kill-line}, and @code{kill-region}.
18879 @need 1500
18880 Here is the line in @code{kill-new}, which is explained in
18881 @ref{kill-new function, , The @code{kill-new} function}.
18883 @smallexample
18884 (setq kill-ring-yank-pointer kill-ring)
18885 @end smallexample
18887 @ifnottex
18888 @node Understanding current-kill
18889 @unnumberedsubsec @code{current-kill} in Outline
18890 @end ifnottex
18892 The @code{current-kill} function looks complex, but as usual, it can
18893 be understood by taking it apart piece by piece.  First look at it in
18894 skeletal form:
18896 @smallexample
18897 @group
18898 (defun current-kill (n &optional do-not-move)
18899   "Rotate the yanking point by N places, and then return that kill."
18900   (let @var{varlist}
18901     @var{body}@dots{})
18902 @end group
18903 @end smallexample
18905 This function takes two arguments, one of which is optional.  It has a
18906 documentation string.  It is @emph{not} interactive.
18908 @menu
18909 * Body of current-kill::
18910 * Digression concerning error::  How to mislead humans, but not computers.
18911 * Determining the Element::
18912 @end menu
18914 @ifnottex
18915 @node Body of current-kill
18916 @unnumberedsubsubsec The Body of @code{current-kill}
18917 @end ifnottex
18919 The body of the function definition is a @code{let} expression, which
18920 itself has a body as well as a @var{varlist}.
18922 The @code{let} expression declares a variable that will be only usable
18923 within the bounds of this function.  This variable is called
18924 @code{interprogram-paste} and is for copying to another program.  It
18925 is not for copying within this instance of GNU Emacs.  Most window
18926 systems provide a facility for interprogram pasting.  Sadly, that
18927 facility usually provides only for the last element.  Most windowing
18928 systems have not adopted a ring of many possibilities, even though
18929 Emacs has provided it for decades.
18931 The @code{if} expression has two parts, one if there exists
18932 @code{interprogram-paste} and one if not.
18934 @need 2000
18935 Let us consider the else-part of the @code{current-kill}
18936 function.  (The then-part uses the @code{kill-new} function, which
18937 we have already described.  @xref{kill-new function, , The
18938 @code{kill-new} function}.)
18940 @smallexample
18941 @group
18942 (or kill-ring (error "Kill ring is empty"))
18943 (let ((ARGth-kill-element
18944        (nthcdr (mod (- n (length kill-ring-yank-pointer))
18945                     (length kill-ring))
18946                kill-ring)))
18947   (or do-not-move
18948       (setq kill-ring-yank-pointer ARGth-kill-element))
18949   (car ARGth-kill-element))
18950 @end group
18951 @end smallexample
18953 @noindent
18954 The code first checks whether the kill ring has content; otherwise it
18955 signals an error.
18957 @need 1000
18958 Note that the @code{or} expression is very similar to testing length
18959 with an @code{if}:
18961 @findex zerop
18962 @findex error
18963 @smallexample
18964 @group
18965 (if (zerop (length kill-ring))          ; @r{if-part}
18966     (error "Kill ring is empty"))       ; @r{then-part}
18967   ;; No else-part
18968 @end group
18969 @end smallexample
18971 @noindent
18972 If there is not anything in the kill ring, its length must be zero and
18973 an error message sent to the user: @samp{Kill ring is empty}.  The
18974 @code{current-kill} function uses an @code{or} expression which is
18975 simpler.  But an @code{if} expression reminds us what goes on.
18977 This @code{if} expression uses the function @code{zerop} which returns
18978 true if the value it is testing is zero.  When @code{zerop} tests
18979 true, the then-part of the @code{if} is evaluated.  The then-part is a
18980 list starting with the function @code{error}, which is a function that
18981 is similar to the @code{message} function
18982 (@pxref{message, , The @code{message} Function}) in that
18983 it prints a one-line message in the echo area.  However, in addition
18984 to printing a message, @code{error} also stops evaluation of the
18985 function within which it is embedded.  This means that the rest of the
18986 function will not be evaluated if the length of the kill ring is zero.
18988 Then the @code{current-kill} function selects the element to return.
18989 The selection depends on the number of places that @code{current-kill}
18990 rotates and on where @code{kill-ring-yank-pointer} points.
18992 Next, either the optional @code{do-not-move} argument is true or the
18993 current value of @code{kill-ring-yank-pointer} is set to point to the
18994 list.  Finally, another expression returns the first element of the
18995 list even if the @code{do-not-move} argument is true.
18997 @ifnottex
18998 @node Digression concerning error
18999 @unnumberedsubsubsec Digression about the word ``error''
19000 @end ifnottex
19002 In my opinion, it is slightly misleading, at least to humans, to use
19003 the term ``error'' as the name of the @code{error} function.  A better
19004 term would be ``cancel''.  Strictly speaking, of course, you cannot
19005 point to, much less rotate a pointer to a list that has no length, so
19006 from the point of view of the computer, the word ``error'' is correct.
19007 But a human expects to attempt this sort of thing, if only to find out
19008 whether the kill ring is full or empty.  This is an act of
19009 exploration.
19011 From the human point of view, the act of exploration and discovery is
19012 not necessarily an error, and therefore should not be labeled as one,
19013 even in the bowels of a computer.  As it is, the code in Emacs implies
19014 that a human who is acting virtuously, by exploring his or her
19015 environment, is making an error.  This is bad.  Even though the computer
19016 takes the same steps as it does when there is an error, a term such as
19017 ``cancel'' would have a clearer connotation.
19019 @ifnottex
19020 @node Determining the Element
19021 @unnumberedsubsubsec Determining the Element
19022 @end ifnottex
19024 Among other actions, the else-part of the @code{if} expression sets
19025 the value of @code{kill-ring-yank-pointer} to
19026 @code{ARGth-kill-element} when the kill ring has something in it and
19027 the value of @code{do-not-move} is @code{nil}.
19029 @need 800
19030 The code looks like this:
19032 @smallexample
19033 @group
19034 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19035              (length kill-ring))
19036         kill-ring)))
19037 @end group
19038 @end smallexample
19040 This needs some examination.  Unless it is not supposed to move the
19041 pointer, the @code{current-kill} function changes where
19042 @code{kill-ring-yank-pointer} points.
19043 That is what the
19044 @w{@code{(setq kill-ring-yank-pointer ARGth-kill-element))}}
19045 expression does.  Also, clearly, @code{ARGth-kill-element} is being
19046 set to be equal to some @sc{cdr} of the kill ring, using the
19047 @code{nthcdr} function that is described in an earlier section.
19048 (@xref{copy-region-as-kill}.)  How does it do this?
19050 As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
19051 works by repeatedly taking the @sc{cdr} of a list---it takes the
19052 @sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
19054 @need 800
19055 The two following expressions produce the same result:
19057 @smallexample
19058 @group
19059 (setq kill-ring-yank-pointer (cdr kill-ring))
19061 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
19062 @end group
19063 @end smallexample
19065 However, the @code{nthcdr} expression is more complicated.  It uses
19066 the @code{mod} function to determine which @sc{cdr} to select.
19068 (You will remember to look at inner functions first; indeed, we will
19069 have to go inside the @code{mod}.)
19071 The @code{mod} function returns the value of its first argument modulo
19072 the second; that is to say, it returns the remainder after dividing
19073 the first argument by the second.  The value returned has the same
19074 sign as the second argument.
19076 @need 800
19077 Thus,
19079 @smallexample
19080 @group
19081 (mod 12 4)
19082   @result{} 0  ;; @r{because there is no remainder}
19083 (mod 13 4)
19084   @result{} 1
19085 @end group
19086 @end smallexample
19088 @need 1250
19089 In this case, the first argument is often smaller than the second.
19090 That is fine.
19092 @smallexample
19093 @group
19094 (mod 0 4)
19095   @result{} 0
19096 (mod 1 4)
19097   @result{} 1
19098 @end group
19099 @end smallexample
19101 We can guess what the @code{-} function does.  It is like @code{+} but
19102 subtracts instead of adds; the @code{-} function subtracts its second
19103 argument from its first.  Also, we already know what the @code{length}
19104 function does (@pxref{length}).  It returns the length of a list.
19106 And @code{n} is the name of the required argument to the
19107 @code{current-kill} function.
19109 @need 1250
19110 So when the first argument to @code{nthcdr} is zero, the @code{nthcdr}
19111 expression returns the whole list, as you can see by evaluating the
19112 following:
19114 @smallexample
19115 @group
19116 ;; kill-ring-yank-pointer @r{and} kill-ring @r{have a length of four}
19117 ;; @r{and} (mod (- 0 4) 4) @result{} 0
19118 (nthcdr (mod (- 0 4) 4)
19119         '("fourth line of text"
19120           "third line"
19121           "second piece of text"
19122           "first some text"))
19123 @end group
19124 @end smallexample
19126 @need 1250
19127 When the first argument to the @code{current-kill} function is one,
19128 the @code{nthcdr} expression returns the list without its first
19129 element.
19131 @smallexample
19132 @group
19133 (nthcdr (mod (- 1 4) 4)
19134         '("fourth line of text"
19135           "third line"
19136           "second piece of text"
19137           "first some text"))
19138 @end group
19139 @end smallexample
19141 @cindex @samp{global variable} defined
19142 @cindex @samp{variable, global}, defined
19143 Incidentally, both @code{kill-ring} and @code{kill-ring-yank-pointer}
19144 are @dfn{global variables}.  That means that any expression in Emacs
19145 Lisp can access them.  They are not like the local variables set by
19146 @code{let} or like the symbols in an argument list.
19147 Local variables can only be accessed
19148 within the @code{let} that defines them or the function that specifies
19149 them in an argument list (and within expressions called by them).
19151 @ignore
19152 @c texi2dvi fails when the name of the section is within ifnottex ...
19153 (@xref{Prevent confusion, , @code{let} Prevents Confusion}, and
19154 @ref{defun, , The @code{defun} Macro}.)
19155 @end ignore
19157 @node yank
19158 @appendixsec @code{yank}
19159 @findex yank
19161 After learning about @code{current-kill}, the code for the
19162 @code{yank} function is almost easy.
19164 The @code{yank} function does not use the
19165 @code{kill-ring-yank-pointer} variable directly.  It calls
19166 @code{insert-for-yank} which calls @code{current-kill} which sets the
19167 @code{kill-ring-yank-pointer} variable.
19169 @need 1250
19170 The code looks like this:
19172 @c in GNU Emacs 22
19173 @smallexample
19174 @group
19175 (defun yank (&optional arg)
19176   "Reinsert (\"paste\") the last stretch of killed text.
19177 More precisely, reinsert the stretch of killed text most recently
19178 killed OR yanked.  Put point at end, and set mark at beginning.
19179 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
19180 With argument N, reinsert the Nth most recently killed stretch of killed
19181 text.
19183 When this command inserts killed text into the buffer, it honors
19184 `yank-excluded-properties' and `yank-handler' as described in the
19185 doc string for `insert-for-yank-1', which see.
19187 See also the command `yank-pop' (\\[yank-pop])."
19188 @end group
19189 @group
19190   (interactive "*P")
19191   (setq yank-window-start (window-start))
19192   ;; If we don't get all the way thru, make last-command indicate that
19193   ;; for the following command.
19194   (setq this-command t)
19195   (push-mark (point))
19196 @end group
19197 @group
19198   (insert-for-yank (current-kill (cond
19199                                   ((listp arg) 0)
19200                                   ((eq arg '-) -2)
19201                                   (t (1- arg)))))
19202   (if (consp arg)
19203       ;; This is like exchange-point-and-mark, but doesn't activate the mark.
19204       ;; It is cleaner to avoid activation, even though the command
19205       ;; loop would deactivate the mark because we inserted text.
19206       (goto-char (prog1 (mark t)
19207                    (set-marker (mark-marker) (point) (current-buffer)))))
19208 @end group
19209 @group
19210   ;; If we do get all the way thru, make this-command indicate that.
19211   (if (eq this-command t)
19212       (setq this-command 'yank))
19213   nil)
19214 @end group
19215 @end smallexample
19217 The key expression is @code{insert-for-yank}, which inserts the string
19218 returned by @code{current-kill}, but removes some text properties from
19221 However, before getting to that expression, the function sets the value
19222 of @code{yank-window-start} to the position returned by the
19223 @code{(window-start)} expression, the position at which the display
19224 currently starts.  The @code{yank} function also sets
19225 @code{this-command} and pushes the mark.
19227 After it yanks the appropriate element, if the optional argument is a
19228 @sc{cons} rather than a number or nothing, it puts point at beginning
19229 of the yanked text and mark at its end.
19231 (The @code{prog1} function is like @code{progn} but returns the value
19232 of its first argument rather than the value of its last argument.  Its
19233 first argument is forced to return the buffer's mark as an integer.
19234 You can see the documentation for these functions by placing point
19235 over them in this buffer and then typing @kbd{C-h f}
19236 (@code{describe-function}) followed by a @kbd{RET}; the default is the
19237 function.)
19239 The last part of the function tells what to do when it succeeds.
19241 @node yank-pop
19242 @appendixsec @code{yank-pop}
19243 @findex yank-pop
19245 After understanding @code{yank} and @code{current-kill}, you know how
19246 to approach the @code{yank-pop} function.  Leaving out the
19247 documentation to save space, it looks like this:
19249 @c GNU Emacs 22
19250 @smallexample
19251 @group
19252 (defun yank-pop (&optional arg)
19253   "@dots{}"
19254   (interactive "*p")
19255   (if (not (eq last-command 'yank))
19256       (error "Previous command was not a yank"))
19257 @end group
19258 @group
19259   (setq this-command 'yank)
19260   (unless arg (setq arg 1))
19261   (let ((inhibit-read-only t)
19262         (before (< (point) (mark t))))
19263 @end group
19264 @group
19265     (if before
19266         (funcall (or yank-undo-function 'delete-region) (point) (mark t))
19267       (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
19268     (setq yank-undo-function nil)
19269 @end group
19270 @group
19271     (set-marker (mark-marker) (point) (current-buffer))
19272     (insert-for-yank (current-kill arg))
19273     ;; Set the window start back where it was in the yank command,
19274     ;; if possible.
19275     (set-window-start (selected-window) yank-window-start t)
19276 @end group
19277 @group
19278     (if before
19279         ;; This is like exchange-point-and-mark,
19280         ;;     but doesn't activate the mark.
19281         ;; It is cleaner to avoid activation, even though the command
19282         ;; loop would deactivate the mark because we inserted text.
19283         (goto-char (prog1 (mark t)
19284                      (set-marker (mark-marker)
19285                                  (point)
19286                                  (current-buffer))))))
19287   nil)
19288 @end group
19289 @end smallexample
19291 The function is interactive with a small @samp{p} so the prefix
19292 argument is processed and passed to the function.  The command can
19293 only be used after a previous yank; otherwise an error message is
19294 sent.  This check uses the variable @code{last-command} which is set
19295 by @code{yank} and is discussed elsewhere.
19296 (@xref{copy-region-as-kill}.)
19298 The @code{let} clause sets the variable @code{before} to true or false
19299 depending whether point is before or after mark and then the region
19300 between point and mark is deleted.  This is the region that was just
19301 inserted by the previous yank and it is this text that will be
19302 replaced.
19304 @code{funcall} calls its first argument as a function, passing
19305 remaining arguments to it.  The first argument is whatever the
19306 @code{or} expression returns.  The two remaining arguments are the
19307 positions of point and mark set by the preceding @code{yank} command.
19309 There is more, but that is the hardest part.
19311 @node ring file
19312 @appendixsec The @file{ring.el} File
19313 @cindex @file{ring.el} file
19315 Interestingly, GNU Emacs posses a file called @file{ring.el} that
19316 provides many of the features we just discussed.  But functions such
19317 as @code{kill-ring-yank-pointer} do not use this library, possibly
19318 because they were written earlier.
19320 @node Full Graph
19321 @appendix A Graph with Labeled Axes
19323 Printed axes help you understand a graph.  They convey scale.  In an
19324 earlier chapter (@pxref{Readying a Graph, ,  Readying a Graph}), we
19325 wrote the code to print the body of a graph.  Here we write the code
19326 for printing and labeling vertical and horizontal axes, along with the
19327 body itself.
19329 @menu
19330 * Labeled Example::
19331 * print-graph Varlist::         @code{let} expression in @code{print-graph}.
19332 * print-Y-axis::                Print a label for the vertical axis.
19333 * print-X-axis::                Print a horizontal label.
19334 * Print Whole Graph::           The function to print a complete graph.
19335 @end menu
19337 @ifnottex
19338 @node Labeled Example
19339 @unnumberedsec Labeled Example Graph
19340 @end ifnottex
19342 Since insertions fill a buffer to the right and below point, the new
19343 graph printing function should first print the Y or vertical axis,
19344 then the body of the graph, and finally the X or horizontal axis.
19345 This sequence lays out for us the contents of the function:
19347 @enumerate
19348 @item
19349 Set up code.
19351 @item
19352 Print Y axis.
19354 @item
19355 Print body of graph.
19357 @item
19358 Print X axis.
19359 @end enumerate
19361 @need 800
19362 Here is an example of how a finished graph should look:
19364 @smallexample
19365 @group
19366     10 -
19367                   *
19368                   *  *
19369                   *  **
19370                   *  ***
19371      5 -      *   *******
19372             * *** *******
19373             *************
19374           ***************
19375      1 - ****************
19376          |   |    |    |
19377          1   5   10   15
19378 @end group
19379 @end smallexample
19381 @noindent
19382 In this graph, both the vertical and the horizontal axes are labeled
19383 with numbers.  However, in some graphs, the horizontal axis is time
19384 and would be better labeled with months, like this:
19386 @smallexample
19387 @group
19388      5 -      *
19389             * ** *
19390             *******
19391           ********** **
19392      1 - **************
19393          |    ^      |
19394          Jan  June   Jan
19395 @end group
19396 @end smallexample
19398 Indeed, with a little thought, we can easily come up with a variety of
19399 vertical and horizontal labeling schemes.  Our task could become
19400 complicated.  But complications breed confusion.  Rather than permit
19401 this, it is better choose a simple labeling scheme for our first
19402 effort, and to modify or replace it later.
19404 @need 1200
19405 These considerations suggest the following outline for the
19406 @code{print-graph} function:
19408 @smallexample
19409 @group
19410 (defun print-graph (numbers-list)
19411   "@var{documentation}@dots{}"
19412   (let ((height  @dots{}
19413         @dots{}))
19414 @end group
19415 @group
19416     (print-Y-axis height @dots{} )
19417     (graph-body-print numbers-list)
19418     (print-X-axis @dots{} )))
19419 @end group
19420 @end smallexample
19422 We can work on each part of the @code{print-graph} function definition
19423 in turn.
19425 @node print-graph Varlist
19426 @appendixsec The @code{print-graph} Varlist
19427 @cindex @code{print-graph} varlist
19429 In writing the @code{print-graph} function, the first task is to write
19430 the varlist in the @code{let} expression.  (We will leave aside for the
19431 moment any thoughts about making the function interactive or about the
19432 contents of its documentation string.)
19434 The varlist should set several values.  Clearly, the top of the label
19435 for the vertical axis must be at least the height of the graph, which
19436 means that we must obtain this information here.  Note that the
19437 @code{print-graph-body} function also requires this information.  There
19438 is no reason to calculate the height of the graph in two different
19439 places, so we should change @code{print-graph-body} from the way we
19440 defined it earlier to take advantage of the calculation.
19442 Similarly, both the function for printing the X axis labels and the
19443 @code{print-graph-body} function need to learn the value of the width of
19444 each symbol.  We can perform the calculation here and change the
19445 definition for @code{print-graph-body} from the way we defined it in the
19446 previous chapter.
19448 The length of the label for the horizontal axis must be at least as long
19449 as the graph.  However, this information is used only in the function
19450 that prints the horizontal axis, so it does not need to be calculated here.
19452 These thoughts lead us directly to the following form for the varlist
19453 in the @code{let} for @code{print-graph}:
19455 @smallexample
19456 @group
19457 (let ((height (apply 'max numbers-list)) ; @r{First version.}
19458       (symbol-width (length graph-blank)))
19459 @end group
19460 @end smallexample
19462 @noindent
19463 As we shall see, this expression is not quite right.
19465 @need 2000
19466 @node print-Y-axis
19467 @appendixsec The @code{print-Y-axis} Function
19468 @cindex Axis, print vertical
19469 @cindex Y axis printing
19470 @cindex Vertical axis printing
19471 @cindex Print vertical axis
19473 The job of the @code{print-Y-axis} function is to print a label for
19474 the vertical axis that looks like this:
19476 @smallexample
19477 @group
19478     10 -
19483      5 -
19487      1 -
19488 @end group
19489 @end smallexample
19491 @noindent
19492 The function should be passed the height of the graph, and then should
19493 construct and insert the appropriate numbers and marks.
19495 @menu
19496 * print-Y-axis in Detail::
19497 * Height of label::             What height for the Y axis?
19498 * Compute a Remainder::         How to compute the remainder of a division.
19499 * Y Axis Element::              Construct a line for the Y axis.
19500 * Y-axis-column::               Generate a list of Y axis labels.
19501 * print-Y-axis Penultimate::    A not quite final version.
19502 @end menu
19504 @ifnottex
19505 @node print-Y-axis in Detail
19506 @unnumberedsubsec The @code{print-Y-axis} Function in Detail
19507 @end ifnottex
19509 It is easy enough to see in the figure what the Y axis label should
19510 look like; but to say in words, and then to write a function
19511 definition to do the job is another matter.  It is not quite true to
19512 say that we want a number and a tic every five lines: there are only
19513 three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
19514 but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
19515 and 9).  It is better to say that we want a number and a tic mark on
19516 the base line (number 1) and then that we want a number and a tic on
19517 the fifth line from the bottom and on every line that is a multiple of
19518 five.
19520 @ifnottex
19521 @node Height of label
19522 @unnumberedsubsec What height should the label be?
19523 @end ifnottex
19525 The next issue is what height the label should be?  Suppose the maximum
19526 height of tallest column of the graph is seven.  Should the highest
19527 label on the Y axis be @samp{5 -}, and should the graph stick up above
19528 the label?  Or should the highest label be @samp{7 -}, and mark the peak
19529 of the graph?  Or should the highest label be @code{10 -}, which is a
19530 multiple of five, and be higher than the topmost value of the graph?
19532 The latter form is preferred.  Most graphs are drawn within rectangles
19533 whose sides are an integral number of steps long---5, 10, 15, and so
19534 on for a step distance of five.  But as soon as we decide to use a
19535 step height for the vertical axis, we discover that the simple
19536 expression in the varlist for computing the height is wrong.  The
19537 expression is @code{(apply 'max numbers-list)}.  This returns the
19538 precise height, not the maximum height plus whatever is necessary to
19539 round up to the nearest multiple of five.  A more complex expression
19540 is required.
19542 As usual in cases like this, a complex problem becomes simpler if it is
19543 divided into several smaller problems.
19545 First, consider the case when the highest value of the graph is an
19546 integral multiple of five---when it is 5, 10, 15, or some higher
19547 multiple of five.  We can use this value as the Y axis height.
19549 A fairly simply way to determine whether a number is a multiple of
19550 five is to divide it by five and see if the division results in a
19551 remainder.  If there is no remainder, the number is a multiple of
19552 five.  Thus, seven divided by five has a remainder of two, and seven
19553 is not an integral multiple of five.  Put in slightly different
19554 language, more reminiscent of the classroom, five goes into seven
19555 once, with a remainder of two.  However, five goes into ten twice,
19556 with no remainder: ten is an integral multiple of five.
19558 @node Compute a Remainder
19559 @appendixsubsec Side Trip: Compute a Remainder
19561 @findex % @r{(remainder function)}
19562 @cindex Remainder function, @code{%}
19563 In Lisp, the function for computing a remainder is @code{%}.  The
19564 function returns the remainder of its first argument divided by its
19565 second argument.  As it happens, @code{%} is a function in Emacs Lisp
19566 that you cannot discover using @code{apropos}: you find nothing if you
19567 type @kbd{M-x apropos @key{RET} remainder @key{RET}}.  The only way to
19568 learn of the existence of @code{%} is to read about it in a book such
19569 as this or in the Emacs Lisp sources.
19571 You can try the @code{%} function by evaluating the following two
19572 expressions:
19574 @smallexample
19575 @group
19576 (% 7 5)
19578 (% 10 5)
19579 @end group
19580 @end smallexample
19582 @noindent
19583 The first expression returns 2 and the second expression returns 0.
19585 To test whether the returned value is zero or some other number, we
19586 can use the @code{zerop} function.  This function returns @code{t} if
19587 its argument, which must be a number, is zero.
19589 @smallexample
19590 @group
19591 (zerop (% 7 5))
19592      @result{} nil
19594 (zerop (% 10 5))
19595      @result{} t
19596 @end group
19597 @end smallexample
19599 Thus, the following expression will return @code{t} if the height
19600 of the graph is evenly divisible by five:
19602 @smallexample
19603 (zerop (% height 5))
19604 @end smallexample
19606 @noindent
19607 (The value of @code{height}, of course, can be found from @code{(apply
19608 'max numbers-list)}.)
19610 On the other hand, if the value of @code{height} is not a multiple of
19611 five, we want to reset the value to the next higher multiple of five.
19612 This is straightforward arithmetic using functions with which we are
19613 already familiar.  First, we divide the value of @code{height} by five
19614 to determine how many times five goes into the number.  Thus, five
19615 goes into twelve twice.  If we add one to this quotient and multiply by
19616 five, we will obtain the value of the next multiple of five that is
19617 larger than the height.  Five goes into twelve twice.  Add one to two,
19618 and multiply by five; the result is fifteen, which is the next multiple
19619 of five that is higher than twelve.  The Lisp expression for this is:
19621 @smallexample
19622 (* (1+ (/ height 5)) 5)
19623 @end smallexample
19625 @noindent
19626 For example, if you evaluate the following, the result is 15:
19628 @smallexample
19629 (* (1+ (/ 12 5)) 5)
19630 @end smallexample
19632 All through this discussion, we have been using 5 as the value
19633 for spacing labels on the Y axis; but we may want to use some other
19634 value.  For generality, we should replace 5 with a variable to
19635 which we can assign a value.  The best name I can think of for this
19636 variable is @code{Y-axis-label-spacing}.
19638 @need 1250
19639 Using this term, and an @code{if} expression, we produce the
19640 following:
19642 @smallexample
19643 @group
19644 (if (zerop (% height Y-axis-label-spacing))
19645     height
19646   ;; @r{else}
19647   (* (1+ (/ height Y-axis-label-spacing))
19648      Y-axis-label-spacing))
19649 @end group
19650 @end smallexample
19652 @noindent
19653 This expression returns the value of @code{height} itself if the height
19654 is an even multiple of the value of the @code{Y-axis-label-spacing} or
19655 else it computes and returns a value of @code{height} that is equal to
19656 the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19658 We can now include this expression in the @code{let} expression of the
19659 @code{print-graph} function (after first setting the value of
19660 @code{Y-axis-label-spacing}):
19661 @vindex Y-axis-label-spacing
19663 @smallexample
19664 @group
19665 (defvar Y-axis-label-spacing 5
19666   "Number of lines from one Y axis label to next.")
19667 @end group
19669 @group
19670 @dots{}
19671 (let* ((height (apply 'max numbers-list))
19672        (height-of-top-line
19673         (if (zerop (% height Y-axis-label-spacing))
19674             height
19675 @end group
19676 @group
19677           ;; @r{else}
19678           (* (1+ (/ height Y-axis-label-spacing))
19679              Y-axis-label-spacing)))
19680        (symbol-width (length graph-blank))))
19681 @dots{}
19682 @end group
19683 @end smallexample
19685 @noindent
19686 (Note use of the  @code{let*} function: the initial value of height is
19687 computed once by the @code{(apply 'max numbers-list)} expression and
19688 then the resulting value of  @code{height} is used to compute its
19689 final value.  @xref{fwd-para let, , The @code{let*} expression}, for
19690 more about @code{let*}.)
19692 @node Y Axis Element
19693 @appendixsubsec Construct a Y Axis Element
19695 When we print the vertical axis, we want to insert strings such as
19696 @w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19697 Moreover, we want the numbers and dashes to line up, so shorter
19698 numbers must be padded with leading spaces.  If some of the strings
19699 use two digit numbers, the strings with single digit numbers must
19700 include a leading blank space before the number.
19702 @findex number-to-string
19703 To figure out the length of the number, the @code{length} function is
19704 used.  But the @code{length} function works only with a string, not with
19705 a number.  So the number has to be converted from being a number to
19706 being a string.  This is done with the @code{number-to-string} function.
19707 For example,
19709 @smallexample
19710 @group
19711 (length (number-to-string 35))
19712      @result{} 2
19714 (length (number-to-string 100))
19715      @result{} 3
19716 @end group
19717 @end smallexample
19719 @noindent
19720 (@code{number-to-string} is also called @code{int-to-string}; you will
19721 see this alternative name in various sources.)
19723 In addition, in each label, each number is followed by a string such
19724 as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
19725 This variable is defined with @code{defvar}:
19727 @vindex Y-axis-tic
19728 @smallexample
19729 @group
19730 (defvar Y-axis-tic " - "
19731    "String that follows number in a Y axis label.")
19732 @end group
19733 @end smallexample
19735 The length of the Y label is the sum of the length of the Y axis tic
19736 mark and the length of the number of the top of the graph.
19738 @smallexample
19739 (length (concat (number-to-string height) Y-axis-tic)))
19740 @end smallexample
19742 This value will be calculated by the @code{print-graph} function in
19743 its varlist as @code{full-Y-label-width} and passed on.  (Note that we
19744 did not think to include this in the varlist when we first proposed it.)
19746 To make a complete vertical axis label, a tic mark is concatenated
19747 with a number; and the two together may be preceded by one or more
19748 spaces depending on how long the number is.  The label consists of
19749 three parts: the (optional) leading spaces, the number, and the tic
19750 mark.  The function is passed the value of the number for the specific
19751 row, and the value of the width of the top line, which is calculated
19752 (just once) by @code{print-graph}.
19754 @smallexample
19755 @group
19756 (defun Y-axis-element (number full-Y-label-width)
19757   "Construct a NUMBERed label element.
19758 A numbered element looks like this `  5 - ',
19759 and is padded as needed so all line up with
19760 the element for the largest number."
19761 @end group
19762 @group
19763   (let* ((leading-spaces
19764          (- full-Y-label-width
19765             (length
19766              (concat (number-to-string number)
19767                      Y-axis-tic)))))
19768 @end group
19769 @group
19770     (concat
19771      (make-string leading-spaces ? )
19772      (number-to-string number)
19773      Y-axis-tic)))
19774 @end group
19775 @end smallexample
19777 The @code{Y-axis-element} function concatenates together the leading
19778 spaces, if any; the number, as a string; and the tic mark.
19780 To figure out how many leading spaces the label will need, the
19781 function subtracts the actual length of the label---the length of the
19782 number plus the length of the tic mark---from the desired label width.
19784 @findex make-string
19785 Blank spaces are inserted using the @code{make-string} function.  This
19786 function takes two arguments: the first tells it how long the string
19787 will be and the second is a symbol for the character to insert, in a
19788 special format.  The format is a question mark followed by a blank
19789 space, like this, @samp{? }.  @xref{Character Type, , Character Type,
19790 elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
19791 syntax for characters.  (Of course, you might want to replace the
19792 blank space by some other character @dots{}  You know what to do.)
19794 The @code{number-to-string} function is used in the concatenation
19795 expression, to convert the number to a string that is concatenated
19796 with the leading spaces and the tic mark.
19798 @node Y-axis-column
19799 @appendixsubsec Create a Y Axis Column
19801 The preceding functions provide all the tools needed to construct a
19802 function that generates a list of numbered and blank strings to insert
19803 as the label for the vertical axis:
19805 @findex Y-axis-column
19806 @smallexample
19807 @group
19808 (defun Y-axis-column (height width-of-label)
19809   "Construct list of Y axis labels and blank strings.
19810 For HEIGHT of line above base and WIDTH-OF-LABEL."
19811   (let (Y-axis)
19812 @group
19813 @end group
19814     (while (> height 1)
19815       (if (zerop (% height Y-axis-label-spacing))
19816           ;; @r{Insert label.}
19817           (setq Y-axis
19818                 (cons
19819                  (Y-axis-element height width-of-label)
19820                  Y-axis))
19821 @group
19822 @end group
19823         ;; @r{Else, insert blanks.}
19824         (setq Y-axis
19825               (cons
19826                (make-string width-of-label ? )
19827                Y-axis)))
19828       (setq height (1- height)))
19829     ;; @r{Insert base line.}
19830     (setq Y-axis
19831           (cons (Y-axis-element 1 width-of-label) Y-axis))
19832     (nreverse Y-axis)))
19833 @end group
19834 @end smallexample
19836 In this function, we start with the value of @code{height} and
19837 repetitively subtract one from its value.  After each subtraction, we
19838 test to see whether the value is an integral multiple of the
19839 @code{Y-axis-label-spacing}.  If it is, we construct a numbered label
19840 using the @code{Y-axis-element} function; if not, we construct a
19841 blank label using the @code{make-string} function.  The base line
19842 consists of the number one followed by a tic mark.
19844 @need 2000
19845 @node print-Y-axis Penultimate
19846 @appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
19848 The list constructed by the @code{Y-axis-column} function is passed to
19849 the @code{print-Y-axis} function, which inserts the list as a column.
19851 @findex print-Y-axis
19852 @smallexample
19853 @group
19854 (defun print-Y-axis (height full-Y-label-width)
19855   "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
19856 Height must be the maximum height of the graph.
19857 Full width is the width of the highest label element."
19858 ;; Value of height and full-Y-label-width
19859 ;; are passed by print-graph.
19860 @end group
19861 @group
19862   (let ((start (point)))
19863     (insert-rectangle
19864      (Y-axis-column height full-Y-label-width))
19865     ;; @r{Place point ready for inserting graph.}
19866     (goto-char start)
19867     ;; @r{Move point forward by value of} full-Y-label-width
19868     (forward-char full-Y-label-width)))
19869 @end group
19870 @end smallexample
19872 The @code{print-Y-axis} uses the @code{insert-rectangle} function to
19873 insert the Y axis labels created by the @code{Y-axis-column} function.
19874 In addition, it places point at the correct position for printing the body of
19875 the graph.
19877 You can test @code{print-Y-axis}:
19879 @enumerate
19880 @item
19881 Install
19883 @smallexample
19884 @group
19885 Y-axis-label-spacing
19886 Y-axis-tic
19887 Y-axis-element
19888 Y-axis-column
19889 print-Y-axis
19890 @end group
19891 @end smallexample
19893 @item
19894 Copy the following expression:
19896 @smallexample
19897 (print-Y-axis 12 5)
19898 @end smallexample
19900 @item
19901 Switch to the @file{*scratch*} buffer and place the cursor where you
19902 want the axis labels to start.
19904 @item
19905 Type @kbd{M-:} (@code{eval-expression}).
19907 @item
19908 Yank the @code{graph-body-print} expression into the minibuffer
19909 with @kbd{C-y} (@code{yank)}.
19911 @item
19912 Press @key{RET} to evaluate the expression.
19913 @end enumerate
19915 Emacs will print labels vertically, the top one being @w{@samp{10 -@w{
19916 }}}.  (The @code{print-graph} function will pass the value of
19917 @code{height-of-top-line}, which in this case will end up as 15,
19918 thereby getting rid of what might appear as a bug.)
19920 @need 2000
19921 @node print-X-axis
19922 @appendixsec The @code{print-X-axis} Function
19923 @cindex Axis, print horizontal
19924 @cindex X axis printing
19925 @cindex Print horizontal axis
19926 @cindex Horizontal axis printing
19928 X axis labels are much like Y axis labels, except that the ticks are on a
19929 line above the numbers.  Labels should look like this:
19931 @smallexample
19932 @group
19933     |   |    |    |
19934     1   5   10   15
19935 @end group
19936 @end smallexample
19938 The first tic is under the first column of the graph and is preceded by
19939 several blank spaces.  These spaces provide room in rows above for the Y
19940 axis labels.  The second, third, fourth, and subsequent ticks are all
19941 spaced equally, according to the value of @code{X-axis-label-spacing}.
19943 The second row of the X axis consists of numbers, preceded by several
19944 blank spaces and also separated according to the value of the variable
19945 @code{X-axis-label-spacing}.
19947 The value of the variable @code{X-axis-label-spacing} should itself be
19948 measured in units of @code{symbol-width}, since you may want to change
19949 the width of the symbols that you are using to print the body of the
19950 graph without changing the ways the graph is labeled.
19952 @menu
19953 * Similarities differences::    Much like @code{print-Y-axis}, but not exactly.
19954 * X Axis Tic Marks::            Create tic marks for the horizontal axis.
19955 @end menu
19957 @ifnottex
19958 @node Similarities differences
19959 @unnumberedsubsec Similarities and differences
19960 @end ifnottex
19962 The @code{print-X-axis} function is constructed in more or less the
19963 same fashion as the @code{print-Y-axis} function except that it has
19964 two lines: the line of tic marks and the numbers.  We will write a
19965 separate function to print each line and then combine them within the
19966 @code{print-X-axis} function.
19968 This is a three step process:
19970 @enumerate
19971 @item
19972 Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
19974 @item
19975 Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
19977 @item
19978 Write a function to print both lines, the @code{print-X-axis} function,
19979 using @code{print-X-axis-tic-line} and
19980 @code{print-X-axis-numbered-line}.
19981 @end enumerate
19983 @node X Axis Tic Marks
19984 @appendixsubsec X Axis Tic Marks
19986 The first function should print the X axis tic marks.  We must specify
19987 the tic marks themselves and their spacing:
19989 @smallexample
19990 @group
19991 (defvar X-axis-label-spacing
19992   (if (boundp 'graph-blank)
19993       (* 5 (length graph-blank)) 5)
19994   "Number of units from one X axis label to next.")
19995 @end group
19996 @end smallexample
19998 @noindent
19999 (Note that the value of @code{graph-blank} is set by another
20000 @code{defvar}.  The @code{boundp} predicate checks whether it has
20001 already been set; @code{boundp} returns @code{nil} if it has not.  If
20002 @code{graph-blank} were unbound and we did not use this conditional
20003 construction, in a recent GNU Emacs, we would enter the debugger and
20004 see an error message saying @samp{@w{Debugger entered--Lisp error:}
20005 @w{(void-variable graph-blank)}}.)
20007 @need 1200
20008 Here is the @code{defvar} for @code{X-axis-tic-symbol}:
20010 @smallexample
20011 @group
20012 (defvar X-axis-tic-symbol "|"
20013   "String to insert to point to a column in X axis.")
20014 @end group
20015 @end smallexample
20017 @need 1250
20018 The goal is to make a line that looks like this:
20020 @smallexample
20021        |   |    |    |
20022 @end smallexample
20024 The first tic is indented so that it is under the first column, which is
20025 indented to provide space for the Y axis labels.
20027 A tic element consists of the blank spaces that stretch from one tic to
20028 the next plus a tic symbol.  The number of blanks is determined by the
20029 width of the tic symbol and the @code{X-axis-label-spacing}.
20031 @need 1250
20032 The code looks like this:
20034 @smallexample
20035 @group
20036 ;;; X-axis-tic-element
20037 @dots{}
20038 (concat
20039  (make-string
20040   ;; @r{Make a string of blanks.}
20041   (-  (* symbol-width X-axis-label-spacing)
20042       (length X-axis-tic-symbol))
20043   ? )
20044  ;; @r{Concatenate blanks with tic symbol.}
20045  X-axis-tic-symbol)
20046 @dots{}
20047 @end group
20048 @end smallexample
20050 Next, we determine how many blanks are needed to indent the first tic
20051 mark to the first column of the graph.  This uses the value of
20052 @code{full-Y-label-width} passed it by the @code{print-graph} function.
20054 @need 1250
20055 The code to make @code{X-axis-leading-spaces}
20056 looks like this:
20058 @smallexample
20059 @group
20060 ;; X-axis-leading-spaces
20061 @dots{}
20062 (make-string full-Y-label-width ? )
20063 @dots{}
20064 @end group
20065 @end smallexample
20067 We also need to determine the length of the horizontal axis, which is
20068 the length of the numbers list, and the number of ticks in the horizontal
20069 axis:
20071 @smallexample
20072 @group
20073 ;; X-length
20074 @dots{}
20075 (length numbers-list)
20076 @end group
20078 @group
20079 ;; tic-width
20080 @dots{}
20081 (* symbol-width X-axis-label-spacing)
20082 @end group
20084 @group
20085 ;; number-of-X-ticks
20086 (if (zerop (% (X-length tic-width)))
20087     (/ (X-length tic-width))
20088   (1+ (/ (X-length tic-width))))
20089 @end group
20090 @end smallexample
20092 @need 1250
20093 All this leads us directly to the function for printing the X axis tic line:
20095 @findex print-X-axis-tic-line
20096 @smallexample
20097 @group
20098 (defun print-X-axis-tic-line
20099   (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20100   "Print ticks for X axis."
20101     (insert X-axis-leading-spaces)
20102     (insert X-axis-tic-symbol)  ; @r{Under first column.}
20103 @end group
20104 @group
20105     ;; @r{Insert second tic in the right spot.}
20106     (insert (concat
20107              (make-string
20108               (-  (* symbol-width X-axis-label-spacing)
20109                   ;; @r{Insert white space up to second tic symbol.}
20110                   (* 2 (length X-axis-tic-symbol)))
20111               ? )
20112              X-axis-tic-symbol))
20113 @end group
20114 @group
20115     ;; @r{Insert remaining ticks.}
20116     (while (> number-of-X-tics 1)
20117       (insert X-axis-tic-element)
20118       (setq number-of-X-tics (1- number-of-X-tics))))
20119 @end group
20120 @end smallexample
20122 The line of numbers is equally straightforward:
20124 @need 1250
20125 First, we create a numbered element with blank spaces before each number:
20127 @findex X-axis-element
20128 @smallexample
20129 @group
20130 (defun X-axis-element (number)
20131   "Construct a numbered X axis element."
20132   (let ((leading-spaces
20133          (-  (* symbol-width X-axis-label-spacing)
20134              (length (number-to-string number)))))
20135     (concat (make-string leading-spaces ? )
20136             (number-to-string number))))
20137 @end group
20138 @end smallexample
20140 Next, we create the function to print the numbered line, starting with
20141 the number 1 under the first column:
20143 @findex print-X-axis-numbered-line
20144 @smallexample
20145 @group
20146 (defun print-X-axis-numbered-line
20147   (number-of-X-tics X-axis-leading-spaces)
20148   "Print line of X-axis numbers"
20149   (let ((number X-axis-label-spacing))
20150     (insert X-axis-leading-spaces)
20151     (insert "1")
20152 @end group
20153 @group
20154     (insert (concat
20155              (make-string
20156               ;; @r{Insert white space up to next number.}
20157               (-  (* symbol-width X-axis-label-spacing) 2)
20158               ? )
20159              (number-to-string number)))
20160 @end group
20161 @group
20162     ;; @r{Insert remaining numbers.}
20163     (setq number (+ number X-axis-label-spacing))
20164     (while (> number-of-X-tics 1)
20165       (insert (X-axis-element number))
20166       (setq number (+ number X-axis-label-spacing))
20167       (setq number-of-X-tics (1- number-of-X-tics)))))
20168 @end group
20169 @end smallexample
20171 Finally, we need to write the @code{print-X-axis} that uses
20172 @code{print-X-axis-tic-line} and
20173 @code{print-X-axis-numbered-line}.
20175 The function must determine the local values of the variables used by both
20176 @code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
20177 then it must call them.  Also, it must print the carriage return that
20178 separates the two lines.
20180 The function consists of a varlist that specifies five local variables,
20181 and calls to each of the two line printing functions:
20183 @findex print-X-axis
20184 @smallexample
20185 @group
20186 (defun print-X-axis (numbers-list)
20187   "Print X axis labels to length of NUMBERS-LIST."
20188   (let* ((leading-spaces
20189           (make-string full-Y-label-width ? ))
20190 @end group
20191 @group
20192        ;; symbol-width @r{is provided by} graph-body-print
20193        (tic-width (* symbol-width X-axis-label-spacing))
20194        (X-length (length numbers-list))
20195 @end group
20196 @group
20197        (X-tic
20198         (concat
20199          (make-string
20200 @end group
20201 @group
20202           ;; @r{Make a string of blanks.}
20203           (-  (* symbol-width X-axis-label-spacing)
20204               (length X-axis-tic-symbol))
20205           ? )
20206 @end group
20207 @group
20208          ;; @r{Concatenate blanks with tic symbol.}
20209          X-axis-tic-symbol))
20210 @end group
20211 @group
20212        (tic-number
20213         (if (zerop (% X-length tic-width))
20214             (/ X-length tic-width)
20215           (1+ (/ X-length tic-width)))))
20216 @end group
20217 @group
20218     (print-X-axis-tic-line tic-number leading-spaces X-tic)
20219     (insert "\n")
20220     (print-X-axis-numbered-line tic-number leading-spaces)))
20221 @end group
20222 @end smallexample
20224 @need 1250
20225 You can test @code{print-X-axis}:
20227 @enumerate
20228 @item
20229 Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
20230 @code{print-X-axis-tic-line}, as well as @code{X-axis-element},
20231 @code{print-X-axis-numbered-line}, and @code{print-X-axis}.
20233 @item
20234 Copy the following expression:
20236 @smallexample
20237 @group
20238 (progn
20239  (let ((full-Y-label-width 5)
20240        (symbol-width 1))
20241    (print-X-axis
20242     '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
20243 @end group
20244 @end smallexample
20246 @item
20247 Switch to the @file{*scratch*} buffer and place the cursor where you
20248 want the axis labels to start.
20250 @item
20251 Type @kbd{M-:} (@code{eval-expression}).
20253 @item
20254 Yank the test expression into the minibuffer
20255 with @kbd{C-y} (@code{yank)}.
20257 @item
20258 Press @key{RET} to evaluate the expression.
20259 @end enumerate
20261 @need 1250
20262 Emacs will print the horizontal axis like this:
20263 @sp 1
20265 @smallexample
20266 @group
20267      |   |    |    |    |
20268      1   5   10   15   20
20269 @end group
20270 @end smallexample
20272 @node Print Whole Graph
20273 @appendixsec Printing the Whole Graph
20274 @cindex Printing the whole graph
20275 @cindex Whole graph printing
20276 @cindex Graph, printing all
20278 Now we are nearly ready to print the whole graph.
20280 The function to print the graph with the proper labels follows the
20281 outline we created earlier (@pxref{Full Graph, , A Graph with Labeled
20282 Axes}), but with additions.
20284 @need 1250
20285 Here is the outline:
20287 @smallexample
20288 @group
20289 (defun print-graph (numbers-list)
20290   "@var{documentation}@dots{}"
20291   (let ((height  @dots{}
20292         @dots{}))
20293 @end group
20294 @group
20295     (print-Y-axis height @dots{} )
20296     (graph-body-print numbers-list)
20297     (print-X-axis @dots{} )))
20298 @end group
20299 @end smallexample
20301 @menu
20302 * The final version::           A few changes.
20303 * Test print-graph::            Run a short test.
20304 * Graphing words in defuns::    Executing the final code.
20305 * lambda::                      How to write an anonymous function.
20306 * mapcar::                      Apply a function to elements of a list.
20307 * Another Bug::                 Yet another bug @dots{} most insidious.
20308 * Final printed graph::         The graph itself!
20309 @end menu
20311 @ifnottex
20312 @node The final version
20313 @unnumberedsubsec Changes for the Final Version
20314 @end ifnottex
20316 The final version is different from what we planned in two ways:
20317 first, it contains additional values calculated once in the varlist;
20318 second, it carries an option to specify the labels' increment per row.
20319 This latter feature turns out to be essential; otherwise, a graph may
20320 have more rows than fit on a display or on a sheet of paper.
20322 @need 1500
20323 This new feature requires a change to the @code{Y-axis-column}
20324 function, to add @code{vertical-step} to it.  The function looks like
20325 this:
20327 @findex Y-axis-column @r{Final version.}
20328 @smallexample
20329 @group
20330 ;;; @r{Final version.}
20331 (defun Y-axis-column
20332   (height width-of-label &optional vertical-step)
20333   "Construct list of labels for Y axis.
20334 HEIGHT is maximum height of graph.
20335 WIDTH-OF-LABEL is maximum width of label.
20336 VERTICAL-STEP, an option, is a positive integer
20337 that specifies how much a Y axis label increments
20338 for each line.  For example, a step of 5 means
20339 that each line is five units of the graph."
20340 @end group
20341 @group
20342   (let (Y-axis
20343         (number-per-line (or vertical-step 1)))
20344     (while (> height 1)
20345       (if (zerop (% height Y-axis-label-spacing))
20346 @end group
20347 @group
20348           ;; @r{Insert label.}
20349           (setq Y-axis
20350                 (cons
20351                  (Y-axis-element
20352                   (* height number-per-line)
20353                   width-of-label)
20354                  Y-axis))
20355 @end group
20356 @group
20357         ;; @r{Else, insert blanks.}
20358         (setq Y-axis
20359               (cons
20360                (make-string width-of-label ? )
20361                Y-axis)))
20362       (setq height (1- height)))
20363 @end group
20364 @group
20365     ;; @r{Insert base line.}
20366     (setq Y-axis (cons (Y-axis-element
20367                         (or vertical-step 1)
20368                         width-of-label)
20369                        Y-axis))
20370     (nreverse Y-axis)))
20371 @end group
20372 @end smallexample
20374 The values for the maximum height of graph and the width of a symbol
20375 are computed by @code{print-graph} in its @code{let} expression; so
20376 @code{graph-body-print} must be changed to accept them.
20378 @findex graph-body-print @r{Final version.}
20379 @smallexample
20380 @group
20381 ;;; @r{Final version.}
20382 (defun graph-body-print (numbers-list height symbol-width)
20383   "Print a bar graph of the NUMBERS-LIST.
20384 The numbers-list consists of the Y-axis values.
20385 HEIGHT is maximum height of graph.
20386 SYMBOL-WIDTH is number of each column."
20387 @end group
20388 @group
20389   (let (from-position)
20390     (while numbers-list
20391       (setq from-position (point))
20392       (insert-rectangle
20393        (column-of-graph height (car numbers-list)))
20394       (goto-char from-position)
20395       (forward-char symbol-width)
20396 @end group
20397 @group
20398       ;; @r{Draw graph column by column.}
20399       (sit-for 0)
20400       (setq numbers-list (cdr numbers-list)))
20401     ;; @r{Place point for X axis labels.}
20402     (forward-line height)
20403     (insert "\n")))
20404 @end group
20405 @end smallexample
20407 @need 1250
20408 Finally, the code for the @code{print-graph} function:
20410 @findex print-graph @r{Final version.}
20411 @smallexample
20412 @group
20413 ;;; @r{Final version.}
20414 (defun print-graph
20415   (numbers-list &optional vertical-step)
20416   "Print labeled bar graph of the NUMBERS-LIST.
20417 The numbers-list consists of the Y-axis values.
20418 @end group
20420 @group
20421 Optionally, VERTICAL-STEP, a positive integer,
20422 specifies how much a Y axis label increments for
20423 each line.  For example, a step of 5 means that
20424 each row is five units."
20425 @end group
20426 @group
20427   (let* ((symbol-width (length graph-blank))
20428          ;; @code{height} @r{is both the largest number}
20429          ;; @r{and the number with the most digits.}
20430          (height (apply 'max numbers-list))
20431 @end group
20432 @group
20433          (height-of-top-line
20434           (if (zerop (% height Y-axis-label-spacing))
20435               height
20436             ;; @r{else}
20437             (* (1+ (/ height Y-axis-label-spacing))
20438                Y-axis-label-spacing)))
20439 @end group
20440 @group
20441          (vertical-step (or vertical-step 1))
20442          (full-Y-label-width
20443           (length
20444 @end group
20445 @group
20446            (concat
20447             (number-to-string
20448              (* height-of-top-line vertical-step))
20449             Y-axis-tic))))
20450 @end group
20452 @group
20453     (print-Y-axis
20454      height-of-top-line full-Y-label-width vertical-step)
20455 @end group
20456 @group
20457     (graph-body-print
20458      numbers-list height-of-top-line symbol-width)
20459     (print-X-axis numbers-list)))
20460 @end group
20461 @end smallexample
20463 @node Test print-graph
20464 @appendixsubsec Testing @code{print-graph}
20466 @need 1250
20467 We can test the @code{print-graph} function with a short list of numbers:
20469 @enumerate
20470 @item
20471 Install the final versions of @code{Y-axis-column},
20472 @code{graph-body-print}, and @code{print-graph} (in addition to the
20473 rest of the code.)
20475 @item
20476 Copy the following expression:
20478 @smallexample
20479 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
20480 @end smallexample
20482 @item
20483 Switch to the @file{*scratch*} buffer and place the cursor where you
20484 want the axis labels to start.
20486 @item
20487 Type @kbd{M-:} (@code{eval-expression}).
20489 @item
20490 Yank the test expression into the minibuffer
20491 with @kbd{C-y} (@code{yank)}.
20493 @item
20494 Press @key{RET} to evaluate the expression.
20495 @end enumerate
20497 @need 1250
20498 Emacs will print a graph that looks like this:
20500 @smallexample
20501 @group
20502 10 -
20505          *
20506         **   *
20507  5 -   ****  *
20508        **** ***
20509      * *********
20510      ************
20511  1 - *************
20513      |   |    |    |
20514      1   5   10   15
20515 @end group
20516 @end smallexample
20518 @need 1200
20519 On the other hand, if you pass @code{print-graph} a
20520 @code{vertical-step} value of 2, by evaluating this expression:
20522 @smallexample
20523 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
20524 @end smallexample
20526 @need 1250
20527 @noindent
20528 The graph looks like this:
20530 @smallexample
20531 @group
20532 20 -
20535          *
20536         **   *
20537 10 -   ****  *
20538        **** ***
20539      * *********
20540      ************
20541  2 - *************
20543      |   |    |    |
20544      1   5   10   15
20545 @end group
20546 @end smallexample
20548 @noindent
20549 (A question: is the @samp{2} on the bottom of the vertical axis a bug or a
20550 feature?  If you think it is a bug, and should be a @samp{1} instead, (or
20551 even a @samp{0}), you can modify the sources.)
20553 @node Graphing words in defuns
20554 @appendixsubsec Graphing Numbers of Words and Symbols
20556 Now for the graph for which all this code was written: a graph that
20557 shows how many function definitions contain fewer than 10 words and
20558 symbols, how many contain between 10 and 19 words and symbols, how
20559 many contain between 20 and 29 words and symbols, and so on.
20561 This is a multi-step process.  First make sure you have loaded all the
20562 requisite code.
20564 @need 1500
20565 It is a good idea to reset the value of @code{top-of-ranges} in case
20566 you have set it to some different value.  You can evaluate the
20567 following:
20569 @smallexample
20570 @group
20571 (setq top-of-ranges
20572  '(10  20  30  40  50
20573    60  70  80  90 100
20574   110 120 130 140 150
20575   160 170 180 190 200
20576   210 220 230 240 250
20577   260 270 280 290 300)
20578 @end group
20579 @end smallexample
20581 @noindent
20582 Next create a list of the number of words and symbols in each range.
20584 @need 1500
20585 @noindent
20586 Evaluate the following:
20588 @smallexample
20589 @group
20590 (setq list-for-graph
20591        (defuns-per-range
20592          (sort
20593           (recursive-lengths-list-many-files
20594            (directory-files "/usr/local/emacs/lisp"
20595                             t ".+el$"))
20596           '<)
20597          top-of-ranges))
20598 @end group
20599 @end smallexample
20601 @noindent
20602 On my old machine, this took about an hour.  It looked though 303 Lisp
20603 files in my copy of Emacs version 19.23.  After all that computing,
20604 the @code{list-for-graph} had this value:
20606 @smallexample
20607 @group
20608 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
20609 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20610 @end group
20611 @end smallexample
20613 @noindent
20614 This means that my copy of Emacs had 537 function definitions with
20615 fewer than 10 words or symbols in them, 1,027 function definitions
20616 with 10 to 19 words or symbols in them, 955 function definitions with
20617 20 to 29 words or symbols in them, and so on.
20619 Clearly, just by looking at this list we can see that most function
20620 definitions contain ten to thirty words and symbols.
20622 Now for printing.  We do @emph{not} want to print a graph that is
20623 1,030 lines high @dots{}  Instead, we should print a graph that is
20624 fewer than twenty-five lines high.  A graph that height can be
20625 displayed on almost any monitor, and easily printed on a sheet of paper.
20627 This means that each value in @code{list-for-graph} must be reduced to
20628 one-fiftieth its present value.
20630 Here is a short function to do just that, using two functions we have
20631 not yet seen, @code{mapcar} and @code{lambda}.
20633 @smallexample
20634 @group
20635 (defun one-fiftieth (full-range)
20636   "Return list, each number one-fiftieth of previous."
20637  (mapcar (lambda (arg) (/ arg 50)) full-range))
20638 @end group
20639 @end smallexample
20641 @node lambda
20642 @appendixsubsec A @code{lambda} Expression: Useful Anonymity
20643 @cindex Anonymous function
20644 @findex lambda
20646 @code{lambda} is the symbol for an anonymous function, a function
20647 without a name.  Every time you use an anonymous function, you need to
20648 include its whole body.
20650 @need 1250
20651 @noindent
20652 Thus,
20654 @smallexample
20655 (lambda (arg) (/ arg 50))
20656 @end smallexample
20658 @noindent
20659 is a function that returns the value resulting from
20660 dividing whatever is passed to it as @code{arg} by 50.
20662 @need 1200
20663 Earlier, for example, we had a function @code{multiply-by-seven}; it
20664 multiplied its argument by 7.  This function is similar, except it
20665 divides its argument by 50; and, it has no name.  The anonymous
20666 equivalent of @code{multiply-by-seven} is:
20668 @smallexample
20669 (lambda (number) (* 7 number))
20670 @end smallexample
20672 @noindent
20673 (@xref{defun, ,  The @code{defun} Macro}.)
20675 @need 1250
20676 @noindent
20677 If we want to multiply 3 by 7, we can write:
20679 @c clear print-postscript-figures
20680 @c lambda example diagram #1
20681 @ifnottex
20682 @smallexample
20683 @group
20684 (multiply-by-seven 3)
20685  \_______________/ ^
20686          |         |
20687       function  argument
20688 @end group
20689 @end smallexample
20690 @end ifnottex
20691 @ifset print-postscript-figures
20692 @sp 1
20693 @tex
20694 @center @image{lambda-1}
20695 @end tex
20696 @sp 1
20697 @end ifset
20698 @ifclear print-postscript-figures
20699 @iftex
20700 @smallexample
20701 @group
20702 (multiply-by-seven 3)
20703  \_______________/ ^
20704          |         |
20705       function  argument
20706 @end group
20707 @end smallexample
20708 @end iftex
20709 @end ifclear
20711 @noindent
20712 This expression returns 21.
20714 @need 1250
20715 @noindent
20716 Similarly, we can write:
20718 @c lambda example diagram #2
20719 @ifnottex
20720 @smallexample
20721 @group
20722 ((lambda (number) (* 7 number)) 3)
20723  \____________________________/ ^
20724                |                |
20725       anonymous function     argument
20726 @end group
20727 @end smallexample
20728 @end ifnottex
20729 @ifset print-postscript-figures
20730 @sp 1
20731 @tex
20732 @center @image{lambda-2}
20733 @end tex
20734 @sp 1
20735 @end ifset
20736 @ifclear print-postscript-figures
20737 @iftex
20738 @smallexample
20739 @group
20740 ((lambda (number) (* 7 number)) 3)
20741  \____________________________/ ^
20742                |                |
20743       anonymous function     argument
20744 @end group
20745 @end smallexample
20746 @end iftex
20747 @end ifclear
20749 @need 1250
20750 @noindent
20751 If we want to divide 100 by 50, we can write:
20753 @c lambda example diagram #3
20754 @ifnottex
20755 @smallexample
20756 @group
20757 ((lambda (arg) (/ arg 50)) 100)
20758  \______________________/  \_/
20759              |              |
20760     anonymous function   argument
20761 @end group
20762 @end smallexample
20763 @end ifnottex
20764 @ifset print-postscript-figures
20765 @sp 1
20766 @tex
20767 @center @image{lambda-3}
20768 @end tex
20769 @sp 1
20770 @end ifset
20771 @ifclear print-postscript-figures
20772 @iftex
20773 @smallexample
20774 @group
20775 ((lambda (arg) (/ arg 50)) 100)
20776  \______________________/  \_/
20777              |              |
20778     anonymous function   argument
20779 @end group
20780 @end smallexample
20781 @end iftex
20782 @end ifclear
20784 @noindent
20785 This expression returns 2.  The 100 is passed to the function, which
20786 divides that number by 50.
20788 @xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
20789 Lisp Reference Manual}, for more about @code{lambda}.  Lisp and lambda
20790 expressions derive from the Lambda Calculus.
20792 @node mapcar
20793 @appendixsubsec The @code{mapcar} Function
20794 @findex mapcar
20796 @code{mapcar} is a function that calls its first argument with each
20797 element of its second argument, in turn.  The second argument must be
20798 a sequence.
20800 The @samp{map} part of the name comes from the mathematical phrase,
20801 ``mapping over a domain'', meaning to apply a function to each of the
20802 elements in a domain.  The mathematical phrase is based on the
20803 metaphor of a surveyor walking, one step at a time, over an area he is
20804 mapping.  And @samp{car}, of course, comes from the Lisp notion of the
20805 first of a list.
20807 @need 1250
20808 @noindent
20809 For example,
20811 @smallexample
20812 @group
20813 (mapcar '1+ '(2 4 6))
20814      @result{} (3 5 7)
20815 @end group
20816 @end smallexample
20818 @noindent
20819 The function @code{1+} which adds one to its argument, is executed on
20820 @emph{each} element of the list, and a new list is returned.
20822 Contrast this with @code{apply}, which applies its first argument to
20823 all the remaining.
20824 (@xref{Readying a Graph, , Readying a Graph}, for a explanation of
20825 @code{apply}.)
20827 @need 1250
20828 In the definition of @code{one-fiftieth}, the first argument is the
20829 anonymous function:
20831 @smallexample
20832 (lambda (arg) (/ arg 50))
20833 @end smallexample
20835 @noindent
20836 and the second argument is @code{full-range}, which will be bound to
20837 @code{list-for-graph}.
20839 @need 1250
20840 The whole expression looks like this:
20842 @smallexample
20843 (mapcar (lambda (arg) (/ arg 50)) full-range))
20844 @end smallexample
20846 @xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
20847 Lisp Reference Manual}, for more about @code{mapcar}.
20849 Using the @code{one-fiftieth} function, we can generate a list in
20850 which each element is one-fiftieth the size of the corresponding
20851 element in @code{list-for-graph}.
20853 @smallexample
20854 @group
20855 (setq fiftieth-list-for-graph
20856       (one-fiftieth list-for-graph))
20857 @end group
20858 @end smallexample
20860 @need 1250
20861 The resulting list looks like this:
20863 @smallexample
20864 @group
20865 (10 20 19 15 11 9 6 5 4 3 3 2 2
20866 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
20867 @end group
20868 @end smallexample
20870 @noindent
20871 This, we are almost ready to print!  (We also notice the loss of
20872 information: many of the higher ranges are 0, meaning that fewer than
20873 50 defuns had that many words or symbols---but not necessarily meaning
20874 that none had that many words or symbols.)
20876 @node Another Bug
20877 @appendixsubsec Another Bug @dots{} Most Insidious
20878 @cindex Bug, most insidious type
20879 @cindex Insidious type of bug
20881 I said ``almost ready to print''!  Of course, there is a bug in the
20882 @code{print-graph} function @dots{}  It has a @code{vertical-step}
20883 option, but not a @code{horizontal-step} option.  The
20884 @code{top-of-range} scale goes from 10 to 300 by tens.  But the
20885 @code{print-graph} function will print only by ones.
20887 This is a classic example of what some consider the most insidious
20888 type of bug, the bug of omission.  This is not the kind of bug you can
20889 find by studying the code, for it is not in the code; it is an omitted
20890 feature.  Your best actions are to try your program early and often;
20891 and try to arrange, as much as you can, to write code that is easy to
20892 understand and easy to change.  Try to be aware, whenever you can,
20893 that whatever you have written, @emph{will} be rewritten, if not soon,
20894 eventually.  A hard maxim to follow.
20896 It is the @code{print-X-axis-numbered-line} function that needs the
20897 work; and then the @code{print-X-axis} and the @code{print-graph}
20898 functions need to be adapted.  Not much needs to be done; there is one
20899 nicety: the numbers ought to line up under the tic marks.  This takes
20900 a little thought.
20902 @need 1250
20903 Here is the corrected @code{print-X-axis-numbered-line}:
20905 @smallexample
20906 @group
20907 (defun print-X-axis-numbered-line
20908   (number-of-X-tics X-axis-leading-spaces
20909    &optional horizontal-step)
20910   "Print line of X-axis numbers"
20911   (let ((number X-axis-label-spacing)
20912         (horizontal-step (or horizontal-step 1)))
20913 @end group
20914 @group
20915     (insert X-axis-leading-spaces)
20916     ;; @r{Delete extra leading spaces.}
20917     (delete-char
20918      (- (1-
20919          (length (number-to-string horizontal-step)))))
20920     (insert (concat
20921              (make-string
20922 @end group
20923 @group
20924               ;; @r{Insert white space.}
20925               (-  (* symbol-width
20926                      X-axis-label-spacing)
20927                   (1-
20928                    (length
20929                     (number-to-string horizontal-step)))
20930                   2)
20931               ? )
20932              (number-to-string
20933               (* number horizontal-step))))
20934 @end group
20935 @group
20936     ;; @r{Insert remaining numbers.}
20937     (setq number (+ number X-axis-label-spacing))
20938     (while (> number-of-X-tics 1)
20939       (insert (X-axis-element
20940                (* number horizontal-step)))
20941       (setq number (+ number X-axis-label-spacing))
20942       (setq number-of-X-tics (1- number-of-X-tics)))))
20943 @end group
20944 @end smallexample
20946 @need 1500
20947 If you are reading this in Info, you can see the new versions of
20948 @code{print-X-axis} @code{print-graph} and evaluate them.  If you are
20949 reading this in a printed book, you can see the changed lines here
20950 (the full text is too much to print).
20952 @iftex
20953 @smallexample
20954 @group
20955 (defun print-X-axis (numbers-list horizontal-step)
20956   @dots{}
20957     (print-X-axis-numbered-line
20958      tic-number leading-spaces horizontal-step))
20959 @end group
20960 @end smallexample
20962 @smallexample
20963 @group
20964 (defun print-graph
20965   (numbers-list
20966    &optional vertical-step horizontal-step)
20967   @dots{}
20968     (print-X-axis numbers-list horizontal-step))
20969 @end group
20970 @end smallexample
20971 @end iftex
20973 @ifnottex
20974 @smallexample
20975 @group
20976 (defun print-X-axis (numbers-list horizontal-step)
20977   "Print X axis labels to length of NUMBERS-LIST.
20978 Optionally, HORIZONTAL-STEP, a positive integer,
20979 specifies how much an X  axis label increments for
20980 each column."
20981 @end group
20982 @group
20983 ;; Value of symbol-width and full-Y-label-width
20984 ;; are passed by print-graph.
20985   (let* ((leading-spaces
20986           (make-string full-Y-label-width ? ))
20987        ;; symbol-width @r{is provided by} graph-body-print
20988        (tic-width (* symbol-width X-axis-label-spacing))
20989        (X-length (length numbers-list))
20990 @end group
20991 @group
20992        (X-tic
20993         (concat
20994          (make-string
20995           ;; @r{Make a string of blanks.}
20996           (-  (* symbol-width X-axis-label-spacing)
20997               (length X-axis-tic-symbol))
20998           ? )
20999 @end group
21000 @group
21001          ;; @r{Concatenate blanks with tic symbol.}
21002          X-axis-tic-symbol))
21003        (tic-number
21004         (if (zerop (% X-length tic-width))
21005             (/ X-length tic-width)
21006           (1+ (/ X-length tic-width)))))
21007 @end group
21009 @group
21010     (print-X-axis-tic-line
21011      tic-number leading-spaces X-tic)
21012     (insert "\n")
21013     (print-X-axis-numbered-line
21014      tic-number leading-spaces horizontal-step)))
21015 @end group
21016 @end smallexample
21018 @smallexample
21019 @group
21020 (defun print-graph
21021   (numbers-list &optional vertical-step horizontal-step)
21022   "Print labeled bar graph of the NUMBERS-LIST.
21023 The numbers-list consists of the Y-axis values.
21024 @end group
21026 @group
21027 Optionally, VERTICAL-STEP, a positive integer,
21028 specifies how much a Y axis label increments for
21029 each line.  For example, a step of 5 means that
21030 each row is five units.
21031 @end group
21033 @group
21034 Optionally, HORIZONTAL-STEP, a positive integer,
21035 specifies how much an X  axis label increments for
21036 each column."
21037   (let* ((symbol-width (length graph-blank))
21038          ;; @code{height} @r{is both the largest number}
21039          ;; @r{and the number with the most digits.}
21040          (height (apply 'max numbers-list))
21041 @end group
21042 @group
21043          (height-of-top-line
21044           (if (zerop (% height Y-axis-label-spacing))
21045               height
21046             ;; @r{else}
21047             (* (1+ (/ height Y-axis-label-spacing))
21048                Y-axis-label-spacing)))
21049 @end group
21050 @group
21051          (vertical-step (or vertical-step 1))
21052          (full-Y-label-width
21053           (length
21054            (concat
21055             (number-to-string
21056              (* height-of-top-line vertical-step))
21057             Y-axis-tic))))
21058 @end group
21059 @group
21060     (print-Y-axis
21061      height-of-top-line full-Y-label-width vertical-step)
21062     (graph-body-print
21063         numbers-list height-of-top-line symbol-width)
21064     (print-X-axis numbers-list horizontal-step)))
21065 @end group
21066 @end smallexample
21067 @end ifnottex
21069 @c qqq
21070 @ignore
21071 Graphing Definitions Re-listed
21073 @need 1250
21074 Here are all the graphing definitions in their final form:
21076 @smallexample
21077 @group
21078 (defvar top-of-ranges
21079  '(10  20  30  40  50
21080    60  70  80  90 100
21081   110 120 130 140 150
21082   160 170 180 190 200
21083   210 220 230 240 250)
21084  "List specifying ranges for `defuns-per-range'.")
21085 @end group
21087 @group
21088 (defvar graph-symbol "*"
21089   "String used as symbol in graph, usually an asterisk.")
21090 @end group
21092 @group
21093 (defvar graph-blank " "
21094   "String used as blank in graph, usually a blank space.
21095 graph-blank must be the same number of columns wide
21096 as graph-symbol.")
21097 @end group
21099 @group
21100 (defvar Y-axis-tic " - "
21101    "String that follows number in a Y axis label.")
21102 @end group
21104 @group
21105 (defvar Y-axis-label-spacing 5
21106   "Number of lines from one Y axis label to next.")
21107 @end group
21109 @group
21110 (defvar X-axis-tic-symbol "|"
21111   "String to insert to point to a column in X axis.")
21112 @end group
21114 @group
21115 (defvar X-axis-label-spacing
21116   (if (boundp 'graph-blank)
21117       (* 5 (length graph-blank)) 5)
21118   "Number of units from one X axis label to next.")
21119 @end group
21120 @end smallexample
21122 @smallexample
21123 @group
21124 (defun count-words-in-defun ()
21125   "Return the number of words and symbols in a defun."
21126   (beginning-of-defun)
21127   (let ((count 0)
21128         (end (save-excursion (end-of-defun) (point))))
21129 @end group
21131 @group
21132     (while
21133         (and (< (point) end)
21134              (re-search-forward
21135               "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
21136               end t))
21137       (setq count (1+ count)))
21138     count))
21139 @end group
21140 @end smallexample
21142 @smallexample
21143 @group
21144 (defun lengths-list-file (filename)
21145   "Return list of definitions' lengths within FILE.
21146 The returned list is a list of numbers.
21147 Each number is the number of words or
21148 symbols in one function definition."
21149 @end group
21151 @group
21152   (message "Working on `%s' ... " filename)
21153   (save-excursion
21154     (let ((buffer (find-file-noselect filename))
21155           (lengths-list))
21156       (set-buffer buffer)
21157       (setq buffer-read-only t)
21158       (widen)
21159       (goto-char (point-min))
21160 @end group
21162 @group
21163       (while (re-search-forward "^(defun" nil t)
21164         (setq lengths-list
21165               (cons (count-words-in-defun) lengths-list)))
21166       (kill-buffer buffer)
21167       lengths-list)))
21168 @end group
21169 @end smallexample
21171 @smallexample
21172 @group
21173 (defun lengths-list-many-files (list-of-files)
21174   "Return list of lengths of defuns in LIST-OF-FILES."
21175   (let (lengths-list)
21176 ;;; @r{true-or-false-test}
21177     (while list-of-files
21178       (setq lengths-list
21179             (append
21180              lengths-list
21181 @end group
21182 @group
21183 ;;; @r{Generate a lengths' list.}
21184              (lengths-list-file
21185               (expand-file-name (car list-of-files)))))
21186 ;;; @r{Make files' list shorter.}
21187       (setq list-of-files (cdr list-of-files)))
21188 ;;; @r{Return final value of lengths' list.}
21189     lengths-list))
21190 @end group
21191 @end smallexample
21193 @smallexample
21194 @group
21195 (defun defuns-per-range (sorted-lengths top-of-ranges)
21196   "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
21197   (let ((top-of-range (car top-of-ranges))
21198         (number-within-range 0)
21199         defuns-per-range-list)
21200 @end group
21202 @group
21203     ;; @r{Outer loop.}
21204     (while top-of-ranges
21206       ;; @r{Inner loop.}
21207       (while (and
21208               ;; @r{Need number for numeric test.}
21209               (car sorted-lengths)
21210               (< (car sorted-lengths) top-of-range))
21212         ;; @r{Count number of definitions within current range.}
21213         (setq number-within-range (1+ number-within-range))
21214         (setq sorted-lengths (cdr sorted-lengths)))
21215 @end group
21217 @group
21218       ;; @r{Exit inner loop but remain within outer loop.}
21220       (setq defuns-per-range-list
21221             (cons number-within-range defuns-per-range-list))
21222       (setq number-within-range 0)      ; @r{Reset count to zero.}
21224       ;; @r{Move to next range.}
21225       (setq top-of-ranges (cdr top-of-ranges))
21226       ;; @r{Specify next top of range value.}
21227       (setq top-of-range (car top-of-ranges)))
21228 @end group
21230 @group
21231     ;; @r{Exit outer loop and count the number of defuns larger than}
21232     ;; @r{  the largest top-of-range value.}
21233     (setq defuns-per-range-list
21234           (cons
21235            (length sorted-lengths)
21236            defuns-per-range-list))
21238     ;; @r{Return a list of the number of definitions within each range,}
21239     ;; @r{  smallest to largest.}
21240     (nreverse defuns-per-range-list)))
21241 @end group
21242 @end smallexample
21244 @smallexample
21245 @group
21246 (defun column-of-graph (max-graph-height actual-height)
21247   "Return list of MAX-GRAPH-HEIGHT strings;
21248 ACTUAL-HEIGHT are graph-symbols.
21249 The graph-symbols are contiguous entries at the end
21250 of the list.
21251 The list will be inserted as one column of a graph.
21252 The strings are either graph-blank or graph-symbol."
21253 @end group
21255 @group
21256   (let ((insert-list nil)
21257         (number-of-top-blanks
21258          (- max-graph-height actual-height)))
21260     ;; @r{Fill in @code{graph-symbols}.}
21261     (while (> actual-height 0)
21262       (setq insert-list (cons graph-symbol insert-list))
21263       (setq actual-height (1- actual-height)))
21264 @end group
21266 @group
21267     ;; @r{Fill in @code{graph-blanks}.}
21268     (while (> number-of-top-blanks 0)
21269       (setq insert-list (cons graph-blank insert-list))
21270       (setq number-of-top-blanks
21271             (1- number-of-top-blanks)))
21273     ;; @r{Return whole list.}
21274     insert-list))
21275 @end group
21276 @end smallexample
21278 @smallexample
21279 @group
21280 (defun Y-axis-element (number full-Y-label-width)
21281   "Construct a NUMBERed label element.
21282 A numbered element looks like this `  5 - ',
21283 and is padded as needed so all line up with
21284 the element for the largest number."
21285 @end group
21286 @group
21287   (let* ((leading-spaces
21288          (- full-Y-label-width
21289             (length
21290              (concat (number-to-string number)
21291                      Y-axis-tic)))))
21292 @end group
21293 @group
21294     (concat
21295      (make-string leading-spaces ? )
21296      (number-to-string number)
21297      Y-axis-tic)))
21298 @end group
21299 @end smallexample
21301 @smallexample
21302 @group
21303 (defun print-Y-axis
21304   (height full-Y-label-width &optional vertical-step)
21305   "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
21306 Height must be the  maximum height of the graph.
21307 Full width is the width of the highest label element.
21308 Optionally, print according to VERTICAL-STEP."
21309 @end group
21310 @group
21311 ;; Value of height and full-Y-label-width
21312 ;; are passed by 'print-graph'.
21313   (let ((start (point)))
21314     (insert-rectangle
21315      (Y-axis-column height full-Y-label-width vertical-step))
21316 @end group
21317 @group
21318     ;; @r{Place point ready for inserting graph.}
21319     (goto-char start)
21320     ;; @r{Move point forward by value of} full-Y-label-width
21321     (forward-char full-Y-label-width)))
21322 @end group
21323 @end smallexample
21325 @smallexample
21326 @group
21327 (defun print-X-axis-tic-line
21328   (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
21329   "Print ticks for X axis."
21330     (insert X-axis-leading-spaces)
21331     (insert X-axis-tic-symbol)  ; @r{Under first column.}
21332 @end group
21333 @group
21334     ;; @r{Insert second tic in the right spot.}
21335     (insert (concat
21336              (make-string
21337               (-  (* symbol-width X-axis-label-spacing)
21338                   ;; @r{Insert white space up to second tic symbol.}
21339                   (* 2 (length X-axis-tic-symbol)))
21340               ? )
21341              X-axis-tic-symbol))
21342 @end group
21343 @group
21344     ;; @r{Insert remaining ticks.}
21345     (while (> number-of-X-tics 1)
21346       (insert X-axis-tic-element)
21347       (setq number-of-X-tics (1- number-of-X-tics))))
21348 @end group
21349 @end smallexample
21351 @smallexample
21352 @group
21353 (defun X-axis-element (number)
21354   "Construct a numbered X axis element."
21355   (let ((leading-spaces
21356          (-  (* symbol-width X-axis-label-spacing)
21357              (length (number-to-string number)))))
21358     (concat (make-string leading-spaces ? )
21359             (number-to-string number))))
21360 @end group
21361 @end smallexample
21363 @smallexample
21364 @group
21365 (defun graph-body-print (numbers-list height symbol-width)
21366   "Print a bar graph of the NUMBERS-LIST.
21367 The numbers-list consists of the Y-axis values.
21368 HEIGHT is maximum height of graph.
21369 SYMBOL-WIDTH is number of each column."
21370 @end group
21371 @group
21372   (let (from-position)
21373     (while numbers-list
21374       (setq from-position (point))
21375       (insert-rectangle
21376        (column-of-graph height (car numbers-list)))
21377       (goto-char from-position)
21378       (forward-char symbol-width)
21379 @end group
21380 @group
21381       ;; @r{Draw graph column by column.}
21382       (sit-for 0)
21383       (setq numbers-list (cdr numbers-list)))
21384     ;; @r{Place point for X axis labels.}
21385     (forward-line height)
21386     (insert "\n")))
21387 @end group
21388 @end smallexample
21390 @smallexample
21391 @group
21392 (defun Y-axis-column
21393   (height width-of-label &optional vertical-step)
21394   "Construct list of labels for Y axis.
21395 HEIGHT is maximum height of graph.
21396 WIDTH-OF-LABEL is maximum width of label.
21397 @end group
21398 @group
21399 VERTICAL-STEP, an option, is a positive integer
21400 that specifies how much a Y axis label increments
21401 for each line.  For example, a step of 5 means
21402 that each line is five units of the graph."
21403   (let (Y-axis
21404         (number-per-line (or vertical-step 1)))
21405 @end group
21406 @group
21407     (while (> height 1)
21408       (if (zerop (% height Y-axis-label-spacing))
21409           ;; @r{Insert label.}
21410           (setq Y-axis
21411                 (cons
21412                  (Y-axis-element
21413                   (* height number-per-line)
21414                   width-of-label)
21415                  Y-axis))
21416 @end group
21417 @group
21418         ;; @r{Else, insert blanks.}
21419         (setq Y-axis
21420               (cons
21421                (make-string width-of-label ? )
21422                Y-axis)))
21423       (setq height (1- height)))
21424 @end group
21425 @group
21426     ;; @r{Insert base line.}
21427     (setq Y-axis (cons (Y-axis-element
21428                         (or vertical-step 1)
21429                         width-of-label)
21430                        Y-axis))
21431     (nreverse Y-axis)))
21432 @end group
21433 @end smallexample
21435 @smallexample
21436 @group
21437 (defun print-X-axis-numbered-line
21438   (number-of-X-tics X-axis-leading-spaces
21439    &optional horizontal-step)
21440   "Print line of X-axis numbers"
21441   (let ((number X-axis-label-spacing)
21442         (horizontal-step (or horizontal-step 1)))
21443 @end group
21444 @group
21445     (insert X-axis-leading-spaces)
21446     ;; line up number
21447     (delete-char (- (1- (length (number-to-string horizontal-step)))))
21448     (insert (concat
21449              (make-string
21450               ;; @r{Insert white space up to next number.}
21451               (-  (* symbol-width X-axis-label-spacing)
21452                   (1- (length (number-to-string horizontal-step)))
21453                   2)
21454               ? )
21455              (number-to-string (* number horizontal-step))))
21456 @end group
21457 @group
21458     ;; @r{Insert remaining numbers.}
21459     (setq number (+ number X-axis-label-spacing))
21460     (while (> number-of-X-tics 1)
21461       (insert (X-axis-element (* number horizontal-step)))
21462       (setq number (+ number X-axis-label-spacing))
21463       (setq number-of-X-tics (1- number-of-X-tics)))))
21464 @end group
21465 @end smallexample
21467 @smallexample
21468 @group
21469 (defun print-X-axis (numbers-list horizontal-step)
21470   "Print X axis labels to length of NUMBERS-LIST.
21471 Optionally, HORIZONTAL-STEP, a positive integer,
21472 specifies how much an X  axis label increments for
21473 each column."
21474 @end group
21475 @group
21476 ;; Value of symbol-width and full-Y-label-width
21477 ;; are passed by 'print-graph'.
21478   (let* ((leading-spaces
21479           (make-string full-Y-label-width ? ))
21480        ;; symbol-width @r{is provided by} graph-body-print
21481        (tic-width (* symbol-width X-axis-label-spacing))
21482        (X-length (length numbers-list))
21483 @end group
21484 @group
21485        (X-tic
21486         (concat
21487          (make-string
21488           ;; @r{Make a string of blanks.}
21489           (-  (* symbol-width X-axis-label-spacing)
21490               (length X-axis-tic-symbol))
21491           ? )
21492 @end group
21493 @group
21494          ;; @r{Concatenate blanks with tic symbol.}
21495          X-axis-tic-symbol))
21496        (tic-number
21497         (if (zerop (% X-length tic-width))
21498             (/ X-length tic-width)
21499           (1+ (/ X-length tic-width)))))
21500 @end group
21502 @group
21503     (print-X-axis-tic-line
21504      tic-number leading-spaces X-tic)
21505     (insert "\n")
21506     (print-X-axis-numbered-line
21507      tic-number leading-spaces horizontal-step)))
21508 @end group
21509 @end smallexample
21511 @smallexample
21512 @group
21513 (defun one-fiftieth (full-range)
21514   "Return list, each number of which is 1/50th previous."
21515  (mapcar (lambda (arg) (/ arg 50)) full-range))
21516 @end group
21517 @end smallexample
21519 @smallexample
21520 @group
21521 (defun print-graph
21522   (numbers-list &optional vertical-step horizontal-step)
21523   "Print labeled bar graph of the NUMBERS-LIST.
21524 The numbers-list consists of the Y-axis values.
21525 @end group
21527 @group
21528 Optionally, VERTICAL-STEP, a positive integer,
21529 specifies how much a Y axis label increments for
21530 each line.  For example, a step of 5 means that
21531 each row is five units.
21532 @end group
21534 @group
21535 Optionally, HORIZONTAL-STEP, a positive integer,
21536 specifies how much an X  axis label increments for
21537 each column."
21538   (let* ((symbol-width (length graph-blank))
21539          ;; @code{height} @r{is both the largest number}
21540          ;; @r{and the number with the most digits.}
21541          (height (apply 'max numbers-list))
21542 @end group
21543 @group
21544          (height-of-top-line
21545           (if (zerop (% height Y-axis-label-spacing))
21546               height
21547             ;; @r{else}
21548             (* (1+ (/ height Y-axis-label-spacing))
21549                Y-axis-label-spacing)))
21550 @end group
21551 @group
21552          (vertical-step (or vertical-step 1))
21553          (full-Y-label-width
21554           (length
21555            (concat
21556             (number-to-string
21557              (* height-of-top-line vertical-step))
21558             Y-axis-tic))))
21559 @end group
21560 @group
21562     (print-Y-axis
21563      height-of-top-line full-Y-label-width vertical-step)
21564     (graph-body-print
21565         numbers-list height-of-top-line symbol-width)
21566     (print-X-axis numbers-list horizontal-step)))
21567 @end group
21568 @end smallexample
21569 @c qqq
21570 @end ignore
21572 @page
21573 @node Final printed graph
21574 @appendixsubsec The Printed Graph
21576 When made and installed, you can call the @code{print-graph} command
21577 like this:
21578 @sp 1
21580 @smallexample
21581 @group
21582 (print-graph fiftieth-list-for-graph 50 10)
21583 @end group
21584 @end smallexample
21585 @sp 1
21587 @noindent
21588 Here is the graph:
21589 @sp 2
21591 @smallexample
21592 @group
21593 1000 -  *
21594         **
21595         **
21596         **
21597         **
21598  750 -  ***
21599         ***
21600         ***
21601         ***
21602         ****
21603  500 - *****
21604        ******
21605        ******
21606        ******
21607        *******
21608  250 - ********
21609        *********                     *
21610        ***********                   *
21611        *************                 *
21612   50 - ***************** *           *
21613        |   |    |    |    |    |    |    |
21614       10  50  100  150  200  250  300  350
21615 @end group
21616 @end smallexample
21618 @sp 2
21620 @noindent
21621 The largest group of functions contain 10--19 words and symbols each.
21623 @node Free Software and Free Manuals
21624 @appendix Free Software and Free Manuals
21626 @strong{by Richard M. Stallman}
21627 @sp 1
21629 The biggest deficiency in free operating systems is not in the
21630 software---it is the lack of good free manuals that we can include in
21631 these systems.  Many of our most important programs do not come with
21632 full manuals.  Documentation is an essential part of any software
21633 package; when an important free software package does not come with a
21634 free manual, that is a major gap.  We have many such gaps today.
21636 Once upon a time, many years ago, I thought I would learn Perl.  I got
21637 a copy of a free manual, but I found it hard to read.  When I asked
21638 Perl users about alternatives, they told me that there were better
21639 introductory manuals---but those were not free.
21641 Why was this?  The authors of the good manuals had written them for
21642 O'Reilly Associates, which published them with restrictive terms---no
21643 copying, no modification, source files not available---which exclude
21644 them from the free software community.
21646 That wasn't the first time this sort of thing has happened, and (to
21647 our community's great loss) it was far from the last.  Proprietary
21648 manual publishers have enticed a great many authors to restrict their
21649 manuals since then.  Many times I have heard a GNU user eagerly tell me
21650 about a manual that he is writing, with which he expects to help the
21651 GNU project---and then had my hopes dashed, as he proceeded to explain
21652 that he had signed a contract with a publisher that would restrict it
21653 so that we cannot use it.
21655 Given that writing good English is a rare skill among programmers, we
21656 can ill afford to lose manuals this way.
21658 Free documentation, like free software, is a matter of freedom, not
21659 price.  The problem with these manuals was not that O'Reilly Associates
21660 charged a price for printed copies---that in itself is fine.  The Free
21661 Software Foundation @uref{https://shop.fsf.org, sells printed copies} of
21662 free @uref{https://www.gnu.org/doc/doc.html, GNU manuals}, too.
21663 But GNU manuals are available in source code form, while these manuals
21664 are available only on paper.  GNU manuals come with permission to copy
21665 and modify; the Perl manuals do not.  These restrictions are the
21666 problems.
21668 The criterion for a free manual is pretty much the same as for free
21669 software: it is a matter of giving all users certain
21670 freedoms.  Redistribution (including commercial redistribution) must be
21671 permitted, so that the manual can accompany every copy of the program,
21672 on-line or on paper.  Permission for modification is crucial too.
21674 As a general rule, I don't believe that it is essential for people to
21675 have permission to modify all sorts of articles and books.  The issues
21676 for writings are not necessarily the same as those for software.  For
21677 example, I don't think you or I are obliged to give permission to
21678 modify articles like this one, which describe our actions and our
21679 views.
21681 But there is a particular reason why the freedom to modify is crucial
21682 for documentation for free software.  When people exercise their right
21683 to modify the software, and add or change its features, if they are
21684 conscientious they will change the manual too---so they can provide
21685 accurate and usable documentation with the modified program.  A manual
21686 which forbids programmers to be conscientious and finish the job, or
21687 more precisely requires them to write a new manual from scratch if
21688 they change the program, does not fill our community's needs.
21690 While a blanket prohibition on modification is unacceptable, some
21691 kinds of limits on the method of modification pose no problem.  For
21692 example, requirements to preserve the original author's copyright
21693 notice, the distribution terms, or the list of authors, are ok.  It is
21694 also no problem to require modified versions to include notice that
21695 they were modified, even to have entire sections that may not be
21696 deleted or changed, as long as these sections deal with nontechnical
21697 topics.  (Some GNU manuals have them.)
21699 These kinds of restrictions are not a problem because, as a practical
21700 matter, they don't stop the conscientious programmer from adapting the
21701 manual to fit the modified program.  In other words, they don't block
21702 the free software community from making full use of the manual.
21704 However, it must be possible to modify all the technical content of
21705 the manual, and then distribute the result in all the usual media,
21706 through all the usual channels; otherwise, the restrictions do block
21707 the community, the manual is not free, and so we need another manual.
21709 Unfortunately, it is often hard to find someone to write another
21710 manual when a proprietary manual exists.  The obstacle is that many
21711 users think that a proprietary manual is good enough---so they don't
21712 see the need to write a free manual.  They do not see that the free
21713 operating system has a gap that needs filling.
21715 Why do users think that proprietary manuals are good enough?  Some have
21716 not considered the issue.  I hope this article will do something to
21717 change that.
21719 Other users consider proprietary manuals acceptable for the same
21720 reason so many people consider proprietary software acceptable: they
21721 judge in purely practical terms, not using freedom as a
21722 criterion.  These people are entitled to their opinions, but since
21723 those opinions spring from values which do not include freedom, they
21724 are no guide for those of us who do value freedom.
21726 Please spread the word about this issue.  We continue to lose manuals
21727 to proprietary publishing.  If we spread the word that proprietary
21728 manuals are not sufficient, perhaps the next person who wants to help
21729 GNU by writing documentation will realize, before it is too late, that
21730 he must above all make it free.
21732 We can also encourage commercial publishers to sell free, copylefted
21733 manuals instead of proprietary ones.  One way you can help this is to
21734 check the distribution terms of a manual before you buy it, and prefer
21735 copylefted manuals to non-copylefted ones.
21737 @sp 2
21738 @noindent
21739 Note: The Free Software Foundation maintains a page on its Web site
21740 that lists free books available from other publishers:@*
21741 @uref{https://www.gnu.org/doc/other-free-books.html}
21743 @node GNU Free Documentation License
21744 @appendix GNU Free Documentation License
21746 @cindex FDL, GNU Free Documentation License
21747 @include doclicense.texi
21749 @node Index
21750 @unnumbered Index
21752 @ignore
21753 MENU ENTRY: NODE NAME.
21754 @end ignore
21756 @printindex cp
21758 @iftex
21759 @c Place biographical information on right-hand (verso) page
21761 @tex
21762 \par\vfill\supereject
21763 \ifodd\pageno
21764     \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21765     \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21766     %\page\hbox{}\page
21767 \else
21768 %    \par\vfill\supereject
21769     \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21770     \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21771     %\page\hbox{}%\page
21772     %\page\hbox{}%\page
21774 @end tex
21776 @c page
21777 @w{ }
21779 @c ================ Biographical information ================
21781 @w{ }
21782 @sp 8
21783 @center About the Author
21784 @sp 1
21785 @end iftex
21787 @ifnottex
21788 @node About the Author
21789 @unnumbered About the Author
21790 @end ifnottex
21792 @quotation
21793 Robert J. Chassell has worked with GNU Emacs since 1985.  He writes
21794 and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
21795 world on software freedom.  Chassell was a founding Director and
21796 Treasurer of the Free Software Foundation, Inc.  He is co-author of
21797 the @cite{Texinfo} manual, and has edited more than a dozen other
21798 books.  He graduated from Cambridge University, in England.  He has an
21799 abiding interest in social and economic history and flies his own
21800 airplane.
21801 @end quotation
21803 @c @page
21804 @c @w{ }
21806 @c @c Prevent page number on blank verso, so eject it first.
21807 @c @tex
21808 @c \par\vfill\supereject
21809 @c @end tex
21811 @c @iftex
21812 @c @headings off
21813 @c @evenheading @thispage @| @| @thistitle
21814 @c @oddheading            @| @| @thispage
21815 @c @end iftex
21817 @bye