1This is eintr.info, produced by makeinfo version 6.7 from
2emacs-lisp-intro.texi.
3
4This is ‘An Introduction to Programming in Emacs Lisp’, for people who
5are not programmers.
6
7
8   Distributed with Emacs version 27.2.
9
10   Copyright © 1990–1995, 1997, 2001–2021 Free Software Foundation, Inc.
11
12   Printed copies available from <https://shop.fsf.org/>.  Published by:
13
14     GNU Press,                        https://www.fsf.org/licensing/gnu-press/
15     a division of the                 email: sales@fsf.org
16     Free Software Foundation, Inc.    Tel: +1 (617) 542-5942
17     51 Franklin Street, Fifth Floor   Fax: +1 (617) 542-2652
18     Boston, MA 02110-1301 USA
19
20
21   ISBN 1-882114-43-4
22
23     Permission is granted to copy, distribute and/or modify this
24     document under the terms of the GNU Free Documentation License,
25     Version 1.3 or any later version published by the Free Software
26     Foundation; there being no Invariant Section, with the Front-Cover
27     Texts being “A GNU Manual”, and with the Back-Cover Texts as in (a)
28     below.  A copy of the license is included in the section entitled
29     “GNU Free Documentation License”.
30
31     (a) The FSF’s Back-Cover Text is: “You have the freedom to copy and
32     modify this GNU manual.  Buying copies from the FSF supports it in
33     developing GNU and promoting software freedom.”
34INFO-DIR-SECTION Emacs lisp
35START-INFO-DIR-ENTRY
36* Emacs Lisp Intro: (eintr).    A simple introduction to Emacs Lisp programming.
37END-INFO-DIR-ENTRY
38
39
40File: eintr.info,  Node: Top,  Next: Preface,  Up: (dir)
41
42An Introduction to Programming in Emacs Lisp
43********************************************
44
45This is ‘An Introduction to Programming in Emacs Lisp’, for people who
46are not programmers.
47
48
49   Distributed with Emacs version 27.2.
50
51   Copyright © 1990–1995, 1997, 2001–2021 Free Software Foundation, Inc.
52
53   Printed copies available from <https://shop.fsf.org/>.  Published by:
54
55     GNU Press,                        https://www.fsf.org/licensing/gnu-press/
56     a division of the                 email: sales@fsf.org
57     Free Software Foundation, Inc.    Tel: +1 (617) 542-5942
58     51 Franklin Street, Fifth Floor   Fax: +1 (617) 542-2652
59     Boston, MA 02110-1301 USA
60
61
62   ISBN 1-882114-43-4
63
64     Permission is granted to copy, distribute and/or modify this
65     document under the terms of the GNU Free Documentation License,
66     Version 1.3 or any later version published by the Free Software
67     Foundation; there being no Invariant Section, with the Front-Cover
68     Texts being “A GNU Manual”, and with the Back-Cover Texts as in (a)
69     below.  A copy of the license is included in the section entitled
70     “GNU Free Documentation License”.
71
72     (a) The FSF’s Back-Cover Text is: “You have the freedom to copy and
73     modify this GNU manual.  Buying copies from the FSF supports it in
74     developing GNU and promoting software freedom.”
75
76   This master menu first lists each chapter and index; then it lists
77every node in every chapter.
78
79* Menu:
80
81* Preface::                     What to look for.
82* List Processing::             What is Lisp?
83* Practicing Evaluation::       Running several programs.
84* Writing Defuns::              How to write function definitions.
85* Buffer Walk Through::         Exploring a few buffer-related functions.
86* More Complex::                A few, even more complex functions.
87* Narrowing & Widening::        Restricting your and Emacs attention to
88                                    a region.
89* car cdr & cons::              Fundamental functions in Lisp.
90* Cutting & Storing Text::      Removing text and saving it.
91* List Implementation::         How lists are implemented in the computer.
92* Yanking::                     Pasting stored text.
93* Loops & Recursion::           How to repeat a process.
94* Regexp Search::               Regular expression searches.
95* Counting Words::              A review of repetition and regexps.
96* Words in a defun::            Counting words in a ‘defun’.
97* Readying a Graph::            A prototype graph printing function.
98* Emacs Initialization::        How to write a ‘.emacs’ file.
99* Debugging::                   How to run the Emacs Lisp debuggers.
100* Conclusion::                  Now you have the basics.
101* the-the::                     An appendix: how to find reduplicated words.
102* Kill Ring::                   An appendix: how the kill ring works.
103* Full Graph::                  How to create a graph with labeled axes.
104* Free Software and Free Manuals::
105* GNU Free Documentation License::
106* Index::
107* About the Author::
108
109 — The Detailed Node Listing —
110
111Preface
112
113* Why::                         Why learn Emacs Lisp?
114* On Reading this Text::        Read, gain familiarity, pick up habits....
115* Who You Are::                 For whom this is written.
116* Lisp History::
117* Note for Novices::            You can read this as a novice.
118* Thank You::
119
120List Processing
121
122* Lisp Lists::                  What are lists?
123* Run a Program::               Any list in Lisp is a program ready to run.
124* Making Errors::               Generating an error message.
125* Names & Definitions::         Names of symbols and function definitions.
126* Lisp Interpreter::            What the Lisp interpreter does.
127* Evaluation::                  Running a program.
128* Variables::                   Returning a value from a variable.
129* Arguments::                   Passing information to a function.
130* set & setq::                  Setting the value of a variable.
131* Summary::                     The major points.
132* Error Message Exercises::
133
134Lisp Lists
135
136* Numbers Lists::               List have numbers, other lists, in them.
137* Lisp Atoms::                  Elemental entities.
138* Whitespace in Lists::         Formatting lists to be readable.
139* Typing Lists::                How GNU Emacs helps you type lists.
140
141The Lisp Interpreter
142
143* Complications::               Variables, Special forms, Lists within.
144* Byte Compiling::              Specially processing code for speed.
145
146Evaluation
147
148* How the Interpreter Acts::    Returns and Side Effects...
149* Evaluating Inner Lists::      Lists within lists...
150
151Variables
152
153* fill-column Example::
154* Void Function::               The error message for a symbol
155                                  without a function.
156* Void Variable::               The error message for a symbol without a value.
157
158Arguments
159
160* Data types::                  Types of data passed to a function.
161* Args as Variable or List::    An argument can be the value
162                                  of a variable or list.
163* Variable Number of Arguments::  Some functions may take a
164                                  variable number of arguments.
165* Wrong Type of Argument::      Passing an argument of the wrong type
166                                  to a function.
167* message::                     A useful function for sending messages.
168
169Setting the Value of a Variable
170
171* Using set::                  Setting values.
172* Using setq::                 Setting a quoted value.
173* Counting::                   Using ‘setq’ to count.
174
175Practicing Evaluation
176
177* How to Evaluate::            Typing editing commands or ‘C-x C-e’
178                                 causes evaluation.
179* Buffer Names::               Buffers and files are different.
180* Getting Buffers::            Getting a buffer itself, not merely its name.
181* Switching Buffers::          How to change to another buffer.
182* Buffer Size & Locations::    Where point is located and the size of
183                               the buffer.
184* Evaluation Exercise::
185
186How To Write Function Definitions
187
188* Primitive Functions::
189* defun::                        The ‘defun’ macro.
190* Install::                      Install a function definition.
191* Interactive::                  Making a function interactive.
192* Interactive Options::          Different options for ‘interactive’.
193* Permanent Installation::       Installing code permanently.
194* let::                          Creating and initializing local variables.
195* if::                           What if?
196* else::                         If–then–else expressions.
197* Truth & Falsehood::            What Lisp considers false and true.
198* save-excursion::               Keeping track of point and buffer.
199* Review::
200* defun Exercises::
201
202Install a Function Definition
203
204* Effect of installation::
205* Change a defun::              How to change a function definition.
206
207Make a Function Interactive
208
209* Interactive multiply-by-seven::  An overview.
210* multiply-by-seven in detail::    The interactive version.
211
212‘let’
213
214* Prevent confusion::
215* Parts of let Expression::
216* Sample let Expression::
217* Uninitialized let Variables::
218
219The ‘if’ Special Form
220
221* if in more detail::
222* type-of-animal in detail::    An example of an ‘if’ expression.
223
224Truth and Falsehood in Emacs Lisp
225
226* nil explained::               ‘nil’ has two meanings.
227
228‘save-excursion’
229
230* Point and mark::              A review of various locations.
231* Template for save-excursion::
232
233A Few Buffer-Related Functions
234
235* Finding More::                How to find more information.
236* simplified-beginning-of-buffer::  Shows ‘goto-char’,
237                                ‘point-min’, and ‘push-mark’.
238* mark-whole-buffer::           Almost the same as ‘beginning-of-buffer’.
239* append-to-buffer::            Uses ‘save-excursion’ and
240                                ‘insert-buffer-substring’.
241* Buffer Related Review::       Review.
242* Buffer Exercises::
243
244The Definition of ‘mark-whole-buffer’
245
246* mark-whole-buffer overview::
247* Body of mark-whole-buffer::   Only three lines of code.
248
249The Definition of ‘append-to-buffer’
250
251* append-to-buffer overview::
252* append interactive::          A two part interactive expression.
253* append-to-buffer body::       Incorporates a ‘let’ expression.
254* append save-excursion::       How the ‘save-excursion’ works.
255
256A Few More Complex Functions
257
258* copy-to-buffer::              With ‘set-buffer’, ‘get-buffer-create’.
259* insert-buffer::               Read-only, and with ‘or’.
260* beginning-of-buffer::         Shows ‘goto-char’,
261                                ‘point-min’, and ‘push-mark’.
262* Second Buffer Related Review::
263* optional Exercise::
264
265The Definition of ‘insert-buffer’
266
267* insert-buffer code::
268* insert-buffer interactive::   When you can read, but not write.
269* insert-buffer body::          The body has an ‘or’ and a ‘let’.
270* if & or::                     Using an ‘if’ instead of an ‘or’.
271* Insert or::                   How the ‘or’ expression works.
272* Insert let::                  Two ‘save-excursion’ expressions.
273* New insert-buffer::
274
275The Interactive Expression in ‘insert-buffer’
276
277* Read-only buffer::            When a buffer cannot be modified.
278* b for interactive::           An existing buffer or else its name.
279
280Complete Definition of ‘beginning-of-buffer’
281
282* Optional Arguments::
283* beginning-of-buffer opt arg::  Example with optional argument.
284* beginning-of-buffer complete::
285
286‘beginning-of-buffer’ with an Argument
287
288* Disentangle beginning-of-buffer::
289* Large buffer case::
290* Small buffer case::
291
292Narrowing and Widening
293
294* Narrowing advantages::        The advantages of narrowing
295* save-restriction::            The ‘save-restriction’ special form.
296* what-line::                   The number of the line that point is on.
297* narrow Exercise::
298
299‘car’, ‘cdr’, ‘cons’: Fundamental Functions
300
301* Strange Names::               A historical aside: why the strange names?
302* car & cdr::                   Functions for extracting part of a list.
303* cons::                        Constructing a list.
304* nthcdr::                      Calling ‘cdr’ repeatedly.
305* nth::
306* setcar::                      Changing the first element of a list.
307* setcdr::                      Changing the rest of a list.
308* cons Exercise::
309
310‘cons’
311
312* Build a list::
313* length::                      How to find the length of a list.
314
315Cutting and Storing Text
316
317* Storing Text::                Text is stored in a list.
318* zap-to-char::                 Cutting out text up to a character.
319* kill-region::                 Cutting text out of a region.
320* copy-region-as-kill::         A definition for copying text.
321* Digression into C::           Minor note on C programming language macros.
322* defvar::                      How to give a variable an initial value.
323* cons & search-fwd Review::
324* search Exercises::
325
326‘zap-to-char’
327
328* Complete zap-to-char::        The complete implementation.
329* zap-to-char interactive::     A three part interactive expression.
330* zap-to-char body::            A short overview.
331* search-forward::              How to search for a string.
332* progn::                       The ‘progn’ special form.
333* Summing up zap-to-char::      Using ‘point’ and ‘search-forward’.
334
335‘kill-region’
336
337* Complete kill-region::        The function definition.
338* condition-case::              Dealing with a problem.
339* Lisp macro::
340
341‘copy-region-as-kill’
342
343* Complete copy-region-as-kill::  The complete function definition.
344* copy-region-as-kill body::      The body of ‘copy-region-as-kill’.
345
346The Body of ‘copy-region-as-kill’
347
348* last-command & this-command::
349* kill-append function::
350* kill-new function::
351
352Initializing a Variable with ‘defvar’
353
354* See variable current value::
355* defvar and asterisk::
356
357How Lists are Implemented
358
359* Lists diagrammed::
360* Symbols as Chest::            Exploring a powerful metaphor.
361* List Exercise::
362
363Yanking Text Back
364
365* Kill Ring Overview::
366* kill-ring-yank-pointer::      The kill ring is a list.
367* yank nthcdr Exercises::       The ‘kill-ring-yank-pointer’ variable.
368
369Loops and Recursion
370
371* while::                       Causing a stretch of code to repeat.
372* dolist dotimes::
373* Recursion::                   Causing a function to call itself.
374* Looping exercise::
375
376‘while’
377
378* Looping with while::          Repeat so long as test returns true.
379* Loop Example::                A ‘while’ loop that uses a list.
380* print-elements-of-list::      Uses ‘while’, ‘car’, ‘cdr’.
381* Incrementing Loop::           A loop with an incrementing counter.
382* Incrementing Loop Details::
383* Decrementing Loop::           A loop with a decrementing counter.
384
385Details of an Incrementing Loop
386
387* Incrementing Example::        Counting pebbles in a triangle.
388* Inc Example parts::           The parts of the function definition.
389* Inc Example altogether::      Putting the function definition together.
390
391Loop with a Decrementing Counter
392
393* Decrementing Example::        More pebbles on the beach.
394* Dec Example parts::           The parts of the function definition.
395* Dec Example altogether::      Putting the function definition together.
396
397Save your time: ‘dolist’ and ‘dotimes’
398
399* dolist::
400* dotimes::
401
402Recursion
403
404* Building Robots::             Same model, different serial number ...
405* Recursive Definition Parts::  Walk until you stop ...
406* Recursion with list::         Using a list as the test whether to recurse.
407* Recursive triangle function::
408* Recursion with cond::
409* Recursive Patterns::          Often used templates.
410* No Deferment::                Don’t store up work ...
411* No deferment solution::
412
413Recursion in Place of a Counter
414
415* Recursive Example arg of 1 or 2::
416* Recursive Example arg of 3 or 4::
417
418Recursive Patterns
419
420* Every::
421* Accumulate::
422* Keep::
423
424Regular Expression Searches
425
426* sentence-end::                The regular expression for ‘sentence-end’.
427* re-search-forward::           Very similar to ‘search-forward’.
428* forward-sentence::            A straightforward example of regexp search.
429* forward-paragraph::           A somewhat complex example.
430* Regexp Review::
431* re-search Exercises::
432
433‘forward-sentence’
434
435* Complete forward-sentence::
436* fwd-sentence while loops::    Two ‘while’ loops.
437* fwd-sentence re-search::      A regular expression search.
438
439‘forward-paragraph’: a Goldmine of Functions
440
441* forward-paragraph in brief::  Key parts of the function definition.
442* fwd-para let::                The ‘let*’ expression.
443* fwd-para while::              The forward motion ‘while’ loop.
444
445Counting: Repetition and Regexps
446
447* Why Count Words::
448* count-words-example::         Use a regexp, but find a problem.
449* recursive-count-words::       Start with case of no words in region.
450* Counting Exercise::
451
452The ‘count-words-example’ Function
453
454* Design count-words-example::  The definition using a ‘while’ loop.
455* Whitespace Bug::              The Whitespace Bug in ‘count-words-example’.
456
457Counting Words in a ‘defun’
458
459* Divide and Conquer::
460* Words and Symbols::           What to count?
461* Syntax::                      What constitutes a word or symbol?
462* count-words-in-defun::        Very like ‘count-words-example’.
463* Several defuns::              Counting several defuns in a file.
464* Find a File::                 Do you want to look at a file?
465* lengths-list-file::           A list of the lengths of many definitions.
466* Several files::               Counting in definitions in different files.
467* Several files recursively::   Recursively counting in different files.
468* Prepare the data::            Prepare the data for display in a graph.
469
470Count Words in ‘defuns’ in Different Files
471
472* lengths-list-many-files::     Return a list of the lengths of defuns.
473* append::                      Attach one list to another.
474
475Prepare the Data for Display in a Graph
476
477* Data for Display in Detail::
478* Sorting::                     Sorting lists.
479* Files List::                  Making a list of files.
480* Counting function definitions::
481
482Readying a Graph
483
484* Columns of a graph::
485* graph-body-print::            How to print the body of a graph.
486* recursive-graph-body-print::
487* Printed Axes::
488* Line Graph Exercise::
489
490Your ‘.emacs’ File
491
492* Default Configuration::
493* Site-wide Init::              You can write site-wide init files.
494* defcustom::                   Emacs will write code for you.
495* Beginning init File::         How to write a ‘.emacs’ init file.
496* Text and Auto-fill::          Automatically wrap lines.
497* Mail Aliases::                Use abbreviations for email addresses.
498* Indent Tabs Mode::            Don’t use tabs with TeX
499* Keybindings::                 Create some personal keybindings.
500* Keymaps::                     More about key binding.
501* Loading Files::               Load (i.e., evaluate) files automatically.
502* Autoload::                    Make functions available.
503* Simple Extension::            Define a function; bind it to a key.
504* X11 Colors::                  Colors in X.
505* Miscellaneous::
506* Mode Line::                   How to customize your mode line.
507
508Debugging
509
510* debug::                       How to use the built-in debugger.
511* debug-on-entry::              Start debugging when you call a function.
512* debug-on-quit::               Start debugging when you quit with ‘C-g’.
513* edebug::                      How to use Edebug, a source level debugger.
514* Debugging Exercises::
515
516Handling the Kill Ring
517
518* What the Kill Ring Does::
519* current-kill::
520* yank::                        Paste a copy of a clipped element.
521* yank-pop::                    Insert element pointed to.
522* ring file::
523
524The ‘current-kill’ Function
525
526* Code for current-kill::
527* Understanding current-kill::
528
529‘current-kill’ in Outline
530
531* Body of current-kill::
532* Digression concerning error::  How to mislead humans, but not computers.
533* Determining the Element::
534
535A Graph with Labeled Axes
536
537* Labeled Example::
538* print-graph Varlist::         ‘let’ expression in ‘print-graph’.
539* print-Y-axis::                Print a label for the vertical axis.
540* print-X-axis::                Print a horizontal label.
541* Print Whole Graph::           The function to print a complete graph.
542
543The ‘print-Y-axis’ Function
544
545* print-Y-axis in Detail::
546* Height of label::             What height for the Y axis?
547* Compute a Remainder::         How to compute the remainder of a division.
548* Y Axis Element::              Construct a line for the Y axis.
549* Y-axis-column::               Generate a list of Y axis labels.
550* print-Y-axis Penultimate::    A not quite final version.
551
552The ‘print-X-axis’ Function
553
554* Similarities differences::    Much like ‘print-Y-axis’, but not exactly.
555* X Axis Tic Marks::            Create tic marks for the horizontal axis.
556
557Printing the Whole Graph
558
559* The final version::           A few changes.
560* Test print-graph::            Run a short test.
561* Graphing words in defuns::    Executing the final code.
562* lambda::                      How to write an anonymous function.
563* mapcar::                      Apply a function to elements of a list.
564* Another Bug::                 Yet another bug ... most insidious.
565* Final printed graph::         The graph itself!
566
567
568
569File: eintr.info,  Node: Preface,  Next: List Processing,  Prev: Top,  Up: Top
570
571Preface
572*******
573
574Most of the GNU Emacs integrated environment is written in the
575programming language called Emacs Lisp.  The code written in this
576programming language is the software—the sets of instructions—that tell
577the computer what to do when you give it commands.  Emacs is designed so
578that you can write new code in Emacs Lisp and easily install it as an
579extension to the editor.
580
581   (GNU Emacs is sometimes called an “extensible editor”, but it does
582much more than provide editing capabilities.  It is better to refer to
583Emacs as an “extensible computing environment”.  However, that phrase is
584quite a mouthful.  It is easier to refer to Emacs simply as an editor.
585Moreover, everything you do in Emacs—find the Mayan date and phases of
586the moon, simplify polynomials, debug code, manage files, read letters,
587write books—all these activities are kinds of editing in the most
588general sense of the word.)
589
590* Menu:
591
592* Why::                         Why learn Emacs Lisp?
593* On Reading this Text::        Read, gain familiarity, pick up habits....
594* Who You Are::                 For whom this is written.
595* Lisp History::
596* Note for Novices::            You can read this as a novice.
597* Thank You::
598
599
600File: eintr.info,  Node: Why,  Next: On Reading this Text,  Up: Preface
601
602Why Study Emacs Lisp?
603=====================
604
605Although Emacs Lisp is usually thought of in association only with
606Emacs, it is a full computer programming language.  You can use Emacs
607Lisp as you would any other programming language.
608
609   Perhaps you want to understand programming; perhaps you want to
610extend Emacs; or perhaps you want to become a programmer.  This
611introduction to Emacs Lisp is designed to get you started: to guide you
612in learning the fundamentals of programming, and more importantly, to
613show you how you can teach yourself to go further.
614
615
616File: eintr.info,  Node: On Reading this Text,  Next: Who You Are,  Prev: Why,  Up: Preface
617
618On Reading this Text
619====================
620
621All through this document, you will see little sample programs you can
622run inside of Emacs.  If you read this document in Info inside of GNU
623Emacs, you can run the programs as they appear.  (This is easy to do and
624is explained when the examples are presented.)  Alternatively, you can
625read this introduction as a printed book while sitting beside a computer
626running Emacs.  (This is what I like to do; I like printed books.)  If
627you don’t have a running Emacs beside you, you can still read this book,
628but in this case, it is best to treat it as a novel or as a travel guide
629to a country not yet visited: interesting, but not the same as being
630there.
631
632   Much of this introduction is dedicated to walkthroughs or guided
633tours of code used in GNU Emacs.  These tours are designed for two
634purposes: first, to give you familiarity with real, working code (code
635you use every day); and, second, to give you familiarity with the way
636Emacs works.  It is interesting to see how a working environment is
637implemented.  Also, I hope that you will pick up the habit of browsing
638through source code.  You can learn from it and mine it for ideas.
639Having GNU Emacs is like having a dragon’s cave of treasures.
640
641   In addition to learning about Emacs as an editor and Emacs Lisp as a
642programming language, the examples and guided tours will give you an
643opportunity to get acquainted with Emacs as a Lisp programming
644environment.  GNU Emacs supports programming and provides tools that you
645will want to become comfortable using, such as ‘M-.’ (the key which
646invokes the ‘xref-find-definitions’ command).  You will also learn about
647buffers and other objects that are part of the environment.  Learning
648about these features of Emacs is like learning new routes around your
649home town.
650
651   Finally, I hope to convey some of the skills for using Emacs to learn
652aspects of programming that you don’t know.  You can often use Emacs to
653help you understand what puzzles you or to find out how to do something
654new.  This self-reliance is not only a pleasure, but an advantage.
655
656
657File: eintr.info,  Node: Who You Are,  Next: Lisp History,  Prev: On Reading this Text,  Up: Preface
658
659For Whom This is Written
660========================
661
662This text is written as an elementary introduction for people who are
663not programmers.  If you are a programmer, you may not be satisfied with
664this primer.  The reason is that you may have become expert at reading
665reference manuals and be put off by the way this text is organized.
666
667   An expert programmer who reviewed this text said to me:
668
669     I prefer to learn from reference manuals.  I “dive into” each
670     paragraph, and “come up for air” between paragraphs.
671
672     When I get to the end of a paragraph, I assume that subject is
673     done, finished, that I know everything I need (with the possible
674     exception of the case when the next paragraph starts talking about
675     it in more detail).  I expect that a well written reference manual
676     will not have a lot of redundancy, and that it will have excellent
677     pointers to the (one) place where the information I want is.
678
679   This introduction is not written for this person!
680
681   Firstly, I try to say everything at least three times: first, to
682introduce it; second, to show it in context; and third, to show it in a
683different context, or to review it.
684
685   Secondly, I hardly ever put all the information about a subject in
686one place, much less in one paragraph.  To my way of thinking, that
687imposes too heavy a burden on the reader.  Instead I try to explain only
688what you need to know at the time.  (Sometimes I include a little extra
689information so you won’t be surprised later when the additional
690information is formally introduced.)
691
692   When you read this text, you are not expected to learn everything the
693first time.  Frequently, you need make only a nodding acquaintance with
694some of the items mentioned.  My hope is that I have structured the text
695and given you enough hints that you will be alert to what is important,
696and concentrate on it.
697
698   You will need to dive into some paragraphs; there is no other way to
699read them.  But I have tried to keep down the number of such paragraphs.
700This book is intended as an approachable hill, rather than as a daunting
701mountain.
702
703   This book, ‘An Introduction to Programming in Emacs Lisp’, has a
704companion document, *note The GNU Emacs Lisp Reference Manual:
705(elisp)Top.  The reference manual has more detail than this
706introduction.  In the reference manual, all the information about one
707topic is concentrated in one place.  You should turn to it if you are
708like the programmer quoted above.  And, of course, after you have read
709this ‘Introduction’, you will find the ‘Reference Manual’ useful when
710you are writing your own programs.
711
712
713File: eintr.info,  Node: Lisp History,  Next: Note for Novices,  Prev: Who You Are,  Up: Preface
714
715Lisp History
716============
717
718Lisp was first developed in the late 1950s at the Massachusetts
719Institute of Technology for research in artificial intelligence.  The
720great power of the Lisp language makes it superior for other purposes as
721well, such as writing editor commands and integrated environments.
722
723   GNU Emacs Lisp is largely inspired by Maclisp, which was written at
724MIT in the 1960s.  It is somewhat inspired by Common Lisp, which became
725a standard in the 1980s.  However, Emacs Lisp is much simpler than
726Common Lisp.  (The standard Emacs distribution contains an optional
727extensions file, ‘cl.el’, that adds many Common Lisp features to Emacs
728Lisp.)
729
730
731File: eintr.info,  Node: Note for Novices,  Next: Thank You,  Prev: Lisp History,  Up: Preface
732
733A Note for Novices
734==================
735
736If you don’t know GNU Emacs, you can still read this document
737profitably.  However, I recommend you learn Emacs, if only to learn to
738move around your computer screen.  You can teach yourself how to use
739Emacs with the built-in tutorial.  To use it, type ‘C-h t’.  (This means
740you press and release the <CTRL> key and the ‘h’ at the same time, and
741then press and release ‘t’.)
742
743   Also, I often refer to one of Emacs’s standard commands by listing
744the keys which you press to invoke the command and then giving the name
745of the command in parentheses, like this: ‘M-C-\’ (‘indent-region’).
746What this means is that the ‘indent-region’ command is customarily
747invoked by typing ‘M-C-\’.  (You can, if you wish, change the keys that
748are typed to invoke the command; this is called “rebinding”.  *Note
749Keymaps: Keymaps.)  The abbreviation ‘M-C-\’ means that you type your
750<META> key, <CTRL> key and ‘\’ key all at the same time.  (On many
751modern keyboards the <META> key is labeled <ALT>.)  Sometimes a
752combination like this is called a keychord, since it is similar to the
753way you play a chord on a piano.  If your keyboard does not have a
754<META> key, the <ESC> key prefix is used in place of it.  In this case,
755‘M-C-\’ means that you press and release your <ESC> key and then type
756the <CTRL> key and the ‘\’ key at the same time.  But usually ‘M-C-\’
757means press the <CTRL> key along with the key that is labeled <ALT> and,
758at the same time, press the ‘\’ key.
759
760   In addition to typing a lone keychord, you can prefix what you type
761with ‘C-u’, which is called the “universal argument”.  The ‘C-u’
762keychord passes an argument to the subsequent command.  Thus, to indent
763a region of plain text by 6 spaces, mark the region, and then type
764‘C-u 6 M-C-\’.  (If you do not specify a number, Emacs either passes the
765number 4 to the command or otherwise runs the command differently than
766it would otherwise.)  *Note Numeric Arguments: (emacs)Arguments.
767
768   If you are reading this in Info using GNU Emacs, you can read through
769this whole document just by pressing the space bar, <SPC>.  (To learn
770about Info, type ‘C-h i’ and then select Info.)
771
772   A note on terminology: when I use the word Lisp alone, I often am
773referring to the various dialects of Lisp in general, but when I speak
774of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
775
776
777File: eintr.info,  Node: Thank You,  Prev: Note for Novices,  Up: Preface
778
779Thank You
780=========
781
782My thanks to all who helped me with this book.  My especial thanks to
783Jim Blandy, Noah Friedman, Jim Kingdon, Roland McGrath, Frank Ritter,
784Randy Smith, Richard M. Stallman, and Melissa Weisshaus.  My thanks also
785go to both Philip Johnson and David Stampe for their patient
786encouragement.  My mistakes are my own.
787
788                                                     Robert J. Chassell
789                                                          <bob@gnu.org>
790
791
792File: eintr.info,  Node: List Processing,  Next: Practicing Evaluation,  Prev: Preface,  Up: Top
793
7941 List Processing
795*****************
796
797To the untutored eye, Lisp is a strange programming language.  In Lisp
798code there are parentheses everywhere.  Some people even claim that the
799name stands for “Lots of Isolated Silly Parentheses”.  But the claim is
800unwarranted.  Lisp stands for LISt Processing, and the programming
801language handles _lists_ (and lists of lists) by putting them between
802parentheses.  The parentheses mark the boundaries of the list.
803Sometimes a list is preceded by an apostrophe ‘'’, called a
804“single-quote” in Lisp.(1)  Lists are the basis of Lisp.
805
806* Menu:
807
808* Lisp Lists::                  What are lists?
809* Run a Program::               Any list in Lisp is a program ready to run.
810* Making Errors::               Generating an error message.
811* Names & Definitions::         Names of symbols and function definitions.
812* Lisp Interpreter::            What the Lisp interpreter does.
813* Evaluation::                  Running a program.
814* Variables::                   Returning a value from a variable.
815* Arguments::                   Passing information to a function.
816* set & setq::                  Setting the value of a variable.
817* Summary::                     The major points.
818* Error Message Exercises::
819
820   ---------- Footnotes ----------
821
822   (1) A single-quote is an abbreviation for the special form ‘quote’;
823you need not think about special forms now.  *Note Complications::.
824
825
826File: eintr.info,  Node: Lisp Lists,  Next: Run a Program,  Up: List Processing
827
8281.1 Lisp Lists
829==============
830
831In Lisp, a list looks like this: ‘'(rose violet daisy buttercup)’.  This
832list is preceded by a single apostrophe.  It could just as well be
833written as follows, which looks more like the kind of list you are
834likely to be familiar with:
835
836     '(rose
837       violet
838       daisy
839       buttercup)
840
841The elements of this list are the names of the four different flowers,
842separated from each other by whitespace and surrounded by parentheses,
843like flowers in a field with a stone wall around them.
844
845* Menu:
846
847* Numbers Lists::               List have numbers, other lists, in them.
848* Lisp Atoms::                  Elemental entities.
849* Whitespace in Lists::         Formatting lists to be readable.
850* Typing Lists::                How GNU Emacs helps you type lists.
851
852
853File: eintr.info,  Node: Numbers Lists,  Next: Lisp Atoms,  Up: Lisp Lists
854
855Numbers, Lists inside of Lists
856------------------------------
857
858Lists can also have numbers in them, as in this list: ‘(+ 2 2)’.  This
859list has a plus-sign, ‘+’, followed by two ‘2’s, each separated by
860whitespace.
861
862   In Lisp, both data and programs are represented the same way; that
863is, they are both lists of words, numbers, or other lists, separated by
864whitespace and surrounded by parentheses.  (Since a program looks like
865data, one program may easily serve as data for another; this is a very
866powerful feature of Lisp.)  (Incidentally, these two parenthetical
867remarks are _not_ Lisp lists, because they contain ‘;’ and ‘.’ as
868punctuation marks.)
869
870   Here is another list, this time with a list inside of it:
871
872     '(this list has (a list inside of it))
873
874   The components of this list are the words ‘this’, ‘list’, ‘has’, and
875the list ‘(a list inside of it)’.  The interior list is made up of the
876words ‘a’, ‘list’, ‘inside’, ‘of’, ‘it’.
877
878
879File: eintr.info,  Node: Lisp Atoms,  Next: Whitespace in Lists,  Prev: Numbers Lists,  Up: Lisp Lists
880
8811.1.1 Lisp Atoms
882----------------
883
884In Lisp, what we have been calling words are called “atoms”.  This term
885comes from the historical meaning of the word atom, which means
886“indivisible”.  As far as Lisp is concerned, the words we have been
887using in the lists cannot be divided into any smaller parts and still
888mean the same thing as part of a program; likewise with numbers and
889single character symbols like ‘+’.  On the other hand, unlike an ancient
890atom, a list can be split into parts.  (*Note ‘car’ ‘cdr’ & ‘cons’
891Fundamental Functions: car cdr & cons.)
892
893   In a list, atoms are separated from each other by whitespace.  They
894can be right next to a parenthesis.
895
896   Technically speaking, a list in Lisp consists of parentheses
897surrounding atoms separated by whitespace or surrounding other lists or
898surrounding both atoms and other lists.  A list can have just one atom
899in it or have nothing in it at all.  A list with nothing in it looks
900like this: ‘()’, and is called the “empty list”.  Unlike anything else,
901an empty list is considered both an atom and a list at the same time.
902
903   The printed representation of both atoms and lists are called
904“symbolic expressions” or, more concisely, “s-expressions”.  The word
905“expression” by itself can refer to either the printed representation,
906or to the atom or list as it is held internally in the computer.  Often,
907people use the term “expression” indiscriminately.  (Also, in many
908texts, the word “form” is used as a synonym for expression.)
909
910   Incidentally, the atoms that make up our universe were named such
911when they were thought to be indivisible; but it has been found that
912physical atoms are not indivisible.  Parts can split off an atom or it
913can fission into two parts of roughly equal size.  Physical atoms were
914named prematurely, before their truer nature was found.  In Lisp,
915certain kinds of atom, such as an array, can be separated into parts;
916but the mechanism for doing this is different from the mechanism for
917splitting a list.  As far as list operations are concerned, the atoms of
918a list are unsplittable.
919
920   As in English, the meanings of the component letters of a Lisp atom
921are different from the meaning the letters make as a word.  For example,
922the word for the South American sloth, the ‘ai’, is completely different
923from the two words, ‘a’, and ‘i’.
924
925   There are many kinds of atom in nature but only a few in Lisp: for
926example, “numbers”, such as 37, 511, or 1729, and “symbols”, such as
927‘+’, ‘foo’, or ‘forward-line’.  The words we have listed in the examples
928above are all symbols.  In everyday Lisp conversation, the word “atom”
929is not often used, because programmers usually try to be more specific
930about what kind of atom they are dealing with.  Lisp programming is
931mostly about symbols (and sometimes numbers) within lists.
932(Incidentally, the preceding three word parenthetical remark is a proper
933list in Lisp, since it consists of atoms, which in this case are
934symbols, separated by whitespace and enclosed by parentheses, without
935any non-Lisp punctuation.)
936
937   Text between double quotation marks—even sentences or paragraphs—is
938also an atom.  Here is an example:
939
940     '(this list includes "text between quotation marks.")
941
942In Lisp, all of the quoted text including the punctuation mark and the
943blank spaces is a single atom.  This kind of atom is called a “string”
944(for “string of characters”) and is the sort of thing that is used for
945messages that a computer can print for a human to read.  Strings are a
946different kind of atom than numbers or symbols and are used differently.
947
948
949File: eintr.info,  Node: Whitespace in Lists,  Next: Typing Lists,  Prev: Lisp Atoms,  Up: Lisp Lists
950
9511.1.2 Whitespace in Lists
952-------------------------
953
954The amount of whitespace in a list does not matter.  From the point of
955view of the Lisp language,
956
957     '(this list
958        looks like this)
959
960is exactly the same as this:
961
962     '(this list looks like this)
963
964   Both examples show what to Lisp is the same list, the list made up of
965the symbols ‘this’, ‘list’, ‘looks’, ‘like’, and ‘this’ in that order.
966
967   Extra whitespace and newlines are designed to make a list more
968readable by humans.  When Lisp reads the expression, it gets rid of all
969the extra whitespace (but it needs to have at least one space between
970atoms in order to tell them apart.)
971
972   Odd as it seems, the examples we have seen cover almost all of what
973Lisp lists look like!  Every other list in Lisp looks more or less like
974one of these examples, except that the list may be longer and more
975complex.  In brief, a list is between parentheses, a string is between
976quotation marks, a symbol looks like a word, and a number looks like a
977number.  (For certain situations, square brackets, dots and a few other
978special characters may be used; however, we will go quite far without
979them.)
980
981
982File: eintr.info,  Node: Typing Lists,  Prev: Whitespace in Lists,  Up: Lisp Lists
983
9841.1.3 GNU Emacs Helps You Type Lists
985------------------------------------
986
987When you type a Lisp expression in GNU Emacs using either Lisp
988Interaction mode or Emacs Lisp mode, you have available to you several
989commands to format the Lisp expression so it is easy to read.  For
990example, pressing the <TAB> key automatically indents the line the
991cursor is on by the right amount.  A command to properly indent the code
992in a region is customarily bound to ‘M-C-\’.  Indentation is designed so
993that you can see which elements of a list belong to which list—elements
994of a sub-list are indented more than the elements of the enclosing list.
995
996   In addition, when you type a closing parenthesis, Emacs momentarily
997jumps the cursor back to the matching opening parenthesis, so you can
998see which one it is.  This is very useful, since every list you type in
999Lisp must have its closing parenthesis match its opening parenthesis.
1000(*Note Major Modes: (emacs)Major Modes, for more information about
1001Emacs’s modes.)
1002
1003
1004File: eintr.info,  Node: Run a Program,  Next: Making Errors,  Prev: Lisp Lists,  Up: List Processing
1005
10061.2 Run a Program
1007=================
1008
1009A list in Lisp—any list—is a program ready to run.  If you run it (for
1010which the Lisp jargon is “evaluate”), the computer will do one of three
1011things: do nothing except return to you the list itself; send you an
1012error message; or, treat the first symbol in the list as a command to do
1013something.  (Usually, of course, it is the last of these three things
1014that you really want!)
1015
1016   The single apostrophe, ‘'’, that I put in front of some of the
1017example lists in preceding sections is called a “quote”; when it
1018precedes a list, it tells Lisp to do nothing with the list, other than
1019take it as it is written.  But if there is no quote preceding a list,
1020the first item of the list is special: it is a command for the computer
1021to obey.  (In Lisp, these commands are called _functions_.)  The list
1022‘(+ 2 2)’ shown above did not have a quote in front of it, so Lisp
1023understands that the ‘+’ is an instruction to do something with the rest
1024of the list: add the numbers that follow.
1025
1026   If you are reading this inside of GNU Emacs in Info, here is how you
1027can evaluate such a list: place your cursor immediately after the right
1028hand parenthesis of the following list and then type ‘C-x C-e’:
1029
1030     (+ 2 2)
1031
1032You will see the number ‘4’ appear in the echo area(1).  (What you have
1033just done is evaluate the list.  The echo area is the line at the bottom
1034of the screen that displays or echoes text.)  Now try the same thing
1035with a quoted list: place the cursor right after the following list and
1036type ‘C-x C-e’:
1037
1038     '(this is a quoted list)
1039
1040You will see ‘(this is a quoted list)’ appear in the echo area.
1041
1042   In both cases, what you are doing is giving a command to the program
1043inside of GNU Emacs called the “Lisp interpreter”—giving the interpreter
1044a command to evaluate the expression.  The name of the Lisp interpreter
1045comes from the word for the task done by a human who comes up with the
1046meaning of an expression—who interprets it.
1047
1048   You can also evaluate an atom that is not part of a list—one that is
1049not surrounded by parentheses; again, the Lisp interpreter translates
1050from the humanly readable expression to the language of the computer.
1051But before discussing this (*note Variables::), we will discuss what the
1052Lisp interpreter does when you make an error.
1053
1054   ---------- Footnotes ----------
1055
1056   (1) Emacs shows integer values in decimal, in octal and in hex, and
1057also as a character, but let’s ignore this convenience feature for now.
1058
1059
1060File: eintr.info,  Node: Making Errors,  Next: Names & Definitions,  Prev: Run a Program,  Up: List Processing
1061
10621.3 Generate an Error Message
1063=============================
1064
1065Partly so you won’t worry if you do it accidentally, we will now give a
1066command to the Lisp interpreter that generates an error message.  This
1067is a harmless activity; and indeed, we will often try to generate error
1068messages intentionally.  Once you understand the jargon, error messages
1069can be informative.  Instead of being called “error” messages, they
1070should be called “help” messages.  They are like signposts to a traveler
1071in a strange country; deciphering them can be hard, but once understood,
1072they can point the way.
1073
1074   The error message is generated by a built-in GNU Emacs debugger.  We
1075will enter the debugger.  You get out of the debugger by typing ‘q’.
1076
1077   What we will do is evaluate a list that is not quoted and does not
1078have a meaningful command as its first element.  Here is a list almost
1079exactly the same as the one we just used, but without the single-quote
1080in front of it.  Position the cursor right after it and type ‘C-x C-e’:
1081
1082     (this is an unquoted list)
1083
1084   A ‘*Backtrace*’ window will open up and you should see the following
1085in it:
1086
1087     ---------- Buffer: *Backtrace* ----------
1088     Debugger entered--Lisp error: (void-function this)
1089       (this is an unquoted list)
1090       eval((this is an unquoted list) nil)
1091       elisp--eval-last-sexp(nil)
1092       eval-last-sexp(nil)
1093       funcall-interactively(eval-last-sexp nil)
1094       call-interactively(eval-last-sexp nil nil)
1095       command-execute(eval-last-sexp)
1096     ---------- Buffer: *Backtrace* ----------
1097
1098Your cursor will be in this window (you may have to wait a few seconds
1099before it becomes visible).  To quit the debugger and make the debugger
1100window go away, type:
1101
1102     q
1103
1104Please type ‘q’ right now, so you become confident that you can get out
1105of the debugger.  Then, type ‘C-x C-e’ again to re-enter it.
1106
1107   Based on what we already know, we can almost read this error message.
1108
1109   You read the ‘*Backtrace*’ buffer from the bottom up; it tells you
1110what Emacs did.  When you typed ‘C-x C-e’, you made an interactive call
1111to the command ‘eval-last-sexp’.  ‘eval’ is an abbreviation for
1112“evaluate” and ‘sexp’ is an abbreviation for “symbolic expression”.  The
1113command means “evaluate last symbolic expression”, which is the
1114expression just before your cursor.
1115
1116   Each line above tells you what the Lisp interpreter evaluated next.
1117The most recent action is at the top.  The buffer is called the
1118‘*Backtrace*’ buffer because it enables you to track Emacs backwards.
1119
1120   At the top of the ‘*Backtrace*’ buffer, you see the line:
1121
1122     Debugger entered--Lisp error: (void-function this)
1123
1124The Lisp interpreter tried to evaluate the first atom of the list, the
1125word ‘this’.  It is this action that generated the error message
1126‘void-function this’.
1127
1128   The message contains the words ‘void-function’ and ‘this’.
1129
1130   The word ‘function’ was mentioned once before.  It is a very
1131important word.  For our purposes, we can define it by saying that a
1132“function” is a set of instructions to the computer that tell the
1133computer to do something.
1134
1135   Now we can begin to understand the error message: ‘void-function
1136this’.  The function (that is, the word ‘this’) does not have a
1137definition of any set of instructions for the computer to carry out.
1138
1139   The slightly odd word, ‘void-function’, is designed to cover the way
1140Emacs Lisp is implemented, which is that when a symbol does not have a
1141function definition attached to it, the place that should contain the
1142instructions is void.
1143
1144   On the other hand, since we were able to add 2 plus 2 successfully,
1145by evaluating ‘(+ 2 2)’, we can infer that the symbol ‘+’ must have a
1146set of instructions for the computer to obey and those instructions must
1147be to add the numbers that follow the ‘+’.
1148
1149   It is possible to prevent Emacs entering the debugger in cases like
1150this.  We do not explain how to do that here, but we will mention what
1151the result looks like, because you may encounter a similar situation if
1152there is a bug in some Emacs code that you are using.  In such cases,
1153you will see only one line of error message; it will appear in the echo
1154area and look like this:
1155
1156     Symbol's function definition is void: this
1157
1158The message goes away as soon as you type a key, even just to move the
1159cursor.
1160
1161   We know the meaning of the word ‘Symbol’.  It refers to the first
1162atom of the list, the word ‘this’.  The word ‘function’ refers to the
1163instructions that tell the computer what to do.  (Technically, the
1164symbol tells the computer where to find the instructions, but this is a
1165complication we can ignore for the moment.)
1166
1167   The error message can be understood: ‘Symbol's function definition is
1168void: this’.  The symbol (that is, the word ‘this’) lacks instructions
1169for the computer to carry out.
1170
1171
1172File: eintr.info,  Node: Names & Definitions,  Next: Lisp Interpreter,  Prev: Making Errors,  Up: List Processing
1173
11741.4 Symbol Names and Function Definitions
1175=========================================
1176
1177We can articulate another characteristic of Lisp based on what we have
1178discussed so far—an important characteristic: a symbol, like ‘+’, is not
1179itself the set of instructions for the computer to carry out.  Instead,
1180the symbol is used, perhaps temporarily, as a way of locating the
1181definition or set of instructions.  What we see is the name through
1182which the instructions can be found.  Names of people work the same way.
1183I can be referred to as ‘Bob’; however, I am not the letters ‘B’, ‘o’,
1184‘b’ but am, or was, the consciousness consistently associated with a
1185particular life-form.  The name is not me, but it can be used to refer
1186to me.
1187
1188   In Lisp, one set of instructions can be attached to several names.
1189For example, the computer instructions for adding numbers can be linked
1190to the symbol ‘plus’ as well as to the symbol ‘+’ (and are in some
1191dialects of Lisp).  Among humans, I can be referred to as ‘Robert’ as
1192well as ‘Bob’ and by other words as well.
1193
1194   On the other hand, a symbol can have only one function definition
1195attached to it at a time.  Otherwise, the computer would be confused as
1196to which definition to use.  If this were the case among people, only
1197one person in the world could be named ‘Bob’.  However, the function
1198definition to which the name refers can be changed readily.  (*Note
1199Install a Function Definition: Install.)
1200
1201   Since Emacs Lisp is large, it is customary to name symbols in a way
1202that identifies the part of Emacs to which the function belongs.  Thus,
1203all the names for functions that deal with Texinfo start with ‘texinfo-’
1204and those for functions that deal with reading mail start with ‘rmail-’.
1205
1206
1207File: eintr.info,  Node: Lisp Interpreter,  Next: Evaluation,  Prev: Names & Definitions,  Up: List Processing
1208
12091.5 The Lisp Interpreter
1210========================
1211
1212Based on what we have seen, we can now start to figure out what the Lisp
1213interpreter does when we command it to evaluate a list.  First, it looks
1214to see whether there is a quote before the list; if there is, the
1215interpreter just gives us the list.  On the other hand, if there is no
1216quote, the interpreter looks at the first element in the list and sees
1217whether it has a function definition.  If it does, the interpreter
1218carries out the instructions in the function definition.  Otherwise, the
1219interpreter prints an error message.
1220
1221   This is how Lisp works.  Simple.  There are added complications which
1222we will get to in a minute, but these are the fundamentals.  Of course,
1223to write Lisp programs, you need to know how to write function
1224definitions and attach them to names, and how to do this without
1225confusing either yourself or the computer.
1226
1227* Menu:
1228
1229* Complications::               Variables, Special forms, Lists within.
1230* Byte Compiling::              Specially processing code for speed.
1231
1232
1233File: eintr.info,  Node: Complications,  Next: Byte Compiling,  Up: Lisp Interpreter
1234
1235Complications
1236-------------
1237
1238Now, for the first complication.  In addition to lists, the Lisp
1239interpreter can evaluate a symbol that is not quoted and does not have
1240parentheses around it.  The Lisp interpreter will attempt to determine
1241the symbol’s value as a “variable”.  This situation is described in the
1242section on variables.  (*Note Variables::.)
1243
1244   The second complication occurs because some functions are unusual and
1245do not work in the usual manner.  Those that don’t are called “special
1246forms”.  They are used for special jobs, like defining a function, and
1247there are not many of them.  In the next few chapters, you will be
1248introduced to several of the more important special forms.
1249
1250   As well as special forms, there are also “macros”.  A macro is a
1251construct defined in Lisp, which differs from a function in that it
1252translates a Lisp expression into another expression that is to be
1253evaluated in place of the original expression.  (*Note Lisp macro::.)
1254
1255   For the purposes of this introduction, you do not need to worry too
1256much about whether something is a special form, macro, or ordinary
1257function.  For example, ‘if’ is a special form (*note if::), but ‘when’
1258is a macro (*note Lisp macro::).  In earlier versions of Emacs, ‘defun’
1259was a special form, but now it is a macro (*note defun::).  It still
1260behaves in the same way.
1261
1262   The final complication is this: if the function that the Lisp
1263interpreter is looking at is not a special form, and if it is part of a
1264list, the Lisp interpreter looks to see whether the list has a list
1265inside of it.  If there is an inner list, the Lisp interpreter first
1266figures out what it should do with the inside list, and then it works on
1267the outside list.  If there is yet another list embedded inside the
1268inner list, it works on that one first, and so on.  It always works on
1269the innermost list first.  The interpreter works on the innermost list
1270first, to evaluate the result of that list.  The result may be used by
1271the enclosing expression.
1272
1273   Otherwise, the interpreter works left to right, from one expression
1274to the next.
1275
1276
1277File: eintr.info,  Node: Byte Compiling,  Prev: Complications,  Up: Lisp Interpreter
1278
12791.5.1 Byte Compiling
1280--------------------
1281
1282One other aspect of interpreting: the Lisp interpreter is able to
1283interpret two kinds of entity: humanly readable code, on which we will
1284focus exclusively, and specially processed code, called “byte compiled”
1285code, which is not humanly readable.  Byte compiled code runs faster
1286than humanly readable code.
1287
1288   You can transform humanly readable code into byte compiled code by
1289running one of the compile commands such as ‘byte-compile-file’.  Byte
1290compiled code is usually stored in a file that ends with a ‘.elc’
1291extension rather than a ‘.el’ extension.  You will see both kinds of
1292file in the ‘emacs/lisp’ directory; the files to read are those with
1293‘.el’ extensions.
1294
1295   As a practical matter, for most things you might do to customize or
1296extend Emacs, you do not need to byte compile; and I will not discuss
1297the topic here.  *Note Byte Compilation: (elisp)Byte Compilation, for a
1298full description of byte compilation.
1299
1300
1301File: eintr.info,  Node: Evaluation,  Next: Variables,  Prev: Lisp Interpreter,  Up: List Processing
1302
13031.6 Evaluation
1304==============
1305
1306When the Lisp interpreter works on an expression, the term for the
1307activity is called “evaluation”.  We say that the interpreter “evaluates
1308the expression”.  I’ve used this term several times before.  The word
1309comes from its use in everyday language, “to ascertain the value or
1310amount of; to appraise”, according to ‘Webster’s New Collegiate
1311Dictionary’.
1312
1313* Menu:
1314
1315* How the Interpreter Acts::    Returns and Side Effects...
1316* Evaluating Inner Lists::      Lists within lists...
1317
1318
1319File: eintr.info,  Node: How the Interpreter Acts,  Next: Evaluating Inner Lists,  Up: Evaluation
1320
1321How the Lisp Interpreter Acts
1322-----------------------------
1323
1324After evaluating an expression, the Lisp interpreter will most likely
1325“return” the value that the computer produces by carrying out the
1326instructions it found in the function definition, or perhaps it will
1327give up on that function and produce an error message.  (The interpreter
1328may also find itself tossed, so to speak, to a different function or it
1329may attempt to repeat continually what it is doing for ever and ever in
1330an infinite loop.  These actions are less common; and we can ignore
1331them.)  Most frequently, the interpreter returns a value.
1332
1333   At the same time the interpreter returns a value, it may do something
1334else as well, such as move a cursor or copy a file; this other kind of
1335action is called a “side effect”.  Actions that we humans think are
1336important, such as printing results, are often side effects to the Lisp
1337interpreter.  It is fairly easy to learn to use side effects.
1338
1339   In summary, evaluating a symbolic expression most commonly causes the
1340Lisp interpreter to return a value and perhaps carry out a side effect;
1341or else produce an error.
1342
1343
1344File: eintr.info,  Node: Evaluating Inner Lists,  Prev: How the Interpreter Acts,  Up: Evaluation
1345
13461.6.1 Evaluating Inner Lists
1347----------------------------
1348
1349If evaluation applies to a list that is inside another list, the outer
1350list may use the value returned by the first evaluation as information
1351when the outer list is evaluated.  This explains why inner expressions
1352are evaluated first: the values they return are used by the outer
1353expressions.
1354
1355   We can investigate this process by evaluating another addition
1356example.  Place your cursor after the following expression and type ‘C-x
1357C-e’:
1358
1359     (+ 2 (+ 3 3))
1360
1361The number 8 will appear in the echo area.
1362
1363   What happens is that the Lisp interpreter first evaluates the inner
1364expression, ‘(+ 3 3)’, for which the value 6 is returned; then it
1365evaluates the outer expression as if it were written ‘(+ 2 6)’, which
1366returns the value 8.  Since there are no more enclosing expressions to
1367evaluate, the interpreter prints that value in the echo area.
1368
1369   Now it is easy to understand the name of the command invoked by the
1370keystrokes ‘C-x C-e’: the name is ‘eval-last-sexp’.  The letters ‘sexp’
1371are an abbreviation for “symbolic expression”, and ‘eval’ is an
1372abbreviation for “evaluate”.  The command evaluates the last symbolic
1373expression.
1374
1375   As an experiment, you can try evaluating the expression by putting
1376the cursor at the beginning of the next line immediately following the
1377expression, or inside the expression.
1378
1379   Here is another copy of the expression:
1380
1381     (+ 2 (+ 3 3))
1382
1383If you place the cursor at the beginning of the blank line that
1384immediately follows the expression and type ‘C-x C-e’, you will still
1385get the value 8 printed in the echo area.  Now try putting the cursor
1386inside the expression.  If you put it right after the next to last
1387parenthesis (so it appears to sit on top of the last parenthesis), you
1388will get a 6 printed in the echo area!  This is because the command
1389evaluates the expression ‘(+ 3 3)’.
1390
1391   Now put the cursor immediately after a number.  Type ‘C-x C-e’ and
1392you will get the number itself.  In Lisp, if you evaluate a number, you
1393get the number itself—this is how numbers differ from symbols.  If you
1394evaluate a list starting with a symbol like ‘+’, you will get a value
1395returned that is the result of the computer carrying out the
1396instructions in the function definition attached to that name.  If a
1397symbol by itself is evaluated, something different happens, as we will
1398see in the next section.
1399
1400
1401File: eintr.info,  Node: Variables,  Next: Arguments,  Prev: Evaluation,  Up: List Processing
1402
14031.7 Variables
1404=============
1405
1406In Emacs Lisp, a symbol can have a value attached to it just as it can
1407have a function definition attached to it.  The two are different.  The
1408function definition is a set of instructions that a computer will obey.
1409A value, on the other hand, is something, such as number or a name, that
1410can vary (which is why such a symbol is called a variable).  The value
1411of a symbol can be any expression in Lisp, such as a symbol, number,
1412list, or string.  A symbol that has a value is often called a
1413“variable”.
1414
1415   A symbol can have both a function definition and a value attached to
1416it at the same time.  Or it can have just one or the other.  The two are
1417separate.  This is somewhat similar to the way the name Cambridge can
1418refer to the city in Massachusetts and have some information attached to
1419the name as well, such as “great programming center”.
1420
1421   Another way to think about this is to imagine a symbol as being a
1422chest of drawers.  The function definition is put in one drawer, the
1423value in another, and so on.  What is put in the drawer holding the
1424value can be changed without affecting the contents of the drawer
1425holding the function definition, and vice versa.
1426
1427* Menu:
1428
1429* fill-column Example::
1430* Void Function::               The error message for a symbol
1431                                  without a function.
1432* Void Variable::               The error message for a symbol without a value.
1433
1434
1435File: eintr.info,  Node: fill-column Example,  Next: Void Function,  Up: Variables
1436
1437‘fill-column’, an Example Variable
1438----------------------------------
1439
1440The variable ‘fill-column’ illustrates a symbol with a value attached to
1441it: in every GNU Emacs buffer, this symbol is set to some value, usually
144272 or 70, but sometimes to some other value.  To find the value of this
1443symbol, evaluate it by itself.  If you are reading this in Info inside
1444of GNU Emacs, you can do this by putting the cursor after the symbol and
1445typing ‘C-x C-e’:
1446
1447     fill-column
1448
1449After I typed ‘C-x C-e’, Emacs printed the number 72 in my echo area.
1450This is the value for which ‘fill-column’ is set for me as I write this.
1451It may be different for you in your Info buffer.  Notice that the value
1452returned as a variable is printed in exactly the same way as the value
1453returned by a function carrying out its instructions.  From the point of
1454view of the Lisp interpreter, a value returned is a value returned.
1455What kind of expression it came from ceases to matter once the value is
1456known.
1457
1458   A symbol can have any value attached to it or, to use the jargon, we
1459can “bind” the variable to a value: to a number, such as 72; to a
1460string, ‘"such as this"’; to a list, such as ‘(spruce pine oak)’; we can
1461even bind a variable to a function definition.
1462
1463   A symbol can be bound to a value in several ways.  *Note Setting the
1464Value of a Variable: set & setq, for information about one way to do
1465this.
1466
1467
1468File: eintr.info,  Node: Void Function,  Next: Void Variable,  Prev: fill-column Example,  Up: Variables
1469
14701.7.1 Error Message for a Symbol Without a Function
1471---------------------------------------------------
1472
1473When we evaluated ‘fill-column’ to find its value as a variable, we did
1474not place parentheses around the word.  This is because we did not
1475intend to use it as a function name.
1476
1477   If ‘fill-column’ were the first or only element of a list, the Lisp
1478interpreter would attempt to find the function definition attached to
1479it.  But ‘fill-column’ has no function definition.  Try evaluating this:
1480
1481     (fill-column)
1482
1483You will create a ‘*Backtrace*’ buffer that says:
1484
1485     ---------- Buffer: *Backtrace* ----------
1486     Debugger entered--Lisp error: (void-function fill-column)
1487       (fill-column)
1488       eval((fill-column) nil)
1489       elisp--eval-last-sexp(nil)
1490       eval-last-sexp(nil)
1491       funcall-interactively(eval-last-sexp nil)
1492       call-interactively(eval-last-sexp nil nil)
1493       command-execute(eval-last-sexp)
1494     ---------- Buffer: *Backtrace* ----------
1495
1496(Remember, to quit the debugger and make the debugger window go away,
1497type ‘q’ in the ‘*Backtrace*’ buffer.)
1498
1499
1500File: eintr.info,  Node: Void Variable,  Prev: Void Function,  Up: Variables
1501
15021.7.2 Error Message for a Symbol Without a Value
1503------------------------------------------------
1504
1505If you attempt to evaluate a symbol that does not have a value bound to
1506it, you will receive an error message.  You can see this by
1507experimenting with our 2 plus 2 addition.  In the following expression,
1508put your cursor right after the ‘+’, before the first number 2, type
1509‘C-x C-e’:
1510
1511     (+ 2 2)
1512
1513In GNU Emacs 22, you will create a ‘*Backtrace*’ buffer that says:
1514
1515     ---------- Buffer: *Backtrace* ----------
1516     Debugger entered--Lisp error: (void-variable +)
1517       eval(+)
1518       elisp--eval-last-sexp(nil)
1519       eval-last-sexp(nil)
1520       funcall-interactively(eval-last-sexp nil)
1521       call-interactively(eval-last-sexp nil nil)
1522       command-execute(eval-last-sexp)
1523     ---------- Buffer: *Backtrace* ----------
1524
1525(Again, you can quit the debugger by typing ‘q’ in the ‘*Backtrace*’
1526buffer.)
1527
1528   This backtrace is different from the very first error message we saw,
1529which said, ‘Debugger entered--Lisp error: (void-function this)’.  In
1530this case, the function does not have a value as a variable; while in
1531the other error message, the function (the word ‘this’) did not have a
1532definition.
1533
1534   In this experiment with the ‘+’, what we did was cause the Lisp
1535interpreter to evaluate the ‘+’ and look for the value of the variable
1536instead of the function definition.  We did this by placing the cursor
1537right after the symbol rather than after the parenthesis of the
1538enclosing list as we did before.  As a consequence, the Lisp interpreter
1539evaluated the preceding s-expression, which in this case was ‘+’ by
1540itself.
1541
1542   Since ‘+’ does not have a value bound to it, just the function
1543definition, the error message reported that the symbol’s value as a
1544variable was void.
1545
1546
1547File: eintr.info,  Node: Arguments,  Next: set & setq,  Prev: Variables,  Up: List Processing
1548
15491.8 Arguments
1550=============
1551
1552To see how information is passed to functions, let’s look again at our
1553old standby, the addition of two plus two.  In Lisp, this is written as
1554follows:
1555
1556     (+ 2 2)
1557
1558   If you evaluate this expression, the number 4 will appear in your
1559echo area.  What the Lisp interpreter does is add the numbers that
1560follow the ‘+’.
1561
1562   The numbers added by ‘+’ are called the “arguments” of the function
1563‘+’.  These numbers are the information that is given to or “passed” to
1564the function.
1565
1566   The word “argument” comes from the way it is used in mathematics and
1567does not refer to a disputation between two people; instead it refers to
1568the information presented to the function, in this case, to the ‘+’.  In
1569Lisp, the arguments to a function are the atoms or lists that follow the
1570function.  The values returned by the evaluation of these atoms or lists
1571are passed to the function.  Different functions require different
1572numbers of arguments; some functions require none at all.(1)
1573
1574* Menu:
1575
1576* Data types::                  Types of data passed to a function.
1577* Args as Variable or List::    An argument can be the value
1578                                  of a variable or list.
1579* Variable Number of Arguments::  Some functions may take a
1580                                  variable number of arguments.
1581* Wrong Type of Argument::      Passing an argument of the wrong type
1582                                  to a function.
1583* message::                     A useful function for sending messages.
1584
1585   ---------- Footnotes ----------
1586
1587   (1) It is curious to track the path by which the word “argument” came
1588to have two different meanings, one in mathematics and the other in
1589everyday English.  According to the ‘Oxford English Dictionary’, the
1590word derives from the Latin for ‘to make clear, prove’; thus it came to
1591mean, by one thread of derivation, “the evidence offered as proof”,
1592which is to say, “the information offered”, which led to its meaning in
1593Lisp.  But in the other thread of derivation, it came to mean “to assert
1594in a manner against which others may make counter assertions”, which led
1595to the meaning of the word as a disputation.  (Note here that the
1596English word has two different definitions attached to it at the same
1597time.  By contrast, in Emacs Lisp, a symbol cannot have two different
1598function definitions at the same time.)
1599
1600
1601File: eintr.info,  Node: Data types,  Next: Args as Variable or List,  Up: Arguments
1602
16031.8.1 Arguments’ Data Types
1604---------------------------
1605
1606The type of data that should be passed to a function depends on what
1607kind of information it uses.  The arguments to a function such as ‘+’
1608must have values that are numbers, since ‘+’ adds numbers.  Other
1609functions use different kinds of data for their arguments.
1610
1611   For example, the ‘concat’ function links together or unites two or
1612more strings of text to produce a string.  The arguments are strings.
1613Concatenating the two character strings ‘abc’, ‘def’ produces the single
1614string ‘abcdef’.  This can be seen by evaluating the following:
1615
1616     (concat "abc" "def")
1617
1618The value produced by evaluating this expression is ‘"abcdef"’.
1619
1620   A function such as ‘substring’ uses both a string and numbers as
1621arguments.  The function returns a part of the string, a “substring” of
1622the first argument.  This function takes three arguments.  Its first
1623argument is the string of characters, the second and third arguments are
1624numbers that indicate the beginning (inclusive) and end (exclusive) of
1625the substring.  The numbers are a count of the number of characters
1626(including spaces and punctuation) from the beginning of the string.
1627Note that the characters in a string are numbered from zero, not one.
1628
1629   For example, if you evaluate the following:
1630
1631     (substring "The quick brown fox jumped." 16 19)
1632
1633you will see ‘"fox"’ appear in the echo area.  The arguments are the
1634string and the two numbers.
1635
1636   Note that the string passed to ‘substring’ is a single atom even
1637though it is made up of several words separated by spaces.  Lisp counts
1638everything between the two quotation marks as part of the string,
1639including the spaces.  You can think of the ‘substring’ function as a
1640kind of atom smasher since it takes an otherwise indivisible atom and
1641extracts a part.  However, ‘substring’ is only able to extract a
1642substring from an argument that is a string, not from another type of
1643atom such as a number or symbol.
1644
1645
1646File: eintr.info,  Node: Args as Variable or List,  Next: Variable Number of Arguments,  Prev: Data types,  Up: Arguments
1647
16481.8.2 An Argument as the Value of a Variable or List
1649----------------------------------------------------
1650
1651An argument can be a symbol that returns a value when it is evaluated.
1652For example, when the symbol ‘fill-column’ by itself is evaluated, it
1653returns a number.  This number can be used in an addition.
1654
1655   Position the cursor after the following expression and type ‘C-x
1656C-e’:
1657
1658     (+ 2 fill-column)
1659
1660The value will be a number two more than what you get by evaluating
1661‘fill-column’ alone.  For me, this is 74, because my value of
1662‘fill-column’ is 72.
1663
1664   As we have just seen, an argument can be a symbol that returns a
1665value when evaluated.  In addition, an argument can be a list that
1666returns a value when it is evaluated.  For example, in the following
1667expression, the arguments to the function ‘concat’ are the strings
1668‘"The "’ and ‘" red foxes."’ and the list ‘(number-to-string (+ 2
1669fill-column))’.
1670
1671     (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
1672
1673If you evaluate this expression—and if, as with my Emacs, ‘fill-column’
1674evaluates to 72—‘"The 74 red foxes."’ will appear in the echo area.
1675(Note that you must put spaces after the word ‘The’ and before the word
1676‘red’ so they will appear in the final string.  The function
1677‘number-to-string’ converts the integer that the addition function
1678returns to a string.  ‘number-to-string’ is also known as
1679‘int-to-string’.)
1680
1681
1682File: eintr.info,  Node: Variable Number of Arguments,  Next: Wrong Type of Argument,  Prev: Args as Variable or List,  Up: Arguments
1683
16841.8.3 Variable Number of Arguments
1685----------------------------------
1686
1687Some functions, such as ‘concat’, ‘+’ or ‘*’, take any number of
1688arguments.  (The ‘*’ is the symbol for multiplication.)  This can be
1689seen by evaluating each of the following expressions in the usual way.
1690What you will see in the echo area is printed in this text after ‘⇒’,
1691which you may read as “evaluates to”.
1692
1693   In the first set, the functions have no arguments:
1694
1695     (+)       ⇒ 0
1696
1697     (*)       ⇒ 1
1698
1699   In this set, the functions have one argument each:
1700
1701     (+ 3)     ⇒ 3
1702
1703     (* 3)     ⇒ 3
1704
1705   In this set, the functions have three arguments each:
1706
1707     (+ 3 4 5) ⇒ 12
1708
1709     (* 3 4 5) ⇒ 60
1710
1711
1712File: eintr.info,  Node: Wrong Type of Argument,  Next: message,  Prev: Variable Number of Arguments,  Up: Arguments
1713
17141.8.4 Using the Wrong Type Object as an Argument
1715------------------------------------------------
1716
1717When a function is passed an argument of the wrong type, the Lisp
1718interpreter produces an error message.  For example, the ‘+’ function
1719expects the values of its arguments to be numbers.  As an experiment we
1720can pass it the quoted symbol ‘hello’ instead of a number.  Position the
1721cursor after the following expression and type ‘C-x C-e’:
1722
1723     (+ 2 'hello)
1724
1725When you do this you will generate an error message.  What has happened
1726is that ‘+’ has tried to add the 2 to the value returned by ‘'hello’,
1727but the value returned by ‘'hello’ is the symbol ‘hello’, not a number.
1728Only numbers can be added.  So ‘+’ could not carry out its addition.
1729
1730   You will create and enter a ‘*Backtrace*’ buffer that says:
1731
1732     ---------- Buffer: *Backtrace* ----------
1733     Debugger entered--Lisp error:
1734              (wrong-type-argument number-or-marker-p hello)
1735       +(2 hello)
1736       eval((+ 2 'hello) nil)
1737       elisp--eval-last-sexp(t)
1738       eval-last-sexp(nil)
1739       funcall-interactively(eval-print-last-sexp nil)
1740       call-interactively(eval-print-last-sexp nil nil)
1741       command-execute(eval-print-last-sexp)
1742     ---------- Buffer: *Backtrace* ----------
1743
1744   As usual, the error message tries to be helpful and makes sense after
1745you learn how to read it.(1)
1746
1747   The first part of the error message is straightforward; it says
1748‘wrong type argument’.  Next comes the mysterious jargon word
1749‘number-or-marker-p’.  This word is trying to tell you what kind of
1750argument the ‘+’ expected.
1751
1752   The symbol ‘number-or-marker-p’ says that the Lisp interpreter is
1753trying to determine whether the information presented it (the value of
1754the argument) is a number or a marker (a special object representing a
1755buffer position).  What it does is test to see whether the ‘+’ is being
1756given numbers to add.  It also tests to see whether the argument is
1757something called a marker, which is a specific feature of Emacs Lisp.
1758(In Emacs, locations in a buffer are recorded as markers.  When the mark
1759is set with the ‘C-@’ or ‘C-<SPC>’ command, its position is kept as a
1760marker.  The mark can be considered a number—the number of characters
1761the location is from the beginning of the buffer.)  In Emacs Lisp, ‘+’
1762can be used to add the numeric value of marker positions as numbers.
1763
1764   The ‘p’ of ‘number-or-marker-p’ is the embodiment of a practice
1765started in the early days of Lisp programming.  The ‘p’ stands for
1766“predicate”.  In the jargon used by the early Lisp researchers, a
1767predicate refers to a function to determine whether some property is
1768true or false.  So the ‘p’ tells us that ‘number-or-marker-p’ is the
1769name of a function that determines whether it is true or false that the
1770argument supplied is a number or a marker.  Other Lisp symbols that end
1771in ‘p’ include ‘zerop’, a function that tests whether its argument has
1772the value of zero, and ‘listp’, a function that tests whether its
1773argument is a list.
1774
1775   Finally, the last part of the error message is the symbol ‘hello’.
1776This is the value of the argument that was passed to ‘+’.  If the
1777addition had been passed the correct type of object, the value passed
1778would have been a number, such as 37, rather than a symbol like ‘hello’.
1779But then you would not have got the error message.
1780
1781   ---------- Footnotes ----------
1782
1783   (1) ‘(quote hello)’ is an expansion of the abbreviation ‘'hello’.
1784
1785
1786File: eintr.info,  Node: message,  Prev: Wrong Type of Argument,  Up: Arguments
1787
17881.8.5 The ‘message’ Function
1789----------------------------
1790
1791Like ‘+’, the ‘message’ function takes a variable number of arguments.
1792It is used to send messages to the user and is so useful that we will
1793describe it here.
1794
1795   A message is printed in the echo area.  For example, you can print a
1796message in your echo area by evaluating the following list:
1797
1798     (message "This message appears in the echo area!")
1799
1800   The whole string between double quotation marks is a single argument
1801and is printed in toto.  (Note that in this example, the message itself
1802will appear in the echo area within double quotes; that is because you
1803see the value returned by the ‘message’ function.  In most uses of
1804‘message’ in programs that you write, the text will be printed in the
1805echo area as a side-effect, without the quotes.  *Note
1806‘multiply-by-seven’ in detail: multiply-by-seven in detail, for an
1807example of this.)
1808
1809   However, if there is a ‘%s’ in the quoted string of characters, the
1810‘message’ function does not print the ‘%s’ as such, but looks to the
1811argument that follows the string.  It evaluates the second argument and
1812prints the value at the location in the string where the ‘%s’ is.
1813
1814   You can see this by positioning the cursor after the following
1815expression and typing ‘C-x C-e’:
1816
1817     (message "The name of this buffer is: %s." (buffer-name))
1818
1819In Info, ‘"The name of this buffer is: *info*."’ will appear in the echo
1820area.  The function ‘buffer-name’ returns the name of the buffer as a
1821string, which the ‘message’ function inserts in place of ‘%s’.
1822
1823   To print a value as an integer, use ‘%d’ in the same way as ‘%s’.
1824For example, to print a message in the echo area that states the value
1825of the ‘fill-column’, evaluate the following:
1826
1827     (message "The value of fill-column is %d." fill-column)
1828
1829On my system, when I evaluate this list, ‘"The value of fill-column is
183072."’ appears in my echo area(1).
1831
1832   If there is more than one ‘%s’ in the quoted string, the value of the
1833first argument following the quoted string is printed at the location of
1834the first ‘%s’ and the value of the second argument is printed at the
1835location of the second ‘%s’, and so on.
1836
1837   For example, if you evaluate the following,
1838
1839     (message "There are %d %s in the office!"
1840              (- fill-column 14) "pink elephants")
1841
1842a rather whimsical message will appear in your echo area.  On my system
1843it says, ‘"There are 58 pink elephants in the office!"’.
1844
1845   The expression ‘(- fill-column 14)’ is evaluated and the resulting
1846number is inserted in place of the ‘%d’; and the string in double
1847quotes, ‘"pink elephants"’, is treated as a single argument and inserted
1848in place of the ‘%s’.  (That is to say, a string between double quotes
1849evaluates to itself, like a number.)
1850
1851   Finally, here is a somewhat complex example that not only illustrates
1852the computation of a number, but also shows how you can use an
1853expression within an expression to generate the text that is substituted
1854for ‘%s’:
1855
1856     (message "He saw %d %s"
1857              (- fill-column 32)
1858              (concat "red "
1859                      (substring
1860                       "The quick brown foxes jumped." 16 21)
1861                      " leaping."))
1862
1863   In this example, ‘message’ has three arguments: the string, ‘"He saw
1864%d %s"’, the expression, ‘(- fill-column 32)’, and the expression
1865beginning with the function ‘concat’.  The value resulting from the
1866evaluation of ‘(- fill-column 32)’ is inserted in place of the ‘%d’; and
1867the value returned by the expression beginning with ‘concat’ is inserted
1868in place of the ‘%s’.
1869
1870   When your fill column is 70 and you evaluate the expression, the
1871message ‘"He saw 38 red foxes leaping."’ appears in your echo area.
1872
1873   ---------- Footnotes ----------
1874
1875   (1) Actually, you can use ‘%s’ to print a number.  It is
1876non-specific.  ‘%d’ prints only the part of a number left of a decimal
1877point, and not anything that is not a number.
1878
1879
1880File: eintr.info,  Node: set & setq,  Next: Summary,  Prev: Arguments,  Up: List Processing
1881
18821.9 Setting the Value of a Variable
1883===================================
1884
1885There are several ways by which a variable can be given a value.  One of
1886the ways is to use either the function ‘set’ or the special form ‘setq’.
1887Another way is to use ‘let’ (*note let::).  (The jargon for this process
1888is to “bind” a variable to a value.)
1889
1890   The following sections not only describe how ‘set’ and ‘setq’ work
1891but also illustrate how arguments are passed.
1892
1893* Menu:
1894
1895* Using set::                  Setting values.
1896* Using setq::                 Setting a quoted value.
1897* Counting::                   Using ‘setq’ to count.
1898
1899
1900File: eintr.info,  Node: Using set,  Next: Using setq,  Up: set & setq
1901
19021.9.1 Using ‘set’
1903-----------------
1904
1905To set the value of the symbol ‘flowers’ to the list ‘'(rose violet
1906daisy buttercup)’, evaluate the following expression by positioning the
1907cursor after the expression and typing ‘C-x C-e’.
1908
1909     (set 'flowers '(rose violet daisy buttercup))
1910
1911The list ‘(rose violet daisy buttercup)’ will appear in the echo area.
1912This is what is _returned_ by the ‘set’ function.  As a side effect, the
1913symbol ‘flowers’ is bound to the list; that is, the symbol ‘flowers’,
1914which can be viewed as a variable, is given the list as its value.
1915(This process, by the way, illustrates how a side effect to the Lisp
1916interpreter, setting the value, can be the primary effect that we humans
1917are interested in.  This is because every Lisp function must return a
1918value if it does not get an error, but it will only have a side effect
1919if it is designed to have one.)
1920
1921   After evaluating the ‘set’ expression, you can evaluate the symbol
1922‘flowers’ and it will return the value you just set.  Here is the
1923symbol.  Place your cursor after it and type ‘C-x C-e’.
1924
1925     flowers
1926
1927When you evaluate ‘flowers’, the list ‘(rose violet daisy buttercup)’
1928appears in the echo area.
1929
1930   Incidentally, if you evaluate ‘'flowers’, the variable with a quote
1931in front of it, what you will see in the echo area is the symbol itself,
1932‘flowers’.  Here is the quoted symbol, so you can try this:
1933
1934     'flowers
1935
1936   Note also, that when you use ‘set’, you need to quote both arguments
1937to ‘set’, unless you want them evaluated.  Since we do not want either
1938argument evaluated, neither the variable ‘flowers’ nor the list ‘(rose
1939violet daisy buttercup)’, both are quoted.  (When you use ‘set’ without
1940quoting its first argument, the first argument is evaluated before
1941anything else is done.  If you did this and ‘flowers’ did not have a
1942value already, you would get an error message that the ‘Symbol's value
1943as variable is void’; on the other hand, if ‘flowers’ did return a value
1944after it was evaluated, the ‘set’ would attempt to set the value that
1945was returned.  There are situations where this is the right thing for
1946the function to do; but such situations are rare.)
1947
1948
1949File: eintr.info,  Node: Using setq,  Next: Counting,  Prev: Using set,  Up: set & setq
1950
19511.9.2 Using ‘setq’
1952------------------
1953
1954As a practical matter, you almost always quote the first argument to
1955‘set’.  The combination of ‘set’ and a quoted first argument is so
1956common that it has its own name: the special form ‘setq’.  This special
1957form is just like ‘set’ except that the first argument is quoted
1958automatically, so you don’t need to type the quote mark yourself.  Also,
1959as an added convenience, ‘setq’ permits you to set several different
1960variables to different values, all in one expression.
1961
1962   To set the value of the variable ‘carnivores’ to the list ‘'(lion
1963tiger leopard)’ using ‘setq’, the following expression is used:
1964
1965     (setq carnivores '(lion tiger leopard))
1966
1967This is exactly the same as using ‘set’ except the first argument is
1968automatically quoted by ‘setq’.  (The ‘q’ in ‘setq’ means ‘quote’.)
1969
1970   With ‘set’, the expression would look like this:
1971
1972     (set 'carnivores '(lion tiger leopard))
1973
1974   Also, ‘setq’ can be used to assign different values to different
1975variables.  The first argument is bound to the value of the second
1976argument, the third argument is bound to the value of the fourth
1977argument, and so on.  For example, you could use the following to assign
1978a list of trees to the symbol ‘trees’ and a list of herbivores to the
1979symbol ‘herbivores’:
1980
1981     (setq trees '(pine fir oak maple)
1982           herbivores '(gazelle antelope zebra))
1983
1984(The expression could just as well have been on one line, but it might
1985not have fit on a page; and humans find it easier to read nicely
1986formatted lists.)
1987
1988   Although I have been using the term “assign”, there is another way of
1989thinking about the workings of ‘set’ and ‘setq’; and that is to say that
1990‘set’ and ‘setq’ make the symbol _point_ to the list.  This latter way
1991of thinking is very common and in forthcoming chapters we shall come
1992upon at least one symbol that has “pointer” as part of its name.  The
1993name is chosen because the symbol has a value, specifically a list,
1994attached to it; or, expressed another way, the symbol is set to point to
1995the list.
1996
1997
1998File: eintr.info,  Node: Counting,  Prev: Using setq,  Up: set & setq
1999
20001.9.3 Counting
2001--------------
2002
2003Here is an example that shows how to use ‘setq’ in a counter.  You might
2004use this to count how many times a part of your program repeats itself.
2005First set a variable to zero; then add one to the number each time the
2006program repeats itself.  To do this, you need a variable that serves as
2007a counter, and two expressions: an initial ‘setq’ expression that sets
2008the counter variable to zero; and a second ‘setq’ expression that
2009increments the counter each time it is evaluated.
2010
2011     (setq counter 0)                ; Let’s call this the initializer.
2012
2013     (setq counter (+ counter 1))    ; This is the incrementer.
2014
2015     counter                         ; This is the counter.
2016
2017(The text following the ‘;’ are comments.  *Note Change a Function
2018Definition: Change a defun.)
2019
2020   If you evaluate the first of these expressions, the initializer,
2021‘(setq counter 0)’, and then evaluate the third expression, ‘counter’,
2022the number ‘0’ will appear in the echo area.  If you then evaluate the
2023second expression, the incrementer, ‘(setq counter (+ counter 1))’, the
2024counter will get the value 1.  So if you again evaluate ‘counter’, the
2025number ‘1’ will appear in the echo area.  Each time you evaluate the
2026second expression, the value of the counter will be incremented.
2027
2028   When you evaluate the incrementer, ‘(setq counter (+ counter 1))’,
2029the Lisp interpreter first evaluates the innermost list; this is the
2030addition.  In order to evaluate this list, it must evaluate the variable
2031‘counter’ and the number ‘1’.  When it evaluates the variable ‘counter’,
2032it receives its current value.  It passes this value and the number ‘1’
2033to the ‘+’ which adds them together.  The sum is then returned as the
2034value of the inner list and passed to the ‘setq’ which sets the variable
2035‘counter’ to this new value.  Thus, the value of the variable,
2036‘counter’, is changed.
2037
2038
2039File: eintr.info,  Node: Summary,  Next: Error Message Exercises,  Prev: set & setq,  Up: List Processing
2040
20411.10 Summary
2042============
2043
2044Learning Lisp is like climbing a hill in which the first part is the
2045steepest.  You have now climbed the most difficult part; what remains
2046becomes easier as you progress onwards.
2047
2048   In summary,
2049
2050   • Lisp programs are made up of expressions, which are lists or single
2051     atoms.
2052
2053   • Lists are made up of zero or more atoms or inner lists, separated
2054     by whitespace and surrounded by parentheses.  A list can be empty.
2055
2056   • Atoms are multi-character symbols, like ‘forward-paragraph’, single
2057     character symbols like ‘+’, strings of characters between double
2058     quotation marks, or numbers.
2059
2060   • A number evaluates to itself.
2061
2062   • A string between double quotes also evaluates to itself.
2063
2064   • When you evaluate a symbol by itself, its value is returned.
2065
2066   • When you evaluate a list, the Lisp interpreter looks at the first
2067     symbol in the list and then at the function definition bound to
2068     that symbol.  Then the instructions in the function definition are
2069     carried out.
2070
2071   • A single-quote ‘'’ tells the Lisp interpreter that it should return
2072     the following expression as written, and not evaluate it as it
2073     would if the quote were not there.
2074
2075   • Arguments are the information passed to a function.  The arguments
2076     to a function are computed by evaluating the rest of the elements
2077     of the list of which the function is the first element.
2078
2079   • A function always returns a value when it is evaluated (unless it
2080     gets an error); in addition, it may also carry out some action that
2081     is a side effect.  In many cases, a function’s primary purpose is
2082     to create a side effect.
2083
2084
2085File: eintr.info,  Node: Error Message Exercises,  Prev: Summary,  Up: List Processing
2086
20871.11 Exercises
2088==============
2089
2090A few simple exercises:
2091
2092   • Generate an error message by evaluating an appropriate symbol that
2093     is not within parentheses.
2094
2095   • Generate an error message by evaluating an appropriate symbol that
2096     is between parentheses.
2097
2098   • Create a counter that increments by two rather than one.
2099
2100   • Write an expression that prints a message in the echo area when
2101     evaluated.
2102
2103
2104File: eintr.info,  Node: Practicing Evaluation,  Next: Writing Defuns,  Prev: List Processing,  Up: Top
2105
21062 Practicing Evaluation
2107***********************
2108
2109Before learning how to write a function definition in Emacs Lisp, it is
2110useful to spend a little time evaluating various expressions that have
2111already been written.  These expressions will be lists with the
2112functions as their first (and often only) element.  Since some of the
2113functions associated with buffers are both simple and interesting, we
2114will start with those.  In this section, we will evaluate a few of
2115these.  In another section, we will study the code of several other
2116buffer-related functions, to see how they were written.
2117
2118* Menu:
2119
2120* How to Evaluate::            Typing editing commands or ‘C-x C-e’
2121                                 causes evaluation.
2122* Buffer Names::               Buffers and files are different.
2123* Getting Buffers::            Getting a buffer itself, not merely its name.
2124* Switching Buffers::          How to change to another buffer.
2125* Buffer Size & Locations::    Where point is located and the size of
2126                               the buffer.
2127* Evaluation Exercise::
2128
2129
2130File: eintr.info,  Node: How to Evaluate,  Next: Buffer Names,  Up: Practicing Evaluation
2131
2132How to Evaluate
2133===============
2134
2135Whenever you give an editing command to Emacs Lisp, such as the command
2136to move the cursor or to scroll the screen, you are evaluating an
2137expression, the first element of which is a function.  This is how Emacs
2138works.
2139
2140   When you type keys, you cause the Lisp interpreter to evaluate an
2141expression and that is how you get your results.  Even typing plain text
2142involves evaluating an Emacs Lisp function, in this case, one that uses
2143‘self-insert-command’, which simply inserts the character you typed.
2144The functions you evaluate by typing keystrokes are called “interactive”
2145functions, or “commands”; how you make a function interactive will be
2146illustrated in the chapter on how to write function definitions.  *Note
2147Making a Function Interactive: Interactive.
2148
2149   In addition to typing keyboard commands, we have seen a second way to
2150evaluate an expression: by positioning the cursor after a list and
2151typing ‘C-x C-e’.  This is what we will do in the rest of this section.
2152There are other ways to evaluate an expression as well; these will be
2153described as we come to them.
2154
2155   Besides being used for practicing evaluation, the functions shown in
2156the next few sections are important in their own right.  A study of
2157these functions makes clear the distinction between buffers and files,
2158how to switch to a buffer, and how to determine a location within it.
2159
2160
2161File: eintr.info,  Node: Buffer Names,  Next: Getting Buffers,  Prev: How to Evaluate,  Up: Practicing Evaluation
2162
21632.1 Buffer Names
2164================
2165
2166The two functions, ‘buffer-name’ and ‘buffer-file-name’, show the
2167difference between a file and a buffer.  When you evaluate the following
2168expression, ‘(buffer-name)’, the name of the buffer appears in the echo
2169area.  When you evaluate ‘(buffer-file-name)’, the name of the file to
2170which the buffer refers appears in the echo area.  Usually, the name
2171returned by ‘(buffer-name)’ is the same as the name of the file to which
2172it refers, and the name returned by ‘(buffer-file-name)’ is the full
2173path-name of the file.
2174
2175   A file and a buffer are two different entities.  A file is
2176information recorded permanently in the computer (unless you delete it).
2177A buffer, on the other hand, is information inside of Emacs that will
2178vanish at the end of the editing session (or when you kill the buffer).
2179Usually, a buffer contains information that you have copied from a file;
2180we say the buffer is “visiting” that file.  This copy is what you work
2181on and modify.  Changes to the buffer do not change the file, until you
2182save the buffer.  When you save the buffer, the buffer is copied to the
2183file and is thus saved permanently.
2184
2185   If you are reading this in Info inside of GNU Emacs, you can evaluate
2186each of the following expressions by positioning the cursor after it and
2187typing ‘C-x C-e’.
2188
2189     (buffer-name)
2190
2191     (buffer-file-name)
2192
2193When I do this in Info, the value returned by evaluating ‘(buffer-name)’
2194is ‘"*info*"’, and the value returned by evaluating ‘(buffer-file-name)’
2195is ‘nil’.
2196
2197   On the other hand, while I am writing this document, the value
2198returned by evaluating ‘(buffer-name)’ is ‘"introduction.texinfo"’, and
2199the value returned by evaluating ‘(buffer-file-name)’ is
2200‘"/gnu/work/intro/introduction.texinfo"’.
2201
2202   The former is the name of the buffer and the latter is the name of
2203the file.  In Info, the buffer name is ‘"*info*"’.  Info does not point
2204to any file, so the result of evaluating ‘(buffer-file-name)’ is ‘nil’.
2205The symbol ‘nil’ is from the Latin word for “nothing”; in this case, it
2206means that the buffer is not associated with any file.  (In Lisp, ‘nil’
2207is also used to mean “false” and is a synonym for the empty list, ‘()’.)
2208
2209   When I am writing, the name of my buffer is ‘"introduction.texinfo"’.
2210The name of the file to which it points is
2211‘"/gnu/work/intro/introduction.texinfo"’.
2212
2213   (In the expressions, the parentheses tell the Lisp interpreter to
2214treat ‘buffer-name’ and ‘buffer-file-name’ as functions; without the
2215parentheses, the interpreter would attempt to evaluate the symbols as
2216variables.  *Note Variables::.)
2217
2218   In spite of the distinction between files and buffers, you will often
2219find that people refer to a file when they mean a buffer and vice versa.
2220Indeed, most people say, “I am editing a file,” rather than saying, “I
2221am editing a buffer which I will soon save to a file.” It is almost
2222always clear from context what people mean.  When dealing with computer
2223programs, however, it is important to keep the distinction in mind,
2224since the computer is not as smart as a person.
2225
2226   The word “buffer”, by the way, comes from the meaning of the word as
2227a cushion that deadens the force of a collision.  In early computers, a
2228buffer cushioned the interaction between files and the computer’s
2229central processing unit.  The drums or tapes that held a file and the
2230central processing unit were pieces of equipment that were very
2231different from each other, working at their own speeds, in spurts.  The
2232buffer made it possible for them to work together effectively.
2233Eventually, the buffer grew from being an intermediary, a temporary
2234holding place, to being the place where work is done.  This
2235transformation is rather like that of a small seaport that grew into a
2236great city: once it was merely the place where cargo was warehoused
2237temporarily before being loaded onto ships; then it became a business
2238and cultural center in its own right.
2239
2240   Not all buffers are associated with files.  For example, a
2241‘*scratch*’ buffer does not visit any file.  Similarly, a ‘*Help*’
2242buffer is not associated with any file.
2243
2244   In the old days, when you lacked a ‘~/.emacs’ file and started an
2245Emacs session by typing the command ‘emacs’ alone, without naming any
2246files, Emacs started with the ‘*scratch*’ buffer visible.  Nowadays, you
2247will see a splash screen.  You can follow one of the commands suggested
2248on the splash screen, visit a file, or press ‘q’ to quit the splash
2249screen and reach the ‘*scratch*’ buffer.
2250
2251   If you switch to the ‘*scratch*’ buffer, type ‘(buffer-name)’,
2252position the cursor after it, and then type ‘C-x C-e’ to evaluate the
2253expression.  The name ‘"*scratch*"’ will be returned and will appear in
2254the echo area.  ‘"*scratch*"’ is the name of the buffer.  When you type
2255‘(buffer-file-name)’ in the ‘*scratch*’ buffer and evaluate that, ‘nil’
2256will appear in the echo area, just as it does when you evaluate
2257‘(buffer-file-name)’ in Info.
2258
2259   Incidentally, if you are in the ‘*scratch*’ buffer and want the value
2260returned by an expression to appear in the ‘*scratch*’ buffer itself
2261rather than in the echo area, type ‘C-u C-x C-e’ instead of ‘C-x C-e’.
2262This causes the value returned to appear after the expression.  The
2263buffer will look like this:
2264
2265     (buffer-name)"*scratch*"
2266
2267You cannot do this in Info since Info is read-only and it will not allow
2268you to change the contents of the buffer.  But you can do this in any
2269buffer you can edit; and when you write code or documentation (such as
2270this book), this feature is very useful.
2271
2272
2273File: eintr.info,  Node: Getting Buffers,  Next: Switching Buffers,  Prev: Buffer Names,  Up: Practicing Evaluation
2274
22752.2 Getting Buffers
2276===================
2277
2278The ‘buffer-name’ function returns the _name_ of the buffer; to get the
2279buffer _itself_, a different function is needed: the ‘current-buffer’
2280function.  If you use this function in code, what you get is the buffer
2281itself.
2282
2283   A name and the object or entity to which the name refers are
2284different from each other.  You are not your name.  You are a person to
2285whom others refer by name.  If you ask to speak to George and someone
2286hands you a card with the letters ‘G’, ‘e’, ‘o’, ‘r’, ‘g’, and ‘e’
2287written on it, you might be amused, but you would not be satisfied.  You
2288do not want to speak to the name, but to the person to whom the name
2289refers.  A buffer is similar: the name of the scratch buffer is
2290‘*scratch*’, but the name is not the buffer.  To get a buffer itself,
2291you need to use a function such as ‘current-buffer’.
2292
2293   However, there is a slight complication: if you evaluate
2294‘current-buffer’ in an expression on its own, as we will do here, what
2295you see is a printed representation of the name of the buffer without
2296the contents of the buffer.  Emacs works this way for two reasons: the
2297buffer may be thousands of lines long—too long to be conveniently
2298displayed; and, another buffer may have the same contents but a
2299different name, and it is important to distinguish between them.
2300
2301   Here is an expression containing the function:
2302
2303     (current-buffer)
2304
2305If you evaluate this expression in Info in Emacs in the usual way,
2306‘#<buffer *info*>’ will appear in the echo area.  The special format
2307indicates that the buffer itself is being returned, rather than just its
2308name.
2309
2310   Incidentally, while you can type a number or symbol into a program,
2311you cannot do that with the printed representation of a buffer: the only
2312way to get a buffer itself is with a function such as ‘current-buffer’.
2313
2314   A related function is ‘other-buffer’.  This returns the most recently
2315selected buffer other than the one you are in currently, not a printed
2316representation of its name.  If you have recently switched back and
2317forth from the ‘*scratch*’ buffer, ‘other-buffer’ will return that
2318buffer.
2319
2320   You can see this by evaluating the expression:
2321
2322     (other-buffer)
2323
2324You should see ‘#<buffer *scratch*>’ appear in the echo area, or the
2325name of whatever other buffer you switched back from most recently(1).
2326
2327   ---------- Footnotes ----------
2328
2329   (1) Actually, by default, if the buffer from which you just switched
2330is visible to you in another window, ‘other-buffer’ will choose the most
2331recent buffer that you cannot see; this is a subtlety that I often
2332forget.
2333
2334
2335File: eintr.info,  Node: Switching Buffers,  Next: Buffer Size & Locations,  Prev: Getting Buffers,  Up: Practicing Evaluation
2336
23372.3 Switching Buffers
2338=====================
2339
2340The ‘other-buffer’ function actually provides a buffer when it is used
2341as an argument to a function that requires one.  We can see this by
2342using ‘other-buffer’ and ‘switch-to-buffer’ to switch to a different
2343buffer.
2344
2345   But first, a brief introduction to the ‘switch-to-buffer’ function.
2346When you switched back and forth from Info to the ‘*scratch*’ buffer to
2347evaluate ‘(buffer-name)’, you most likely typed ‘C-x b’ and then typed
2348‘*scratch*’(1) when prompted in the minibuffer for the name of the
2349buffer to which you wanted to switch.  The keystrokes, ‘C-x b’, cause
2350the Lisp interpreter to evaluate the interactive function
2351‘switch-to-buffer’.  As we said before, this is how Emacs works:
2352different keystrokes call or run different functions.  For example,
2353‘C-f’ calls ‘forward-char’, ‘M-e’ calls ‘forward-sentence’, and so on.
2354
2355   By writing ‘switch-to-buffer’ in an expression, and giving it a
2356buffer to switch to, we can switch buffers just the way ‘C-x b’ does:
2357
2358     (switch-to-buffer (other-buffer))
2359
2360The symbol ‘switch-to-buffer’ is the first element of the list, so the
2361Lisp interpreter will treat it as a function and carry out the
2362instructions that are attached to it.  But before doing that, the
2363interpreter will note that ‘other-buffer’ is inside parentheses and work
2364on that symbol first.  ‘other-buffer’ is the first (and in this case,
2365the only) element of this list, so the Lisp interpreter calls or runs
2366the function.  It returns another buffer.  Next, the interpreter runs
2367‘switch-to-buffer’, passing to it, as an argument, the other buffer,
2368which is what Emacs will switch to.  If you are reading this in Info,
2369try this now.  Evaluate the expression.  (To get back, type ‘C-x b
2370<RET>’.)(2)
2371
2372   In the programming examples in later sections of this document, you
2373will see the function ‘set-buffer’ more often than ‘switch-to-buffer’.
2374This is because of a difference between computer programs and humans:
2375humans have eyes and expect to see the buffer on which they are working
2376on their computer terminals.  This is so obvious, it almost goes without
2377saying.  However, programs do not have eyes.  When a computer program
2378works on a buffer, that buffer does not need to be visible on the
2379screen.
2380
2381   ‘switch-to-buffer’ is designed for humans and does two different
2382things: it switches the buffer to which Emacs’s attention is directed;
2383and it switches the buffer displayed in the window to the new buffer.
2384‘set-buffer’, on the other hand, does only one thing: it switches the
2385attention of the computer program to a different buffer.  The buffer on
2386the screen remains unchanged (of course, normally nothing happens there
2387until the command finishes running).
2388
2389   Also, we have just introduced another jargon term, the word “call”.
2390When you evaluate a list in which the first symbol is a function, you
2391are calling that function.  The use of the term comes from the notion of
2392the function as an entity that can do something for you if you call
2393it—just as a plumber is an entity who can fix a leak if you call him or
2394her.
2395
2396   ---------- Footnotes ----------
2397
2398   (1) Or rather, to save typing, you probably only typed ‘RET’ if the
2399default buffer was ‘*scratch*’, or if it was different, then you typed
2400just part of the name, such as ‘*sc’, pressed your ‘TAB’ key to cause it
2401to expand to the full name, and then typed ‘RET’.
2402
2403   (2) Remember, this expression will move you to your most recent other
2404buffer that you cannot see.  If you really want to go to your most
2405recently selected buffer, even if you can still see it, you need to
2406evaluate the following more complex expression:
2407
2408     (switch-to-buffer (other-buffer (current-buffer) t))
2409
2410   In this case, the first argument to ‘other-buffer’ tells it which
2411buffer to skip—the current one—and the second argument tells
2412‘other-buffer’ it is OK to switch to a visible buffer.  In regular use,
2413‘switch-to-buffer’ takes you to a buffer not visible in windows since
2414you would most likely use ‘C-x o’ (‘other-window’) to go to another
2415visible buffer.
2416
2417
2418File: eintr.info,  Node: Buffer Size & Locations,  Next: Evaluation Exercise,  Prev: Switching Buffers,  Up: Practicing Evaluation
2419
24202.4 Buffer Size and the Location of Point
2421=========================================
2422
2423Finally, let’s look at several rather simple functions, ‘buffer-size’,
2424‘point’, ‘point-min’, and ‘point-max’.  These give information about the
2425size of a buffer and the location of point within it.
2426
2427   The function ‘buffer-size’ tells you the size of the current buffer;
2428that is, the function returns a count of the number of characters in the
2429buffer.
2430
2431     (buffer-size)
2432
2433You can evaluate this in the usual way, by positioning the cursor after
2434the expression and typing ‘C-x C-e’.
2435
2436   In Emacs, the current position of the cursor is called “point”.  The
2437expression ‘(point)’ returns a number that tells you where the cursor is
2438located as a count of the number of characters from the beginning of the
2439buffer up to point.
2440
2441   You can see the character count for point in this buffer by
2442evaluating the following expression in the usual way:
2443
2444     (point)
2445
2446As I write this, the value of point is 65724.  The ‘point’ function is
2447frequently used in some of the examples later in this book.
2448
2449   The value of point depends, of course, on its location within the
2450buffer.  If you evaluate point in this spot, the number will be larger:
2451
2452     (point)
2453
2454For me, the value of point in this location is 66043, which means that
2455there are 319 characters (including spaces) between the two expressions.
2456(Doubtless, you will see different numbers, since I will have edited
2457this since I first evaluated point.)
2458
2459   The function ‘point-min’ is somewhat similar to ‘point’, but it
2460returns the value of the minimum permissible value of point in the
2461current buffer.  This is the number 1 unless “narrowing” is in effect.
2462(Narrowing is a mechanism whereby you can restrict yourself, or a
2463program, to operations on just a part of a buffer.  *Note Narrowing and
2464Widening: Narrowing & Widening.)  Likewise, the function ‘point-max’
2465returns the value of the maximum permissible value of point in the
2466current buffer.
2467
2468
2469File: eintr.info,  Node: Evaluation Exercise,  Prev: Buffer Size & Locations,  Up: Practicing Evaluation
2470
24712.5 Exercise
2472============
2473
2474Find a file with which you are working and move towards its middle.
2475Find its buffer name, file name, length, and your position in the file.
2476
2477
2478File: eintr.info,  Node: Writing Defuns,  Next: Buffer Walk Through,  Prev: Practicing Evaluation,  Up: Top
2479
24803 How To Write Function Definitions
2481***********************************
2482
2483When the Lisp interpreter evaluates a list, it looks to see whether the
2484first symbol on the list has a function definition attached to it; or,
2485put another way, whether the symbol points to a function definition.  If
2486it does, the computer carries out the instructions in the definition.  A
2487symbol that has a function definition is called, simply, a function
2488(although, properly speaking, the definition is the function and the
2489symbol refers to it.)
2490
2491* Menu:
2492
2493* Primitive Functions::
2494* defun::                        The ‘defun’ macro.
2495* Install::                      Install a function definition.
2496* Interactive::                  Making a function interactive.
2497* Interactive Options::          Different options for ‘interactive’.
2498* Permanent Installation::       Installing code permanently.
2499* let::                          Creating and initializing local variables.
2500* if::                           What if?
2501* else::                         If–then–else expressions.
2502* Truth & Falsehood::            What Lisp considers false and true.
2503* save-excursion::               Keeping track of point and buffer.
2504* Review::
2505* defun Exercises::
2506
2507
2508File: eintr.info,  Node: Primitive Functions,  Next: defun,  Up: Writing Defuns
2509
2510An Aside about Primitive Functions
2511==================================
2512
2513All functions are defined in terms of other functions, except for a few
2514“primitive” functions that are written in the C programming language.
2515When you write functions’ definitions, you will write them in Emacs Lisp
2516and use other functions as your building blocks.  Some of the functions
2517you will use will themselves be written in Emacs Lisp (perhaps by you)
2518and some will be primitives written in C.  The primitive functions are
2519used exactly like those written in Emacs Lisp and behave like them.
2520They are written in C so we can easily run GNU Emacs on any computer
2521that has sufficient power and can run C.
2522
2523   Let me re-emphasize this: when you write code in Emacs Lisp, you do
2524not distinguish between the use of functions written in C and the use of
2525functions written in Emacs Lisp.  The difference is irrelevant.  I
2526mention the distinction only because it is interesting to know.  Indeed,
2527unless you investigate, you won’t know whether an already-written
2528function is written in Emacs Lisp or C.
2529
2530
2531File: eintr.info,  Node: defun,  Next: Install,  Prev: Primitive Functions,  Up: Writing Defuns
2532
25333.1 The ‘defun’ Macro
2534=====================
2535
2536In Lisp, a symbol such as ‘mark-whole-buffer’ has code attached to it
2537that tells the computer what to do when the function is called.  This
2538code is called the “function definition” and is created by evaluating a
2539Lisp expression that starts with the symbol ‘defun’ (which is an
2540abbreviation for _define function_).
2541
2542   In subsequent sections, we will look at function definitions from the
2543Emacs source code, such as ‘mark-whole-buffer’.  In this section, we
2544will describe a simple function definition so you can see how it looks.
2545This function definition uses arithmetic because it makes for a simple
2546example.  Some people dislike examples using arithmetic; however, if you
2547are such a person, do not despair.  Hardly any of the code we will study
2548in the remainder of this introduction involves arithmetic or
2549mathematics.  The examples mostly involve text in one way or another.
2550
2551   A function definition has up to five parts following the word
2552‘defun’:
2553
2554  1. The name of the symbol to which the function definition should be
2555     attached.
2556
2557  2. A list of the arguments that will be passed to the function.  If no
2558     arguments will be passed to the function, this is an empty list,
2559     ‘()’.
2560
2561  3. Documentation describing the function.  (Technically optional, but
2562     strongly recommended.)
2563
2564  4. Optionally, an expression to make the function interactive so you
2565     can use it by typing ‘M-x’ and then the name of the function; or by
2566     typing an appropriate key or keychord.
2567
2568  5. The code that instructs the computer what to do: the “body” of the
2569     function definition.
2570
2571   It is helpful to think of the five parts of a function definition as
2572being organized in a template, with slots for each part:
2573
2574     (defun FUNCTION-NAME (ARGUMENTS...)
2575       "OPTIONAL-DOCUMENTATION..."
2576       (interactive ARGUMENT-PASSING-INFO)     ; optional
2577       BODY...)
2578
2579   As an example, here is the code for a function that multiplies its
2580argument by 7.  (This example is not interactive.  *Note Making a
2581Function Interactive: Interactive, for that information.)
2582
2583     (defun multiply-by-seven (number)
2584       "Multiply NUMBER by seven."
2585       (* 7 number))
2586
2587   This definition begins with a parenthesis and the symbol ‘defun’,
2588followed by the name of the function.
2589
2590   The name of the function is followed by a list that contains the
2591arguments that will be passed to the function.  This list is called the
2592“argument list”.  In this example, the list has only one element, the
2593symbol, ‘number’.  When the function is used, the symbol will be bound
2594to the value that is used as the argument to the function.
2595
2596   Instead of choosing the word ‘number’ for the name of the argument, I
2597could have picked any other name.  For example, I could have chosen the
2598word ‘multiplicand’.  I picked the word “number” because it tells what
2599kind of value is intended for this slot; but I could just as well have
2600chosen the word “multiplicand” to indicate the role that the value
2601placed in this slot will play in the workings of the function.  I could
2602have called it ‘foogle’, but that would have been a bad choice because
2603it would not tell humans what it means.  The choice of name is up to the
2604programmer and should be chosen to make the meaning of the function
2605clear.
2606
2607   Indeed, you can choose any name you wish for a symbol in an argument
2608list, even the name of a symbol used in some other function: the name
2609you use in an argument list is private to that particular definition.
2610In that definition, the name refers to a different entity than any use
2611of the same name outside the function definition.  Suppose you have a
2612nick-name “Shorty” in your family; when your family members refer to
2613“Shorty”, they mean you.  But outside your family, in a movie, for
2614example, the name “Shorty” refers to someone else.  Because a name in an
2615argument list is private to the function definition, you can change the
2616value of such a symbol inside the body of a function without changing
2617its value outside the function.  The effect is similar to that produced
2618by a ‘let’ expression.  (*Note ‘let’: let.)
2619
2620   The argument list is followed by the documentation string that
2621describes the function.  This is what you see when you type ‘C-h f’ and
2622the name of a function.  Incidentally, when you write a documentation
2623string like this, you should make the first line a complete sentence
2624since some commands, such as ‘apropos’, print only the first line of a
2625multi-line documentation string.  Also, you should not indent the second
2626line of a documentation string, if you have one, because that looks odd
2627when you use ‘C-h f’ (‘describe-function’).  The documentation string is
2628optional, but it is so useful, it should be included in almost every
2629function you write.
2630
2631   The third line of the example consists of the body of the function
2632definition.  (Most functions’ definitions, of course, are longer than
2633this.)  In this function, the body is the list, ‘(* 7 number)’, which
2634says to multiply the value of NUMBER by 7.  (In Emacs Lisp, ‘*’ is the
2635function for multiplication, just as ‘+’ is the function for addition.)
2636
2637   When you use the ‘multiply-by-seven’ function, the argument ‘number’
2638evaluates to the actual number you want used.  Here is an example that
2639shows how ‘multiply-by-seven’ is used; but don’t try to evaluate this
2640yet!
2641
2642     (multiply-by-seven 3)
2643
2644The symbol ‘number’, specified in the function definition in the next
2645section, is bound to the value 3 in the actual use of the function.
2646Note that although ‘number’ was inside parentheses in the function
2647definition, the argument passed to the ‘multiply-by-seven’ function is
2648not in parentheses.  The parentheses are written in the function
2649definition so the computer can figure out where the argument list ends
2650and the rest of the function definition begins.
2651
2652   If you evaluate this example, you are likely to get an error message.
2653(Go ahead, try it!)  This is because we have written the function
2654definition, but not yet told the computer about the definition—we have
2655not yet loaded the function definition in Emacs.  Installing a function
2656is the process that tells the Lisp interpreter the definition of the
2657function.  Installation is described in the next section.
2658
2659
2660File: eintr.info,  Node: Install,  Next: Interactive,  Prev: defun,  Up: Writing Defuns
2661
26623.2 Install a Function Definition
2663=================================
2664
2665If you are reading this inside of Info in Emacs, you can try out the
2666‘multiply-by-seven’ function by first evaluating the function definition
2667and then evaluating ‘(multiply-by-seven 3)’.  A copy of the function
2668definition follows.  Place the cursor after the last parenthesis of the
2669function definition and type ‘C-x C-e’.  When you do this,
2670‘multiply-by-seven’ will appear in the echo area.  (What this means is
2671that when a function definition is evaluated, the value it returns is
2672the name of the defined function.)  At the same time, this action
2673installs the function definition.
2674
2675     (defun multiply-by-seven (number)
2676       "Multiply NUMBER by seven."
2677       (* 7 number))
2678
2679By evaluating this ‘defun’, you have just installed ‘multiply-by-seven’
2680in Emacs.  The function is now just as much a part of Emacs as
2681‘forward-word’ or any other editing function you use.
2682(‘multiply-by-seven’ will stay installed until you quit Emacs.  To
2683reload code automatically whenever you start Emacs, see *note Installing
2684Code Permanently: Permanent Installation.)
2685
2686* Menu:
2687
2688* Effect of installation::
2689* Change a defun::              How to change a function definition.
2690
2691
2692File: eintr.info,  Node: Effect of installation,  Next: Change a defun,  Up: Install
2693
2694The effect of installation
2695--------------------------
2696
2697You can see the effect of installing ‘multiply-by-seven’ by evaluating
2698the following sample.  Place the cursor after the following expression
2699and type ‘C-x C-e’.  The number 21 will appear in the echo area.
2700
2701     (multiply-by-seven 3)
2702
2703   If you wish, you can read the documentation for the function by
2704typing ‘C-h f’ (‘describe-function’) and then the name of the function,
2705‘multiply-by-seven’.  When you do this, a ‘*Help*’ window will appear on
2706your screen that says:
2707
2708     multiply-by-seven is a Lisp function.
2709
2710     (multiply-by-seven NUMBER)
2711
2712     Multiply NUMBER by seven.
2713
2714(To return to a single window on your screen, type ‘C-x 1’.)
2715
2716
2717File: eintr.info,  Node: Change a defun,  Prev: Effect of installation,  Up: Install
2718
27193.2.1 Change a Function Definition
2720----------------------------------
2721
2722If you want to change the code in ‘multiply-by-seven’, just rewrite it.
2723To install the new version in place of the old one, evaluate the
2724function definition again.  This is how you modify code in Emacs.  It is
2725very simple.
2726
2727   As an example, you can change the ‘multiply-by-seven’ function to add
2728the number to itself seven times instead of multiplying the number by
2729seven.  It produces the same answer, but by a different path.  At the
2730same time, we will add a comment to the code; a comment is text that the
2731Lisp interpreter ignores, but that a human reader may find useful or
2732enlightening.  The comment is that this is the second version.
2733
2734     (defun multiply-by-seven (number)       ; Second version.
2735       "Multiply NUMBER by seven."
2736       (+ number number number number number number number))
2737
2738   The comment follows a semicolon, ‘;’.  In Lisp, everything on a line
2739that follows a semicolon is a comment.  The end of the line is the end
2740of the comment.  To stretch a comment over two or more lines, begin each
2741line with a semicolon.
2742
2743   *Note Beginning a ‘.emacs’ File: Beginning init File, and *note
2744Comments: (elisp)Comments, for more about comments.
2745
2746   You can install this version of the ‘multiply-by-seven’ function by
2747evaluating it in the same way you evaluated the first function: place
2748the cursor after the last parenthesis and type ‘C-x C-e’.
2749
2750   In summary, this is how you write code in Emacs Lisp: you write a
2751function; install it; test it; and then make fixes or enhancements and
2752install it again.
2753
2754
2755File: eintr.info,  Node: Interactive,  Next: Interactive Options,  Prev: Install,  Up: Writing Defuns
2756
27573.3 Make a Function Interactive
2758===============================
2759
2760You make a function interactive by placing a list that begins with the
2761special form ‘interactive’ immediately after the documentation.  A user
2762can invoke an interactive function by typing ‘M-x’ and then the name of
2763the function; or by typing the keys to which it is bound, for example,
2764by typing ‘C-n’ for ‘next-line’ or ‘C-x h’ for ‘mark-whole-buffer’.
2765
2766   Interestingly, when you call an interactive function interactively,
2767the value returned is not automatically displayed in the echo area.
2768This is because you often call an interactive function for its side
2769effects, such as moving forward by a word or line, and not for the value
2770returned.  If the returned value were displayed in the echo area each
2771time you typed a key, it would be very distracting.
2772
2773* Menu:
2774
2775* Interactive multiply-by-seven::  An overview.
2776* multiply-by-seven in detail::    The interactive version.
2777
2778
2779File: eintr.info,  Node: Interactive multiply-by-seven,  Next: multiply-by-seven in detail,  Up: Interactive
2780
2781An Interactive ‘multiply-by-seven’, An Overview
2782-----------------------------------------------
2783
2784Both the use of the special form ‘interactive’ and one way to display a
2785value in the echo area can be illustrated by creating an interactive
2786version of ‘multiply-by-seven’.
2787
2788   Here is the code:
2789
2790     (defun multiply-by-seven (number)       ; Interactive version.
2791       "Multiply NUMBER by seven."
2792       (interactive "p")
2793       (message "The result is %d" (* 7 number)))
2794
2795You can install this code by placing your cursor after it and typing
2796‘C-x C-e’.  The name of the function will appear in your echo area.
2797Then, you can use this code by typing ‘C-u’ and a number and then typing
2798‘M-x multiply-by-seven’ and pressing <RET>.  The phrase ‘The result is
2799...’ followed by the product will appear in the echo area.
2800
2801   Speaking more generally, you invoke a function like this in either of
2802two ways:
2803
2804  1. By typing a prefix argument that contains the number to be passed,
2805     and then typing ‘M-x’ and the name of the function, as with ‘C-u 3
2806     M-x forward-sentence’; or,
2807
2808  2. By typing whatever key or keychord the function is bound to, as
2809     with ‘C-u 3 M-e’.
2810
2811Both the examples just mentioned work identically to move point forward
2812three sentences.  (Since ‘multiply-by-seven’ is not bound to a key, it
2813could not be used as an example of key binding.)
2814
2815   (*Note Some Keybindings: Keybindings, to learn how to bind a command
2816to a key.)
2817
2818   A “prefix argument” is passed to an interactive function by typing
2819the <META> key followed by a number, for example, ‘M-3 M-e’, or by
2820typing ‘C-u’ and then a number, for example, ‘C-u 3 M-e’ (if you type
2821‘C-u’ without a number, it defaults to 4).
2822
2823
2824File: eintr.info,  Node: multiply-by-seven in detail,  Prev: Interactive multiply-by-seven,  Up: Interactive
2825
28263.3.1 An Interactive ‘multiply-by-seven’
2827----------------------------------------
2828
2829Let’s look at the use of the special form ‘interactive’ and then at the
2830function ‘message’ in the interactive version of ‘multiply-by-seven’.
2831You will recall that the function definition looks like this:
2832
2833     (defun multiply-by-seven (number)       ; Interactive version.
2834       "Multiply NUMBER by seven."
2835       (interactive "p")
2836       (message "The result is %d" (* 7 number)))
2837
2838   In this function, the expression, ‘(interactive "p")’, is a list of
2839two elements.  The ‘"p"’ tells Emacs to pass the prefix argument to the
2840function and use its value for the argument of the function.
2841
2842   The argument will be a number.  This means that the symbol ‘number’
2843will be bound to a number in the line:
2844
2845     (message "The result is %d" (* 7 number))
2846
2847For example, if your prefix argument is 5, the Lisp interpreter will
2848evaluate the line as if it were:
2849
2850     (message "The result is %d" (* 7 5))
2851
2852(If you are reading this in GNU Emacs, you can evaluate this expression
2853yourself.)  First, the interpreter will evaluate the inner list, which
2854is ‘(* 7 5)’.  This returns a value of 35.  Next, it will evaluate the
2855outer list, passing the values of the second and subsequent elements of
2856the list to the function ‘message’.
2857
2858   As we have seen, ‘message’ is an Emacs Lisp function especially
2859designed for sending a one line message to a user.  (*Note The ‘message’
2860function: message.)  In summary, the ‘message’ function prints its first
2861argument in the echo area as is, except for occurrences of ‘%d’ or ‘%s’
2862(and various other %-sequences which we have not mentioned).  When it
2863sees a control sequence, the function looks to the second or subsequent
2864arguments and prints the value of the argument in the location in the
2865string where the control sequence is located.
2866
2867   In the interactive ‘multiply-by-seven’ function, the control string
2868is ‘%d’, which requires a number, and the value returned by evaluating
2869‘(* 7 5)’ is the number 35.  Consequently, the number 35 is printed in
2870place of the ‘%d’ and the message is ‘The result is 35’.
2871
2872   (Note that when you call the function ‘multiply-by-seven’, the
2873message is printed without quotes, but when you call ‘message’, the text
2874is printed in double quotes.  This is because the value returned by
2875‘message’ is what appears in the echo area when you evaluate an
2876expression whose first element is ‘message’; but when embedded in a
2877function, ‘message’ prints the text as a side effect without quotes.)
2878
2879
2880File: eintr.info,  Node: Interactive Options,  Next: Permanent Installation,  Prev: Interactive,  Up: Writing Defuns
2881
28823.4 Different Options for ‘interactive’
2883=======================================
2884
2885In the example, ‘multiply-by-seven’ used ‘"p"’ as the argument to
2886‘interactive’.  This argument told Emacs to interpret your typing either
2887‘C-u’ followed by a number or <META> followed by a number as a command
2888to pass that number to the function as its argument.  Emacs has more
2889than twenty characters predefined for use with ‘interactive’.  In almost
2890every case, one of these options will enable you to pass the right
2891information interactively to a function.  (*Note Code Characters for
2892‘interactive’: (elisp)Interactive Codes.)
2893
2894   Consider the function ‘zap-to-char’.  Its interactive expression is
2895
2896     (interactive "p\ncZap to char: ")
2897
2898   The first part of the argument to ‘interactive’ is ‘p’, with which
2899you are already familiar.  This argument tells Emacs to interpret a
2900prefix, as a number to be passed to the function.  You can specify a
2901prefix either by typing ‘C-u’ followed by a number or by typing <META>
2902followed by a number.  The prefix is the number of specified characters.
2903Thus, if your prefix is three and the specified character is ‘x’, then
2904you will delete all the text up to and including the third next ‘x’.  If
2905you do not set a prefix, then you delete all the text up to and
2906including the specified character, but no more.
2907
2908   The ‘c’ tells the function the name of the character to which to
2909delete.
2910
2911   More formally, a function with two or more arguments can have
2912information passed to each argument by adding parts to the string that
2913follows ‘interactive’.  When you do this, the information is passed to
2914each argument in the same order it is specified in the ‘interactive’
2915list.  In the string, each part is separated from the next part by a
2916‘\n’, which is a newline.  For example, you can follow ‘p’ with a ‘\n’
2917and an ‘cZap to char: ’.  This causes Emacs to pass the value of the
2918prefix argument (if there is one) and the character.
2919
2920   In this case, the function definition looks like the following, where
2921‘arg’ and ‘char’ are the symbols to which ‘interactive’ binds the prefix
2922argument and the specified character:
2923
2924     (defun NAME-OF-FUNCTION (arg char)
2925       "DOCUMENTATION..."
2926       (interactive "p\ncZap to char: ")
2927       BODY-OF-FUNCTION...)
2928
2929(The space after the colon in the prompt makes it look better when you
2930are prompted.  *Note The Definition of ‘copy-to-buffer’: copy-to-buffer,
2931for an example.)
2932
2933   When a function does not take arguments, ‘interactive’ does not
2934require any.  Such a function contains the simple expression
2935‘(interactive)’.  The ‘mark-whole-buffer’ function is like this.
2936
2937   Alternatively, if the special letter-codes are not right for your
2938application, you can pass your own arguments to ‘interactive’ as a list.
2939
2940   *Note The Definition of ‘append-to-buffer’: append-to-buffer, for an
2941example.  *Note Using ‘Interactive’: (elisp)Using Interactive, for a
2942more complete explanation about this technique.
2943
2944
2945File: eintr.info,  Node: Permanent Installation,  Next: let,  Prev: Interactive Options,  Up: Writing Defuns
2946
29473.5 Install Code Permanently
2948============================
2949
2950When you install a function definition by evaluating it, it will stay
2951installed until you quit Emacs.  The next time you start a new session
2952of Emacs, the function will not be installed unless you evaluate the
2953function definition again.
2954
2955   At some point, you may want to have code installed automatically
2956whenever you start a new session of Emacs.  There are several ways of
2957doing this:
2958
2959   • If you have code that is just for yourself, you can put the code
2960     for the function definition in your ‘.emacs’ initialization file.
2961     When you start Emacs, your ‘.emacs’ file is automatically evaluated
2962     and all the function definitions within it are installed.  *Note
2963     Your ‘.emacs’ File: Emacs Initialization.
2964
2965   • Alternatively, you can put the function definitions that you want
2966     installed in one or more files of their own and use the ‘load’
2967     function to cause Emacs to evaluate and thereby install each of the
2968     functions in the files.  *Note Loading Files: Loading Files.
2969
2970   • Thirdly, if you have code that your whole site will use, it is
2971     usual to put it in a file called ‘site-init.el’ that is loaded when
2972     Emacs is built.  This makes the code available to everyone who uses
2973     your machine.  (See the ‘INSTALL’ file that is part of the Emacs
2974     distribution.)
2975
2976   Finally, if you have code that everyone who uses Emacs may want, you
2977can post it on a computer network or send a copy to the Free Software
2978Foundation.  (When you do this, please license the code and its
2979documentation under a license that permits other people to run, copy,
2980study, modify, and redistribute the code and which protects you from
2981having your work taken from you.)  If you send a copy of your code to
2982the Free Software Foundation, and properly protect yourself and others,
2983it may be included in the next release of Emacs.  In large part, this is
2984how Emacs has grown over the past years, by donations.
2985
2986
2987File: eintr.info,  Node: let,  Next: if,  Prev: Permanent Installation,  Up: Writing Defuns
2988
29893.6 ‘let’
2990=========
2991
2992The ‘let’ expression is a special form in Lisp that you will need to use
2993in most function definitions.
2994
2995   ‘let’ is used to attach or bind a symbol to a value in such a way
2996that the Lisp interpreter will not confuse the variable with a variable
2997of the same name that is not part of the function.
2998
2999   To understand why the ‘let’ special form is necessary, consider the
3000situation in which you own a home that you generally refer to as “the
3001house”, as in the sentence, “The house needs painting.” If you are
3002visiting a friend and your host refers to “the house”, he is likely to
3003be referring to _his_ house, not yours, that is, to a different house.
3004
3005   If your friend is referring to his house and you think he is
3006referring to your house, you may be in for some confusion.  The same
3007thing could happen in Lisp if a variable that is used inside of one
3008function has the same name as a variable that is used inside of another
3009function, and the two are not intended to refer to the same value.  The
3010‘let’ special form prevents this kind of confusion.
3011
3012* Menu:
3013
3014* Prevent confusion::
3015* Parts of let Expression::
3016* Sample let Expression::
3017* Uninitialized let Variables::
3018
3019
3020File: eintr.info,  Node: Prevent confusion,  Next: Parts of let Expression,  Up: let
3021
3022‘let’ Prevents Confusion
3023------------------------
3024
3025The ‘let’ special form prevents confusion.  ‘let’ creates a name for a
3026“local variable” that overshadows any use of the same name outside the
3027‘let’ expression.  This is like understanding that whenever your host
3028refers to “the house”, he means his house, not yours.  (Symbols used in
3029argument lists work the same way.  *Note The ‘defun’ Macro: defun.)
3030
3031   Local variables created by a ‘let’ expression retain their value
3032_only_ within the ‘let’ expression itself (and within expressions called
3033within the ‘let’ expression); the local variables have no effect outside
3034the ‘let’ expression.
3035
3036   Another way to think about ‘let’ is that it is like a ‘setq’ that is
3037temporary and local.  The values set by ‘let’ are automatically undone
3038when the ‘let’ is finished.  The setting only affects expressions that
3039are inside the bounds of the ‘let’ expression.  In computer science
3040jargon, we would say the binding of a symbol is visible only in
3041functions called in the ‘let’ form; in Emacs Lisp, the default scoping
3042is dynamic, not lexical.  (The non-default lexical binding is not
3043discussed in this manual.)
3044
3045   ‘let’ can create more than one variable at once.  Also, ‘let’ gives
3046each variable it creates an initial value, either a value specified by
3047you, or ‘nil’.  (In the jargon, this is binding the variable to the
3048value.)  After ‘let’ has created and bound the variables, it executes
3049the code in the body of the ‘let’, and returns the value of the last
3050expression in the body, as the value of the whole ‘let’ expression.
3051(“Execute” is a jargon term that means to evaluate a list; it comes from
3052the use of the word meaning “to give practical effect to” (‘Oxford
3053English Dictionary’).  Since you evaluate an expression to perform an
3054action, “execute” has evolved as a synonym to “evaluate”.)
3055
3056
3057File: eintr.info,  Node: Parts of let Expression,  Next: Sample let Expression,  Prev: Prevent confusion,  Up: let
3058
30593.6.1 The Parts of a ‘let’ Expression
3060-------------------------------------
3061
3062A ‘let’ expression is a list of three parts.  The first part is the
3063symbol ‘let’.  The second part is a list, called a “varlist”, each
3064element of which is either a symbol by itself or a two-element list, the
3065first element of which is a symbol.  The third part of the ‘let’
3066expression is the body of the ‘let’.  The body usually consists of one
3067or more lists.
3068
3069   A template for a ‘let’ expression looks like this:
3070
3071     (let VARLIST BODY...)
3072
3073The symbols in the varlist are the variables that are given initial
3074values by the ‘let’ special form.  Symbols by themselves are given the
3075initial value of ‘nil’; and each symbol that is the first element of a
3076two-element list is bound to the value that is returned when the Lisp
3077interpreter evaluates the second element.
3078
3079   Thus, a varlist might look like this: ‘(thread (needles 3))’.  In
3080this case, in a ‘let’ expression, Emacs binds the symbol ‘thread’ to an
3081initial value of ‘nil’, and binds the symbol ‘needles’ to an initial
3082value of 3.
3083
3084   When you write a ‘let’ expression, what you do is put the appropriate
3085expressions in the slots of the ‘let’ expression template.
3086
3087   If the varlist is composed of two-element lists, as is often the
3088case, the template for the ‘let’ expression looks like this:
3089
3090     (let ((VARIABLE VALUE)
3091           (VARIABLE VALUE)
3092           ...)
3093       BODY...)
3094
3095
3096File: eintr.info,  Node: Sample let Expression,  Next: Uninitialized let Variables,  Prev: Parts of let Expression,  Up: let
3097
30983.6.2 Sample ‘let’ Expression
3099-----------------------------
3100
3101The following expression creates and gives initial values to the two
3102variables ‘zebra’ and ‘tiger’.  The body of the ‘let’ expression is a
3103list which calls the ‘message’ function.
3104
3105     (let ((zebra "stripes")
3106           (tiger "fierce"))
3107       (message "One kind of animal has %s and another is %s."
3108                zebra tiger))
3109
3110   Here, the varlist is ‘((zebra "stripes") (tiger "fierce"))’.
3111
3112   The two variables are ‘zebra’ and ‘tiger’.  Each variable is the
3113first element of a two-element list and each value is the second element
3114of its two-element list.  In the varlist, Emacs binds the variable
3115‘zebra’ to the value ‘"stripes"’(1), and binds the variable ‘tiger’ to
3116the value ‘"fierce"’.  In this example, both values are strings.  The
3117values could just as well have been another list or a symbol.  The body
3118of the ‘let’ follows after the list holding the variables.  In this
3119example, the body is a list that uses the ‘message’ function to print a
3120string in the echo area.
3121
3122   You may evaluate the example in the usual fashion, by placing the
3123cursor after the last parenthesis and typing ‘C-x C-e’.  When you do
3124this, the following will appear in the echo area:
3125
3126     "One kind of animal has stripes and another is fierce."
3127
3128   As we have seen before, the ‘message’ function prints its first
3129argument, except for ‘%s’.  In this example, the value of the variable
3130‘zebra’ is printed at the location of the first ‘%s’ and the value of
3131the variable ‘tiger’ is printed at the location of the second ‘%s’.
3132
3133   ---------- Footnotes ----------
3134
3135   (1) According to Jared Diamond in ‘Guns, Germs, and Steel’, “...
3136zebras become impossibly dangerous as they grow older” but the claim
3137here is that they do not become fierce like a tiger.  (1997, W. W.
3138Norton and Co., ISBN 0-393-03894-2, page 171)
3139
3140
3141File: eintr.info,  Node: Uninitialized let Variables,  Prev: Sample let Expression,  Up: let
3142
31433.6.3 Uninitialized Variables in a ‘let’ Statement
3144--------------------------------------------------
3145
3146If you do not bind the variables in a ‘let’ statement to specific
3147initial values, they will automatically be bound to an initial value of
3148‘nil’, as in the following expression:
3149
3150     (let ((birch 3)
3151           pine
3152           fir
3153           (oak 'some))
3154       (message
3155        "Here are %d variables with %s, %s, and %s value."
3156        birch pine fir oak))
3157
3158Here, the varlist is ‘((birch 3) pine fir (oak 'some))’.
3159
3160   If you evaluate this expression in the usual way, the following will
3161appear in your echo area:
3162
3163     "Here are 3 variables with nil, nil, and some value."
3164
3165In this example, Emacs binds the symbol ‘birch’ to the number 3, binds
3166the symbols ‘pine’ and ‘fir’ to ‘nil’, and binds the symbol ‘oak’ to the
3167value ‘some’.
3168
3169   Note that in the first part of the ‘let’, the variables ‘pine’ and
3170‘fir’ stand alone as atoms that are not surrounded by parentheses; this
3171is because they are being bound to ‘nil’, the empty list.  But ‘oak’ is
3172bound to ‘some’ and so is a part of the list ‘(oak 'some)’.  Similarly,
3173‘birch’ is bound to the number 3 and so is in a list with that number.
3174(Since a number evaluates to itself, the number does not need to be
3175quoted.  Also, the number is printed in the message using a ‘%d’ rather
3176than a ‘%s’.)  The four variables as a group are put into a list to
3177delimit them from the body of the ‘let’.
3178
3179
3180File: eintr.info,  Node: if,  Next: else,  Prev: let,  Up: Writing Defuns
3181
31823.7 The ‘if’ Special Form
3183=========================
3184
3185Another special form is the conditional ‘if’.  This form is used to
3186instruct the computer to make decisions.  You can write function
3187definitions without using ‘if’, but it is used often enough, and is
3188important enough, to be included here.  It is used, for example, in the
3189code for the function ‘beginning-of-buffer’.
3190
3191   The basic idea behind an ‘if’, is that _if_ a test is true, _then_ an
3192expression is evaluated.  If the test is not true, the expression is not
3193evaluated.  For example, you might make a decision such as, “if it is
3194warm and sunny, then go to the beach!”
3195
3196* Menu:
3197
3198* if in more detail::
3199* type-of-animal in detail::    An example of an ‘if’ expression.
3200
3201
3202File: eintr.info,  Node: if in more detail,  Next: type-of-animal in detail,  Up: if
3203
3204‘if’ in more detail
3205-------------------
3206
3207An ‘if’ expression written in Lisp does not use the word “then”; the
3208test and the action are the second and third elements of the list whose
3209first element is ‘if’.  Nonetheless, the test part of an ‘if’ expression
3210is often called the “if-part” and the second argument is often called
3211the “then-part”.
3212
3213   Also, when an ‘if’ expression is written, the true-or-false-test is
3214usually written on the same line as the symbol ‘if’, but the action to
3215carry out if the test is true, the then-part, is written on the second
3216and subsequent lines.  This makes the ‘if’ expression easier to read.
3217
3218     (if TRUE-OR-FALSE-TEST
3219         ACTION-TO-CARRY-OUT-IF-TEST-IS-TRUE)
3220
3221The true-or-false-test will be an expression that is evaluated by the
3222Lisp interpreter.
3223
3224   Here is an example that you can evaluate in the usual manner.  The
3225test is whether the number 5 is greater than the number 4.  Since it is,
3226the message ‘5 is greater than 4!’ will be printed.
3227
3228     (if (> 5 4)                             ; if-part
3229         (message "5 is greater than 4!"))   ; then-part
3230
3231(The function ‘>’ tests whether its first argument is greater than its
3232second argument and returns true if it is.)
3233
3234   Of course, in actual use, the test in an ‘if’ expression will not be
3235fixed for all time as it is by the expression ‘(> 5 4)’.  Instead, at
3236least one of the variables used in the test will be bound to a value
3237that is not known ahead of time.  (If the value were known ahead of
3238time, we would not need to run the test!)
3239
3240   For example, the value may be bound to an argument of a function
3241definition.  In the following function definition, the character of the
3242animal is a value that is passed to the function.  If the value bound to
3243‘characteristic’ is ‘"fierce"’, then the message, ‘It is a tiger!’ will
3244be printed; otherwise, ‘nil’ will be returned.
3245
3246     (defun type-of-animal (characteristic)
3247       "Print message in echo area depending on CHARACTERISTIC.
3248     If the CHARACTERISTIC is the string \"fierce\",
3249     then warn of a tiger."
3250       (if (equal characteristic "fierce")
3251           (message "It is a tiger!")))
3252
3253If you are reading this inside of GNU Emacs, you can evaluate the
3254function definition in the usual way to install it in Emacs, and then
3255you can evaluate the following two expressions to see the results:
3256
3257     (type-of-animal "fierce")
3258
3259     (type-of-animal "striped")
3260
3261
3262When you evaluate ‘(type-of-animal "fierce")’, you will see the
3263following message printed in the echo area: ‘"It is a tiger!"’; and when
3264you evaluate ‘(type-of-animal "striped")’ you will see ‘nil’ printed in
3265the echo area.
3266
3267
3268File: eintr.info,  Node: type-of-animal in detail,  Prev: if in more detail,  Up: if
3269
32703.7.1 The ‘type-of-animal’ Function in Detail
3271---------------------------------------------
3272
3273Let’s look at the ‘type-of-animal’ function in detail.
3274
3275   The function definition for ‘type-of-animal’ was written by filling
3276the slots of two templates, one for a function definition as a whole,
3277and a second for an ‘if’ expression.
3278
3279   The template for every function that is not interactive is:
3280
3281     (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
3282       "DOCUMENTATION..."
3283       BODY...)
3284
3285   The parts of the function that match this template look like this:
3286
3287     (defun type-of-animal (characteristic)
3288       "Print message in echo area depending on CHARACTERISTIC.
3289     If the CHARACTERISTIC is the string \"fierce\",
3290     then warn of a tiger."
3291       BODY: THE if EXPRESSION)
3292
3293   The name of function is ‘type-of-animal’; it is passed the value of
3294one argument.  The argument list is followed by a multi-line
3295documentation string.  The documentation string is included in the
3296example because it is a good habit to write documentation string for
3297every function definition.  The body of the function definition consists
3298of the ‘if’ expression.
3299
3300   The template for an ‘if’ expression looks like this:
3301
3302     (if TRUE-OR-FALSE-TEST
3303         ACTION-TO-CARRY-OUT-IF-THE-TEST-RETURNS-TRUE)
3304
3305   In the ‘type-of-animal’ function, the code for the ‘if’ looks like
3306this:
3307
3308     (if (equal characteristic "fierce")
3309         (message "It is a tiger!"))
3310
3311   Here, the true-or-false-test is the expression:
3312
3313     (equal characteristic "fierce")
3314
3315In Lisp, ‘equal’ is a function that determines whether its first
3316argument is equal to its second argument.  The second argument is the
3317string ‘"fierce"’ and the first argument is the value of the symbol
3318‘characteristic’—in other words, the argument passed to this function.
3319
3320   In the first exercise of ‘type-of-animal’, the argument ‘"fierce"’ is
3321passed to ‘type-of-animal’.  Since ‘"fierce"’ is equal to ‘"fierce"’,
3322the expression, ‘(equal characteristic "fierce")’, returns a value of
3323true.  When this happens, the ‘if’ evaluates the second argument or
3324then-part of the ‘if’: ‘(message "It is a tiger!")’.
3325
3326   On the other hand, in the second exercise of ‘type-of-animal’, the
3327argument ‘"striped"’ is passed to ‘type-of-animal’.  ‘"striped"’ is not
3328equal to ‘"fierce"’, so the then-part is not evaluated and ‘nil’ is
3329returned by the ‘if’ expression.
3330
3331
3332File: eintr.info,  Node: else,  Next: Truth & Falsehood,  Prev: if,  Up: Writing Defuns
3333
33343.8 If–then–else Expressions
3335============================
3336
3337An ‘if’ expression may have an optional third argument, called the
3338“else-part”, for the case when the true-or-false-test returns false.
3339When this happens, the second argument or then-part of the overall ‘if’
3340expression is _not_ evaluated, but the third or else-part _is_
3341evaluated.  You might think of this as the cloudy day alternative for
3342the decision “if it is warm and sunny, then go to the beach, else read a
3343book!”.
3344
3345   The word “else” is not written in the Lisp code; the else-part of an
3346‘if’ expression comes after the then-part.  In the written Lisp, the
3347else-part is usually written to start on a line of its own and is
3348indented less than the then-part:
3349
3350     (if TRUE-OR-FALSE-TEST
3351         ACTION-TO-CARRY-OUT-IF-THE-TEST-RETURNS-TRUE
3352       ACTION-TO-CARRY-OUT-IF-THE-TEST-RETURNS-FALSE)
3353
3354   For example, the following ‘if’ expression prints the message ‘4 is
3355not greater than 5!’ when you evaluate it in the usual way:
3356
3357     (if (> 4 5)                               ; if-part
3358         (message "4 falsely greater than 5!") ; then-part
3359       (message "4 is not greater than 5!"))   ; else-part
3360
3361Note that the different levels of indentation make it easy to
3362distinguish the then-part from the else-part.  (GNU Emacs has several
3363commands that automatically indent ‘if’ expressions correctly.  *Note
3364GNU Emacs Helps You Type Lists: Typing Lists.)
3365
3366   We can extend the ‘type-of-animal’ function to include an else-part
3367by simply incorporating an additional part to the ‘if’ expression.
3368
3369   You can see the consequences of doing this if you evaluate the
3370following version of the ‘type-of-animal’ function definition to install
3371it and then evaluate the two subsequent expressions to pass different
3372arguments to the function.
3373
3374     (defun type-of-animal (characteristic)  ; Second version.
3375       "Print message in echo area depending on CHARACTERISTIC.
3376     If the CHARACTERISTIC is the string \"fierce\",
3377     then warn of a tiger; else say it is not fierce."
3378       (if (equal characteristic "fierce")
3379           (message "It is a tiger!")
3380         (message "It is not fierce!")))
3381
3382     (type-of-animal "fierce")
3383
3384     (type-of-animal "striped")
3385
3386
3387When you evaluate ‘(type-of-animal "fierce")’, you will see the
3388following message printed in the echo area: ‘"It is a tiger!"’; but when
3389you evaluate ‘(type-of-animal "striped")’, you will see ‘"It is not
3390fierce!"’.
3391
3392   (Of course, if the CHARACTERISTIC were ‘"ferocious"’, the message
3393‘"It is not fierce!"’ would be printed; and it would be misleading!
3394When you write code, you need to take into account the possibility that
3395some such argument will be tested by the ‘if’ and write your program
3396accordingly.)
3397
3398
3399File: eintr.info,  Node: Truth & Falsehood,  Next: save-excursion,  Prev: else,  Up: Writing Defuns
3400
34013.9 Truth and Falsehood in Emacs Lisp
3402=====================================
3403
3404There is an important aspect to the truth test in an ‘if’ expression.
3405So far, we have spoken of “true” and “false” as values of predicates as
3406if they were new kinds of Emacs Lisp objects.  In fact, “false” is just
3407our old friend ‘nil’.  Anything else—anything at all—is “true”.
3408
3409   The expression that tests for truth is interpreted as “true” if the
3410result of evaluating it is a value that is not ‘nil’.  In other words,
3411the result of the test is considered true if the value returned is a
3412number such as 47, a string such as ‘"hello"’, or a symbol (other than
3413‘nil’) such as ‘flowers’, or a list (so long as it is not empty), or
3414even a buffer!
3415
3416* Menu:
3417
3418* nil explained::               ‘nil’ has two meanings.
3419
3420
3421File: eintr.info,  Node: nil explained,  Up: Truth & Falsehood
3422
3423An explanation of ‘nil’
3424-----------------------
3425
3426Before illustrating a test for truth, we need an explanation of ‘nil’.
3427
3428   In Emacs Lisp, the symbol ‘nil’ has two meanings.  First, it means
3429the empty list.  Second, it means false and is the value returned when a
3430true-or-false-test tests false.  ‘nil’ can be written as an empty list,
3431‘()’, or as ‘nil’.  As far as the Lisp interpreter is concerned, ‘()’
3432and ‘nil’ are the same.  Humans, however, tend to use ‘nil’ for false
3433and ‘()’ for the empty list.
3434
3435   In Emacs Lisp, any value that is not ‘nil’—is not the empty list—is
3436considered true.  This means that if an evaluation returns something
3437that is not an empty list, an ‘if’ expression will test true.  For
3438example, if a number is put in the slot for the test, it will be
3439evaluated and will return itself, since that is what numbers do when
3440evaluated.  In this conditional, the ‘if’ expression will test true.
3441The expression tests false only when ‘nil’, an empty list, is returned
3442by evaluating the expression.
3443
3444   You can see this by evaluating the two expressions in the following
3445examples.
3446
3447   In the first example, the number 4 is evaluated as the test in the
3448‘if’ expression and returns itself; consequently, the then-part of the
3449expression is evaluated and returned: ‘true’ appears in the echo area.
3450In the second example, the ‘nil’ indicates false; consequently, the
3451else-part of the expression is evaluated and returned: ‘false’ appears
3452in the echo area.
3453
3454     (if 4
3455         'true
3456       'false)
3457
3458     (if nil
3459         'true
3460       'false)
3461
3462   Incidentally, if some other useful value is not available for a test
3463that returns true, then the Lisp interpreter will return the symbol ‘t’
3464for true.  For example, the expression ‘(> 5 4)’ returns ‘t’ when
3465evaluated, as you can see by evaluating it in the usual way:
3466
3467     (> 5 4)
3468
3469On the other hand, this function returns ‘nil’ if the test is false.
3470
3471     (> 4 5)
3472
3473
3474File: eintr.info,  Node: save-excursion,  Next: Review,  Prev: Truth & Falsehood,  Up: Writing Defuns
3475
34763.10 ‘save-excursion’
3477=====================
3478
3479The ‘save-excursion’ function is the final special form that we will
3480discuss in this chapter.
3481
3482   In Emacs Lisp programs used for editing, the ‘save-excursion’
3483function is very common.  It saves the location of point, executes the
3484body of the function, and then restores point to its previous position
3485if its location was changed.  Its primary purpose is to keep the user
3486from being surprised and disturbed by unexpected movement of point.
3487
3488* Menu:
3489
3490* Point and mark::              A review of various locations.
3491* Template for save-excursion::
3492
3493
3494File: eintr.info,  Node: Point and mark,  Next: Template for save-excursion,  Up: save-excursion
3495
3496Point and Mark
3497--------------
3498
3499Before discussing ‘save-excursion’, however, it may be useful first to
3500review what point and mark are in GNU Emacs.  “Point” is the current
3501location of the cursor.  Wherever the cursor is, that is point.  More
3502precisely, on terminals where the cursor appears to be on top of a
3503character, point is immediately before the character.  In Emacs Lisp,
3504point is an integer.  The first character in a buffer is number one, the
3505second is number two, and so on.  The function ‘point’ returns the
3506current position of the cursor as a number.  Each buffer has its own
3507value for point.
3508
3509   The “mark” is another position in the buffer; its value can be set
3510with a command such as ‘C-<SPC>’ (‘set-mark-command’).  If a mark has
3511been set, you can use the command ‘C-x C-x’ (‘exchange-point-and-mark’)
3512to cause the cursor to jump to the mark and set the mark to be the
3513previous position of point.  In addition, if you set another mark, the
3514position of the previous mark is saved in the mark ring.  Many mark
3515positions can be saved this way.  You can jump the cursor to a saved
3516mark by typing ‘C-u C-<SPC>’ one or more times.
3517
3518   The part of the buffer between point and mark is called “the region”.
3519Numerous commands work on the region, including ‘center-region’,
3520‘count-lines-region’, ‘kill-region’, and ‘print-region’.
3521
3522   The ‘save-excursion’ special form saves the location of point and
3523restores this position after the code within the body of the special
3524form is evaluated by the Lisp interpreter.  Thus, if point were in the
3525beginning of a piece of text and some code moved point to the end of the
3526buffer, the ‘save-excursion’ would put point back to where it was
3527before, after the expressions in the body of the function were
3528evaluated.
3529
3530   In Emacs, a function frequently moves point as part of its internal
3531workings even though a user would not expect this.  For example,
3532‘count-lines-region’ moves point.  To prevent the user from being
3533bothered by jumps that are both unexpected and (from the user’s point of
3534view) unnecessary, ‘save-excursion’ is often used to keep point in the
3535location expected by the user.  The use of ‘save-excursion’ is good
3536housekeeping.
3537
3538   To make sure the house stays clean, ‘save-excursion’ restores the
3539value of point even if something goes wrong in the code inside of it
3540(or, to be more precise and to use the proper jargon, “in case of
3541abnormal exit”).  This feature is very helpful.
3542
3543   In addition to recording the value of point, ‘save-excursion’ keeps
3544track of the current buffer, and restores it, too.  This means you can
3545write code that will change the buffer and have ‘save-excursion’ switch
3546you back to the original buffer.  This is how ‘save-excursion’ is used
3547in ‘append-to-buffer’.  (*Note The Definition of ‘append-to-buffer’:
3548append-to-buffer.)
3549
3550
3551File: eintr.info,  Node: Template for save-excursion,  Prev: Point and mark,  Up: save-excursion
3552
35533.10.1 Template for a ‘save-excursion’ Expression
3554-------------------------------------------------
3555
3556The template for code using ‘save-excursion’ is simple:
3557
3558     (save-excursion
3559       BODY...)
3560
3561The body of the function is one or more expressions that will be
3562evaluated in sequence by the Lisp interpreter.  If there is more than
3563one expression in the body, the value of the last one will be returned
3564as the value of the ‘save-excursion’ function.  The other expressions in
3565the body are evaluated only for their side effects; and ‘save-excursion’
3566itself is used only for its side effect (which is restoring the position
3567of point).
3568
3569   In more detail, the template for a ‘save-excursion’ expression looks
3570like this:
3571
3572     (save-excursion
3573       FIRST-EXPRESSION-IN-BODY
3574       SECOND-EXPRESSION-IN-BODY
3575       THIRD-EXPRESSION-IN-BODY
3576        ...
3577       LAST-EXPRESSION-IN-BODY)
3578
3579An expression, of course, may be a symbol on its own or a list.
3580
3581   In Emacs Lisp code, a ‘save-excursion’ expression often occurs within
3582the body of a ‘let’ expression.  It looks like this:
3583
3584     (let VARLIST
3585       (save-excursion
3586         BODY...))
3587
3588
3589File: eintr.info,  Node: Review,  Next: defun Exercises,  Prev: save-excursion,  Up: Writing Defuns
3590
35913.11 Review
3592===========
3593
3594In the last few chapters we have introduced a macro and a fair number of
3595functions and special forms.  Here they are described in brief, along
3596with a few similar functions that have not been mentioned yet.
3597
3598‘eval-last-sexp’
3599     Evaluate the last symbolic expression before the current location
3600     of point.  The value is printed in the echo area unless the
3601     function is invoked with an argument; in that case, the output is
3602     printed in the current buffer.  This command is normally bound to
3603     ‘C-x C-e’.
3604
3605‘defun’
3606     Define function.  This macro has up to five parts: the name, a
3607     template for the arguments that will be passed to the function,
3608     documentation, an optional interactive declaration, and the body of
3609     the definition.
3610
3611     For example, in Emacs the function definition of
3612     ‘dired-unmark-all-marks’ is as follows.
3613
3614          (defun dired-unmark-all-marks ()
3615            "Remove all marks from all files in the Dired buffer."
3616            (interactive)
3617            (dired-unmark-all-files ?\r))
3618
3619‘interactive’
3620     Declare to the interpreter that the function can be used
3621     interactively.  This special form may be followed by a string with
3622     one or more parts that pass the information to the arguments of the
3623     function, in sequence.  These parts may also tell the interpreter
3624     to prompt for information.  Parts of the string are separated by
3625     newlines, ‘\n’.
3626
3627     Common code characters are:
3628
3629     ‘b’
3630          The name of an existing buffer.
3631
3632     ‘f’
3633          The name of an existing file.
3634
3635     ‘p’
3636          The numeric prefix argument.  (Note that this ‘p’ is lower
3637          case.)
3638
3639     ‘r’
3640          Point and the mark, as two numeric arguments, smallest first.
3641          This is the only code letter that specifies two successive
3642          arguments rather than one.
3643
3644     *Note Code Characters for ‘interactive’: (elisp)Interactive Codes,
3645     for a complete list of code characters.
3646
3647‘let’
3648     Declare that a list of variables is for use within the body of the
3649     ‘let’ and give them an initial value, either ‘nil’ or a specified
3650     value; then evaluate the rest of the expressions in the body of the
3651     ‘let’ and return the value of the last one.  Inside the body of the
3652     ‘let’, the Lisp interpreter does not see the values of the
3653     variables of the same names that are bound outside of the ‘let’.
3654
3655     For example,
3656
3657          (let ((foo (buffer-name))
3658                (bar (buffer-size)))
3659            (message
3660             "This buffer is %s and has %d characters."
3661             foo bar))
3662
3663‘save-excursion’
3664     Record the values of point and the current buffer before evaluating
3665     the body of this special form.  Restore the value of point and
3666     buffer afterward.
3667
3668     For example,
3669
3670          (message "We are %d characters into this buffer."
3671                   (- (point)
3672                      (save-excursion
3673                        (goto-char (point-min)) (point))))
3674
3675‘if’
3676     Evaluate the first argument to the function; if it is true,
3677     evaluate the second argument; else evaluate the third argument, if
3678     there is one.
3679
3680     The ‘if’ special form is called a “conditional”.  There are other
3681     conditionals in Emacs Lisp, but ‘if’ is perhaps the most commonly
3682     used.
3683
3684     For example,
3685
3686          (if (= 22 emacs-major-version)
3687              (message "This is version 22 Emacs")
3688            (message "This is not version 22 Emacs"))
3689
3690‘<’
3691‘>’
3692‘<=’
3693‘>=’
3694     The ‘<’ function tests whether its first argument is smaller than
3695     its second argument.  A corresponding function, ‘>’, tests whether
3696     the first argument is greater than the second.  Likewise, ‘<=’
3697     tests whether the first argument is less than or equal to the
3698     second and ‘>=’ tests whether the first argument is greater than or
3699     equal to the second.  In all cases, both arguments must be numbers
3700     or markers (markers indicate positions in buffers).
3701
3702‘=’
3703     The ‘=’ function tests whether two arguments, both numbers or
3704     markers, are equal.
3705
3706‘equal’
3707‘eq’
3708     Test whether two objects are the same.  ‘equal’ uses one meaning of
3709     the word “same” and ‘eq’ uses another: ‘equal’ returns true if the
3710     two objects have a similar structure and contents, such as two
3711     copies of the same book.  On the other hand, ‘eq’, returns true if
3712     both arguments are actually the same object.
3713
3714‘string<’
3715‘string-lessp’
3716‘string=’
3717‘string-equal’
3718     The ‘string-lessp’ function tests whether its first argument is
3719     smaller than the second argument.  A shorter, alternative name for
3720     the same function (a ‘defalias’) is ‘string<’.
3721
3722     The arguments to ‘string-lessp’ must be strings or symbols; the
3723     ordering is lexicographic, so case is significant.  The print names
3724     of symbols are used instead of the symbols themselves.
3725
3726     An empty string, ‘""’, a string with no characters in it, is
3727     smaller than any string of characters.
3728
3729     ‘string-equal’ provides the corresponding test for equality.  Its
3730     shorter, alternative name is ‘string=’.  There are no string test
3731     functions that correspond to >, ‘>=’, or ‘<=’.
3732
3733‘message’
3734     Print a message in the echo area.  The first argument is a string
3735     that can contain ‘%s’, ‘%d’, or ‘%c’ to print the value of
3736     arguments that follow the string.  The argument used by ‘%s’ must
3737     be a string or a symbol; the argument used by ‘%d’ must be a
3738     number.  The argument used by ‘%c’ must be an ASCII code number; it
3739     will be printed as the character with that ASCII code.  (Various
3740     other %-sequences have not been mentioned.)
3741
3742‘setq’
3743‘set’
3744     The ‘setq’ special form sets the value of its first argument to the
3745     value of the second argument.  The first argument is automatically
3746     quoted by ‘setq’.  It does the same for succeeding pairs of
3747     arguments.  Another function, ‘set’, takes only two arguments and
3748     evaluates both of them before setting the value returned by its
3749     first argument to the value returned by its second argument.
3750
3751‘buffer-name’
3752     Without an argument, return the name of the buffer, as a string.
3753
3754‘buffer-file-name’
3755     Without an argument, return the name of the file the buffer is
3756     visiting.
3757
3758‘current-buffer’
3759     Return the buffer in which Emacs is active; it may not be the
3760     buffer that is visible on the screen.
3761
3762‘other-buffer’
3763     Return the most recently selected buffer (other than the buffer
3764     passed to ‘other-buffer’ as an argument and other than the current
3765     buffer).
3766
3767‘switch-to-buffer’
3768     Select a buffer for Emacs to be active in and display it in the
3769     current window so users can look at it.  Usually bound to ‘C-x b’.
3770
3771‘set-buffer’
3772     Switch Emacs’s attention to a buffer on which programs will run.
3773     Don’t alter what the window is showing.
3774
3775‘buffer-size’
3776     Return the number of characters in the current buffer.
3777
3778‘point’
3779     Return the value of the current position of the cursor, as an
3780     integer counting the number of characters from the beginning of the
3781     buffer.
3782
3783‘point-min’
3784     Return the minimum permissible value of point in the current
3785     buffer.  This is 1, unless narrowing is in effect.
3786
3787‘point-max’
3788     Return the value of the maximum permissible value of point in the
3789     current buffer.  This is the end of the buffer, unless narrowing is
3790     in effect.
3791
3792
3793File: eintr.info,  Node: defun Exercises,  Prev: Review,  Up: Writing Defuns
3794
37953.12 Exercises
3796==============
3797
3798   • Write a non-interactive function that doubles the value of its
3799     argument, a number.  Make that function interactive.
3800
3801   • Write a function that tests whether the current value of
3802     ‘fill-column’ is greater than the argument passed to the function,
3803     and if so, prints an appropriate message.
3804
3805
3806File: eintr.info,  Node: Buffer Walk Through,  Next: More Complex,  Prev: Writing Defuns,  Up: Top
3807
38084 A Few Buffer-Related Functions
3809********************************
3810
3811In this chapter we study in detail several of the functions used in GNU
3812Emacs.  This is called a “walk-through”.  These functions are used as
3813examples of Lisp code, but are not imaginary examples; with the
3814exception of the first, simplified function definition, these functions
3815show the actual code used in GNU Emacs.  You can learn a great deal from
3816these definitions.  The functions described here are all related to
3817buffers.  Later, we will study other functions.
3818
3819* Menu:
3820
3821* Finding More::                How to find more information.
3822* simplified-beginning-of-buffer::  Shows ‘goto-char’,
3823                                ‘point-min’, and ‘push-mark’.
3824* mark-whole-buffer::           Almost the same as ‘beginning-of-buffer’.
3825* append-to-buffer::            Uses ‘save-excursion’ and
3826                                ‘insert-buffer-substring’.
3827* Buffer Related Review::       Review.
3828* Buffer Exercises::
3829
3830
3831File: eintr.info,  Node: Finding More,  Next: simplified-beginning-of-buffer,  Up: Buffer Walk Through
3832
38334.1 Finding More Information
3834============================
3835
3836In this walk-through, I will describe each new function as we come to
3837it, sometimes in detail and sometimes briefly.  If you are interested,
3838you can get the full documentation of any Emacs Lisp function at any
3839time by typing ‘C-h f’ and then the name of the function (and then
3840<RET>).  Similarly, you can get the full documentation for a variable by
3841typing ‘C-h v’ and then the name of the variable (and then <RET>).
3842
3843   Also, ‘describe-function’ will tell you the location of the function
3844definition.
3845
3846   Put point into the name of the file that contains the function and
3847press the <RET> key.  In this case, <RET> means ‘push-button’ rather
3848than “return” or “enter”.  Emacs will take you directly to the function
3849definition.
3850
3851   More generally, if you want to see a function in its original source
3852file, you can use the ‘xref-find-definitions’ function to jump to it.
3853‘xref-find-definitions’ works with a wide variety of languages, not just
3854Lisp, and C, and it works with non-programming text as well.  For
3855example, ‘xref-find-definitions’ will jump to the various nodes in the
3856Texinfo source file of this document (provided that you’ve run the
3857‘etags’ utility to record all the nodes in the manuals that come with
3858Emacs; *note (emacs)Create Tags Table::).
3859
3860   To use the ‘xref-find-definitions’ command, type ‘M-.’ (i.e., press
3861the period key while holding down the <META> key, or else type the <ESC>
3862key and then type the period key), and then, at the prompt, type in the
3863name of the function whose source code you want to see, such as
3864‘mark-whole-buffer’, and then type <RET>.  (If the command doesn’t
3865prompt, invoke it with an argument: ‘C-u M-.’; *note Interactive
3866Options::.)  Emacs will switch buffers and display the source code for
3867the function on your screen(1).  To switch back to your current buffer,
3868type ‘M-,’ or ‘C-x b <RET>’.  (On some keyboards, the <META> key is
3869labeled <ALT>.)
3870
3871   Incidentally, the files that contain Lisp code are conventionally
3872called “libraries”.  The metaphor is derived from that of a specialized
3873library, such as a law library or an engineering library, rather than a
3874general library.  Each library, or file, contains functions that relate
3875to a particular topic or activity, such as ‘abbrev.el’ for handling
3876abbreviations and other typing shortcuts, and ‘help.el’ for help.
3877(Sometimes several libraries provide code for a single activity, as the
3878various ‘rmail...’ files provide code for reading electronic mail.)  In
3879‘The GNU Emacs Manual’, you will see sentences such as “The ‘C-h p’
3880command lets you search the standard Emacs Lisp libraries by topic
3881keywords.”
3882
3883   ---------- Footnotes ----------
3884
3885   (1) If instead of showing the source code for a Lisp function, Emacs
3886asks you which tags table to visit, invoke ‘M-.’ from a buffer whose
3887major mode is Emacs Lisp or Lisp Interaction.
3888
3889
3890File: eintr.info,  Node: simplified-beginning-of-buffer,  Next: mark-whole-buffer,  Prev: Finding More,  Up: Buffer Walk Through
3891
38924.2 A Simplified ‘beginning-of-buffer’ Definition
3893=================================================
3894
3895The ‘beginning-of-buffer’ command is a good function to start with since
3896you are likely to be familiar with it and it is easy to understand.
3897Used as an interactive command, ‘beginning-of-buffer’ moves the cursor
3898to the beginning of the buffer, leaving the mark at the previous
3899position.  It is generally bound to ‘M-<’.
3900
3901   In this section, we will discuss a shortened version of the function
3902that shows how it is most frequently used.  This shortened function
3903works as written, but it does not contain the code for a complex option.
3904In another section, we will describe the entire function.  (*Note
3905Complete Definition of ‘beginning-of-buffer’: beginning-of-buffer.)
3906
3907   Before looking at the code, let’s consider what the function
3908definition has to contain: it must include an expression that makes the
3909function interactive so it can be called by typing ‘M-x
3910beginning-of-buffer’ or by typing a keychord such as ‘M-<’; it must
3911include code to leave a mark at the original position in the buffer; and
3912it must include code to move the cursor to the beginning of the buffer.
3913
3914   Here is the complete text of the shortened version of the function:
3915
3916     (defun simplified-beginning-of-buffer ()
3917       "Move point to the beginning of the buffer;
3918     leave mark at previous position."
3919       (interactive)
3920       (push-mark)
3921       (goto-char (point-min)))
3922
3923   Like all function definitions, this definition has five parts
3924following the macro ‘defun’:
3925
3926  1. The name: in this example, ‘simplified-beginning-of-buffer’.
3927
3928  2. A list of the arguments: in this example, an empty list, ‘()’,
3929
3930  3. The documentation string.
3931
3932  4. The interactive expression.
3933
3934  5. The body.
3935
3936In this function definition, the argument list is empty; this means that
3937this function does not require any arguments.  (When we look at the
3938definition for the complete function, we will see that it may be passed
3939an optional argument.)
3940
3941   The interactive expression tells Emacs that the function is intended
3942to be used interactively.  In this example, ‘interactive’ does not have
3943an argument because ‘simplified-beginning-of-buffer’ does not require
3944one.
3945
3946   The body of the function consists of the two lines:
3947
3948     (push-mark)
3949     (goto-char (point-min))
3950
3951   The first of these lines is the expression, ‘(push-mark)’.  When this
3952expression is evaluated by the Lisp interpreter, it sets a mark at the
3953current position of the cursor, wherever that may be.  The position of
3954this mark is saved in the mark ring.
3955
3956   The next line is ‘(goto-char (point-min))’.  This expression jumps
3957the cursor to the minimum point in the buffer, that is, to the beginning
3958of the buffer (or to the beginning of the accessible portion of the
3959buffer if it is narrowed.  *Note Narrowing and Widening: Narrowing &
3960Widening.)
3961
3962   The ‘push-mark’ command sets a mark at the place where the cursor was
3963located before it was moved to the beginning of the buffer by the
3964‘(goto-char (point-min))’ expression.  Consequently, you can, if you
3965wish, go back to where you were originally by typing ‘C-x C-x’.
3966
3967   That is all there is to the function definition!
3968
3969   When you are reading code such as this and come upon an unfamiliar
3970function, such as ‘goto-char’, you can find out what it does by using
3971the ‘describe-function’ command.  To use this command, type ‘C-h f’ and
3972then type in the name of the function and press <RET>.  The
3973‘describe-function’ command will print the function’s documentation
3974string in a ‘*Help*’ window.  For example, the documentation for
3975‘goto-char’ is:
3976
3977     Set point to POSITION, a number or marker.
3978     Beginning of buffer is position (point-min), end is (point-max).
3979
3980The function’s one argument is the desired position.
3981
3982(The prompt for ‘describe-function’ will offer you the symbol under or
3983preceding the cursor, so you can save typing by positioning the cursor
3984right over or after the function and then typing ‘C-h f <RET>’.)
3985
3986   The ‘end-of-buffer’ function definition is written in the same way as
3987the ‘beginning-of-buffer’ definition except that the body of the
3988function contains the expression ‘(goto-char (point-max))’ in place of
3989‘(goto-char (point-min))’.
3990
3991
3992File: eintr.info,  Node: mark-whole-buffer,  Next: append-to-buffer,  Prev: simplified-beginning-of-buffer,  Up: Buffer Walk Through
3993
39944.3 The Definition of ‘mark-whole-buffer’
3995=========================================
3996
3997The ‘mark-whole-buffer’ function is no harder to understand than the
3998‘simplified-beginning-of-buffer’ function.  In this case, however, we
3999will look at the complete function, not a shortened version.
4000
4001   The ‘mark-whole-buffer’ function is not as commonly used as the
4002‘beginning-of-buffer’ function, but is useful nonetheless: it marks a
4003whole buffer as a region by putting point at the beginning and a mark at
4004the end of the buffer.  It is generally bound to ‘C-x h’.
4005
4006* Menu:
4007
4008* mark-whole-buffer overview::
4009* Body of mark-whole-buffer::   Only three lines of code.
4010
4011
4012File: eintr.info,  Node: mark-whole-buffer overview,  Next: Body of mark-whole-buffer,  Up: mark-whole-buffer
4013
4014An overview of ‘mark-whole-buffer’
4015----------------------------------
4016
4017In GNU Emacs 22, the code for the complete function looks like this:
4018
4019     (defun mark-whole-buffer ()
4020       "Put point at beginning and mark at end of buffer.
4021     You probably should not use this function in Lisp programs;
4022     it is usually a mistake for a Lisp function to use any subroutine
4023     that uses or sets the mark."
4024       (interactive)
4025       (push-mark (point))
4026       (push-mark (point-max) nil t)
4027       (goto-char (point-min)))
4028
4029   Like all other functions, the ‘mark-whole-buffer’ function fits into
4030the template for a function definition.  The template looks like this:
4031
4032     (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
4033       "DOCUMENTATION..."
4034       (INTERACTIVE-EXPRESSION...)
4035       BODY...)
4036
4037   Here is how the function works: the name of the function is
4038‘mark-whole-buffer’; it is followed by an empty argument list, ‘()’,
4039which means that the function does not require arguments.  The
4040documentation comes next.
4041
4042   The next line is an ‘(interactive)’ expression that tells Emacs that
4043the function will be used interactively.  These details are similar to
4044the ‘simplified-beginning-of-buffer’ function described in the previous
4045section.
4046
4047
4048File: eintr.info,  Node: Body of mark-whole-buffer,  Prev: mark-whole-buffer overview,  Up: mark-whole-buffer
4049
40504.3.1 Body of ‘mark-whole-buffer’
4051---------------------------------
4052
4053The body of the ‘mark-whole-buffer’ function consists of three lines of
4054code:
4055
4056     (push-mark (point))
4057     (push-mark (point-max) nil t)
4058     (goto-char (point-min))
4059
4060   The first of these lines is the expression, ‘(push-mark (point))’.
4061
4062   This line does exactly the same job as the first line of the body of
4063the ‘simplified-beginning-of-buffer’ function, which is written
4064‘(push-mark)’.  In both cases, the Lisp interpreter sets a mark at the
4065current position of the cursor.
4066
4067   I don’t know why the expression in ‘mark-whole-buffer’ is written
4068‘(push-mark (point))’ and the expression in ‘beginning-of-buffer’ is
4069written ‘(push-mark)’.  Perhaps whoever wrote the code did not know that
4070the arguments for ‘push-mark’ are optional and that if ‘push-mark’ is
4071not passed an argument, the function automatically sets mark at the
4072location of point by default.  Or perhaps the expression was written so
4073as to parallel the structure of the next line.  In any case, the line
4074causes Emacs to determine the position of point and set a mark there.
4075
4076   In earlier versions of GNU Emacs, the next line of
4077‘mark-whole-buffer’ was ‘(push-mark (point-max))’.  This expression sets
4078a mark at the point in the buffer that has the highest number.  This
4079will be the end of the buffer (or, if the buffer is narrowed, the end of
4080the accessible portion of the buffer.  *Note Narrowing and Widening:
4081Narrowing & Widening, for more about narrowing.)  After this mark has
4082been set, the previous mark, the one set at point, is no longer set, but
4083Emacs remembers its position, just as all other recent marks are always
4084remembered.  This means that you can, if you wish, go back to that
4085position by typing ‘C-u C-<SPC>’ twice.
4086
4087   In GNU Emacs 22, the ‘(point-max)’ is slightly more complicated.  The
4088line reads
4089
4090     (push-mark (point-max) nil t)
4091
4092The expression works nearly the same as before.  It sets a mark at the
4093highest numbered place in the buffer that it can.  However, in this
4094version, ‘push-mark’ has two additional arguments.  The second argument
4095to ‘push-mark’ is ‘nil’.  This tells the function it _should_ display a
4096message that says “Mark set” when it pushes the mark.  The third
4097argument is ‘t’.  This tells ‘push-mark’ to activate the mark when
4098Transient Mark mode is turned on.  Transient Mark mode highlights the
4099currently active region.  It is often turned off.
4100
4101   Finally, the last line of the function is ‘(goto-char (point-min)))’.
4102This is written exactly the same way as it is written in
4103‘beginning-of-buffer’.  The expression moves the cursor to the minimum
4104point in the buffer, that is, to the beginning of the buffer (or to the
4105beginning of the accessible portion of the buffer).  As a result of
4106this, point is placed at the beginning of the buffer and mark is set at
4107the end of the buffer.  The whole buffer is, therefore, the region.
4108
4109
4110File: eintr.info,  Node: append-to-buffer,  Next: Buffer Related Review,  Prev: mark-whole-buffer,  Up: Buffer Walk Through
4111
41124.4 The Definition of ‘append-to-buffer’
4113========================================
4114
4115The ‘append-to-buffer’ command is more complex than the
4116‘mark-whole-buffer’ command.  What it does is copy the region (that is,
4117the part of the buffer between point and mark) from the current buffer
4118to a specified buffer.
4119
4120* Menu:
4121
4122* append-to-buffer overview::
4123* append interactive::          A two part interactive expression.
4124* append-to-buffer body::       Incorporates a ‘let’ expression.
4125* append save-excursion::       How the ‘save-excursion’ works.
4126
4127
4128File: eintr.info,  Node: append-to-buffer overview,  Next: append interactive,  Up: append-to-buffer
4129
4130An Overview of ‘append-to-buffer’
4131---------------------------------
4132
4133The ‘append-to-buffer’ command uses the ‘insert-buffer-substring’
4134function to copy the region.  ‘insert-buffer-substring’ is described by
4135its name: it takes a substring from a buffer, and inserts it into
4136another buffer.
4137
4138   Most of ‘append-to-buffer’ is concerned with setting up the
4139conditions for ‘insert-buffer-substring’ to work: the code must specify
4140both the buffer to which the text will go, the window it comes from and
4141goes to, and the region that will be copied.
4142
4143   Here is the complete text of the function:
4144
4145     (defun append-to-buffer (buffer start end)
4146       "Append to specified buffer the text of the region.
4147     It is inserted into that buffer before its point.
4148
4149     When calling from a program, give three arguments:
4150     BUFFER (or buffer name), START and END.
4151     START and END specify the portion of the current buffer to be copied."
4152       (interactive
4153        (list (read-buffer "Append to buffer: " (other-buffer
4154                                                 (current-buffer) t))
4155              (region-beginning) (region-end)))
4156       (let ((oldbuf (current-buffer)))
4157         (save-excursion
4158           (let* ((append-to (get-buffer-create buffer))
4159                  (windows (get-buffer-window-list append-to t t))
4160                  point)
4161             (set-buffer append-to)
4162             (setq point (point))
4163             (barf-if-buffer-read-only)
4164             (insert-buffer-substring oldbuf start end)
4165             (dolist (window windows)
4166               (when (= (window-point window) point)
4167                 (set-window-point window (point))))))))
4168
4169   The function can be understood by looking at it as a series of
4170filled-in templates.
4171
4172   The outermost template is for the function definition.  In this
4173function, it looks like this (with several slots filled in):
4174
4175     (defun append-to-buffer (buffer start end)
4176       "DOCUMENTATION..."
4177       (interactive ...)
4178       BODY...)
4179
4180   The first line of the function includes its name and three arguments.
4181The arguments are the ‘buffer’ to which the text will be copied, and the
4182‘start’ and ‘end’ of the region in the current buffer that will be
4183copied.
4184
4185   The next part of the function is the documentation, which is clear
4186and complete.  As is conventional, the three arguments are written in
4187upper case so you will notice them easily.  Even better, they are
4188described in the same order as in the argument list.
4189
4190   Note that the documentation distinguishes between a buffer and its
4191name.  (The function can handle either.)
4192
4193
4194File: eintr.info,  Node: append interactive,  Next: append-to-buffer body,  Prev: append-to-buffer overview,  Up: append-to-buffer
4195
41964.4.1 The ‘append-to-buffer’ Interactive Expression
4197---------------------------------------------------
4198
4199Since the ‘append-to-buffer’ function will be used interactively, the
4200function must have an ‘interactive’ expression.  (For a review of
4201‘interactive’, see *note Making a Function Interactive: Interactive.)
4202The expression reads as follows:
4203
4204     (interactive
4205      (list (read-buffer
4206             "Append to buffer: "
4207             (other-buffer (current-buffer) t))
4208            (region-beginning)
4209            (region-end)))
4210
4211This expression is not one with letters standing for parts, as described
4212earlier.  Instead, it starts a list with these parts:
4213
4214   The first part of the list is an expression to read the name of a
4215buffer and return it as a string.  That is ‘read-buffer’.  The function
4216requires a prompt as its first argument, ‘"Append to buffer: "’.  Its
4217second argument tells the command what value to provide if you don’t
4218specify anything.
4219
4220   In this case that second argument is an expression containing the
4221function ‘other-buffer’, an exception, and a ‘t’, standing for true.
4222
4223   The first argument to ‘other-buffer’, the exception, is yet another
4224function, ‘current-buffer’.  That is not going to be returned.  The
4225second argument is the symbol for true, ‘t’.  that tells ‘other-buffer’
4226that it may show visible buffers (except in this case, it will not show
4227the current buffer, which makes sense).
4228
4229   The expression looks like this:
4230
4231     (other-buffer (current-buffer) t)
4232
4233   The second and third arguments to the ‘list’ expression are
4234‘(region-beginning)’ and ‘(region-end)’.  These two functions specify
4235the beginning and end of the text to be appended.
4236
4237   Originally, the command used the letters ‘B’ and ‘r’.  The whole
4238‘interactive’ expression looked like this:
4239
4240     (interactive "BAppend to buffer: \nr")
4241
4242But when that was done, the default value of the buffer switched to was
4243invisible.  That was not wanted.
4244
4245   (The prompt was separated from the second argument with a newline,
4246‘\n’.  It was followed by an ‘r’ that told Emacs to bind the two
4247arguments that follow the symbol ‘buffer’ in the function’s argument
4248list (that is, ‘start’ and ‘end’) to the values of point and mark.  That
4249argument worked fine.)
4250
4251
4252File: eintr.info,  Node: append-to-buffer body,  Next: append save-excursion,  Prev: append interactive,  Up: append-to-buffer
4253
42544.4.2 The Body of ‘append-to-buffer’
4255------------------------------------
4256
4257The body of the ‘append-to-buffer’ function begins with ‘let’.
4258
4259   As we have seen before (*note ‘let’: let.), the purpose of a ‘let’
4260expression is to create and give initial values to one or more variables
4261that will only be used within the body of the ‘let’.  This means that
4262such a variable will not be confused with any variable of the same name
4263outside the ‘let’ expression.
4264
4265   We can see how the ‘let’ expression fits into the function as a whole
4266by showing a template for ‘append-to-buffer’ with the ‘let’ expression
4267in outline:
4268
4269     (defun append-to-buffer (buffer start end)
4270       "DOCUMENTATION..."
4271       (interactive ...)
4272       (let ((VARIABLE VALUE))
4273             BODY...)
4274
4275   The ‘let’ expression has three elements:
4276
4277  1. The symbol ‘let’;
4278
4279  2. A varlist containing, in this case, a single two-element list,
4280     ‘(VARIABLE VALUE)’;
4281
4282  3. The body of the ‘let’ expression.
4283
4284   In the ‘append-to-buffer’ function, the varlist looks like this:
4285
4286     (oldbuf (current-buffer))
4287
4288In this part of the ‘let’ expression, the one variable, ‘oldbuf’, is
4289bound to the value returned by the ‘(current-buffer)’ expression.  The
4290variable, ‘oldbuf’, is used to keep track of the buffer in which you are
4291working and from which you will copy.
4292
4293   The element or elements of a varlist are surrounded by a set of
4294parentheses so the Lisp interpreter can distinguish the varlist from the
4295body of the ‘let’.  As a consequence, the two-element list within the
4296varlist is surrounded by a circumscribing set of parentheses.  The line
4297looks like this:
4298
4299     (let ((oldbuf (current-buffer)))
4300       ... )
4301
4302The two parentheses before ‘oldbuf’ might surprise you if you did not
4303realize that the first parenthesis before ‘oldbuf’ marks the boundary of
4304the varlist and the second parenthesis marks the beginning of the
4305two-element list, ‘(oldbuf (current-buffer))’.
4306
4307
4308File: eintr.info,  Node: append save-excursion,  Prev: append-to-buffer body,  Up: append-to-buffer
4309
43104.4.3 ‘save-excursion’ in ‘append-to-buffer’
4311--------------------------------------------
4312
4313The body of the ‘let’ expression in ‘append-to-buffer’ consists of a
4314‘save-excursion’ expression.
4315
4316   The ‘save-excursion’ function saves the location of point, and
4317restores it to that position after the expressions in the body of the
4318‘save-excursion’ complete execution.  In addition, ‘save-excursion’
4319keeps track of the original buffer, and restores it.  This is how
4320‘save-excursion’ is used in ‘append-to-buffer’.
4321
4322   Incidentally, it is worth noting here that a Lisp function is
4323normally formatted so that everything that is enclosed in a multi-line
4324spread is indented more to the right than the first symbol.  In this
4325function definition, the ‘let’ is indented more than the ‘defun’, and
4326the ‘save-excursion’ is indented more than the ‘let’, like this:
4327
4328     (defun ...
4329       ...
4330       ...
4331       (let...
4332         (save-excursion
4333           ...
4334
4335This formatting convention makes it easy to see that the lines in the
4336body of the ‘save-excursion’ are enclosed by the parentheses associated
4337with ‘save-excursion’, just as the ‘save-excursion’ itself is enclosed
4338by the parentheses associated with the ‘let’:
4339
4340     (let ((oldbuf (current-buffer)))
4341       (save-excursion
4342         ...
4343         (set-buffer ...)
4344         (insert-buffer-substring oldbuf start end)
4345         ...))
4346
4347   The use of the ‘save-excursion’ function can be viewed as a process
4348of filling in the slots of a template:
4349
4350     (save-excursion
4351       FIRST-EXPRESSION-IN-BODY
4352       SECOND-EXPRESSION-IN-BODY
4353        ...
4354       LAST-EXPRESSION-IN-BODY)
4355
4356In this function, the body of the ‘save-excursion’ contains only one
4357expression, the ‘let*’ expression.  You know about a ‘let’ function.
4358The ‘let*’ function is different.  It has a ‘*’ in its name.  It enables
4359Emacs to set each variable in its varlist in sequence, one after
4360another.
4361
4362   Its critical feature is that variables later in the varlist can make
4363use of the values to which Emacs set variables earlier in the varlist.
4364*Note The ‘let*’ expression: fwd-para let.
4365
4366   We will skip functions like ‘let*’ and focus on two: the ‘set-buffer’
4367function and the ‘insert-buffer-substring’ function.
4368
4369   In the old days, the ‘set-buffer’ expression was simply
4370
4371     (set-buffer (get-buffer-create buffer))
4372
4373but now it is
4374
4375     (set-buffer append-to)
4376
4377‘append-to’ is bound to ‘(get-buffer-create buffer)’ earlier on in the
4378‘let*’ expression.  That extra binding would not be necessary except for
4379that ‘append-to’ is used later in the varlist as an argument to
4380‘get-buffer-window-list’.
4381
4382   The ‘append-to-buffer’ function definition inserts text from the
4383buffer in which you are currently to a named buffer.  It happens that
4384‘insert-buffer-substring’ does just the reverse—it copies text from
4385another buffer to the current buffer—that is why the ‘append-to-buffer’
4386definition starts out with a ‘let’ that binds the local symbol ‘oldbuf’
4387to the value returned by ‘current-buffer’.
4388
4389   The ‘insert-buffer-substring’ expression looks like this:
4390
4391     (insert-buffer-substring oldbuf start end)
4392
4393The ‘insert-buffer-substring’ function copies a string _from_ the buffer
4394specified as its first argument and inserts the string into the present
4395buffer.  In this case, the argument to ‘insert-buffer-substring’ is the
4396value of the variable created and bound by the ‘let’, namely the value
4397of ‘oldbuf’, which was the current buffer when you gave the
4398‘append-to-buffer’ command.
4399
4400   After ‘insert-buffer-substring’ has done its work, ‘save-excursion’
4401will restore the action to the original buffer and ‘append-to-buffer’
4402will have done its job.
4403
4404   Written in skeletal form, the workings of the body look like this:
4405
4406     (let (BIND-oldbuf-TO-VALUE-OF-current-buffer)
4407       (save-excursion                       ; Keep track of buffer.
4408         CHANGE-BUFFER
4409         INSERT-SUBSTRING-FROM-oldbuf-INTO-BUFFER)
4410
4411       CHANGE-BACK-TO-ORIGINAL-BUFFER-WHEN-FINISHED
4412     LET-THE-LOCAL-MEANING-OF-oldbuf-DISAPPEAR-WHEN-FINISHED
4413
4414   In summary, ‘append-to-buffer’ works as follows: it saves the value
4415of the current buffer in the variable called ‘oldbuf’.  It gets the new
4416buffer (creating one if need be) and switches Emacs’s attention to it.
4417Using the value of ‘oldbuf’, it inserts the region of text from the old
4418buffer into the new buffer; and then using ‘save-excursion’, it brings
4419you back to your original buffer.
4420
4421   In looking at ‘append-to-buffer’, you have explored a fairly complex
4422function.  It shows how to use ‘let’ and ‘save-excursion’, and how to
4423change to and come back from another buffer.  Many function definitions
4424use ‘let’, ‘save-excursion’, and ‘set-buffer’ this way.
4425
4426
4427File: eintr.info,  Node: Buffer Related Review,  Next: Buffer Exercises,  Prev: append-to-buffer,  Up: Buffer Walk Through
4428
44294.5 Review
4430==========
4431
4432Here is a brief summary of the various functions discussed in this
4433chapter.
4434
4435‘describe-function’
4436‘describe-variable’
4437     Print the documentation for a function or variable.  Conventionally
4438     bound to ‘C-h f’ and ‘C-h v’.
4439
4440‘xref-find-definitions’
4441     Find the file containing the source for a function or variable and
4442     switch buffers to it, positioning point at the beginning of the
4443     item.  Conventionally bound to ‘M-.’ (that’s a period following the
4444     <META> key).
4445
4446‘save-excursion’
4447     Save the location of point and restore its value after the
4448     arguments to ‘save-excursion’ have been evaluated.  Also, remember
4449     the current buffer and return to it.
4450
4451‘push-mark’
4452     Set mark at a location and record the value of the previous mark on
4453     the mark ring.  The mark is a location in the buffer that will keep
4454     its relative position even if text is added to or removed from the
4455     buffer.
4456
4457‘goto-char’
4458     Set point to the location specified by the value of the argument,
4459     which can be a number, a marker, or an expression that returns the
4460     number of a position, such as ‘(point-min)’.
4461
4462‘insert-buffer-substring’
4463     Copy a region of text from a buffer that is passed to the function
4464     as an argument and insert the region into the current buffer.
4465
4466‘mark-whole-buffer’
4467     Mark the whole buffer as a region.  Normally bound to ‘C-x h’.
4468
4469‘set-buffer’
4470     Switch the attention of Emacs to another buffer, but do not change
4471     the window being displayed.  Used when the program rather than a
4472     human is to work on a different buffer.
4473
4474‘get-buffer-create’
4475‘get-buffer’
4476     Find a named buffer or create one if a buffer of that name does not
4477     exist.  The ‘get-buffer’ function returns ‘nil’ if the named buffer
4478     does not exist.
4479
4480
4481File: eintr.info,  Node: Buffer Exercises,  Prev: Buffer Related Review,  Up: Buffer Walk Through
4482
44834.6 Exercises
4484=============
4485
4486   • Write your own ‘simplified-end-of-buffer’ function definition; then
4487     test it to see whether it works.
4488
4489   • Use ‘if’ and ‘get-buffer’ to write a function that prints a message
4490     telling you whether a buffer exists.
4491
4492   • Using ‘xref-find-definitions’, find the source for the
4493     ‘copy-to-buffer’ function.
4494
4495
4496File: eintr.info,  Node: More Complex,  Next: Narrowing & Widening,  Prev: Buffer Walk Through,  Up: Top
4497
44985 A Few More Complex Functions
4499******************************
4500
4501In this chapter, we build on what we have learned in previous chapters
4502by looking at more complex functions.  The ‘copy-to-buffer’ function
4503illustrates use of two ‘save-excursion’ expressions in one definition,
4504while the ‘insert-buffer’ function illustrates use of an asterisk in an
4505‘interactive’ expression, use of ‘or’, and the important distinction
4506between a name and the object to which the name refers.
4507
4508* Menu:
4509
4510* copy-to-buffer::              With ‘set-buffer’, ‘get-buffer-create’.
4511* insert-buffer::               Read-only, and with ‘or’.
4512* beginning-of-buffer::         Shows ‘goto-char’,
4513                                ‘point-min’, and ‘push-mark’.
4514* Second Buffer Related Review::
4515* optional Exercise::
4516
4517
4518File: eintr.info,  Node: copy-to-buffer,  Next: insert-buffer,  Up: More Complex
4519
45205.1 The Definition of ‘copy-to-buffer’
4521======================================
4522
4523After understanding how ‘append-to-buffer’ works, it is easy to
4524understand ‘copy-to-buffer’.  This function copies text into a buffer,
4525but instead of adding to the second buffer, it replaces all the previous
4526text in the second buffer.
4527
4528   The body of ‘copy-to-buffer’ looks like this,
4529
4530     ...
4531     (interactive "BCopy to buffer: \nr")
4532     (let ((oldbuf (current-buffer)))
4533       (with-current-buffer (get-buffer-create buffer)
4534         (barf-if-buffer-read-only)
4535         (erase-buffer)
4536         (save-excursion
4537           (insert-buffer-substring oldbuf start end)))))
4538
4539   The ‘copy-to-buffer’ function has a simpler ‘interactive’ expression
4540than ‘append-to-buffer’.
4541
4542   The definition then says
4543
4544     (with-current-buffer (get-buffer-create buffer) ...
4545
4546   First, look at the earliest inner expression; that is evaluated
4547first.  That expression starts with ‘get-buffer-create buffer’.  The
4548function tells the computer to use the buffer with the name specified as
4549the one to which you are copying, or if such a buffer does not exist, to
4550create it.  Then, the ‘with-current-buffer’ function evaluates its body
4551with that buffer temporarily current.
4552
4553   (This demonstrates another way to shift the computer’s attention but
4554not the user’s.  The ‘append-to-buffer’ function showed how to do the
4555same with ‘save-excursion’ and ‘set-buffer’.  ‘with-current-buffer’ is a
4556newer, and arguably easier, mechanism.)
4557
4558   The ‘barf-if-buffer-read-only’ function sends you an error message
4559saying the buffer is read-only if you cannot modify it.
4560
4561   The next line has the ‘erase-buffer’ function as its sole contents.
4562That function erases the buffer.
4563
4564   Finally, the last two lines contain the ‘save-excursion’ expression
4565with ‘insert-buffer-substring’ as its body.  The
4566‘insert-buffer-substring’ expression copies the text from the buffer you
4567are in (and you have not seen the computer shift its attention, so you
4568don’t know that that buffer is now called ‘oldbuf’).
4569
4570   Incidentally, this is what is meant by “replacement”.  To replace
4571text, Emacs erases the previous text and then inserts new text.
4572
4573   In outline, the body of ‘copy-to-buffer’ looks like this:
4574
4575     (let (BIND-oldbuf-TO-VALUE-OF-current-buffer)
4576         (WITH-THE-BUFFER-YOU-ARE-COPYING-TO
4577           (BUT-DO-NOT-ERASE-OR-COPY-TO-A-READ-ONLY-BUFFER)
4578           (erase-buffer)
4579           (save-excursion
4580             INSERT-SUBSTRING-FROM-oldbuf-INTO-BUFFER)))
4581
4582
4583File: eintr.info,  Node: insert-buffer,  Next: beginning-of-buffer,  Prev: copy-to-buffer,  Up: More Complex
4584
45855.2 The Definition of ‘insert-buffer’
4586=====================================
4587
4588‘insert-buffer’ is yet another buffer-related function.  This command
4589copies another buffer _into_ the current buffer.  It is the reverse of
4590‘append-to-buffer’ or ‘copy-to-buffer’, since they copy a region of text
4591_from_ the current buffer to another buffer.
4592
4593   Here is a discussion based on the original code.  The code was
4594simplified in 2003 and is harder to understand.
4595
4596   (*Note New Body for ‘insert-buffer’: New insert-buffer, to see a
4597discussion of the new body.)
4598
4599   In addition, this code illustrates the use of ‘interactive’ with a
4600buffer that might be “read-only” and the important distinction between
4601the name of an object and the object actually referred to.
4602
4603* Menu:
4604
4605* insert-buffer code::
4606* insert-buffer interactive::   When you can read, but not write.
4607* insert-buffer body::          The body has an ‘or’ and a ‘let’.
4608* if & or::                     Using an ‘if’ instead of an ‘or’.
4609* Insert or::                   How the ‘or’ expression works.
4610* Insert let::                  Two ‘save-excursion’ expressions.
4611* New insert-buffer::
4612
4613
4614File: eintr.info,  Node: insert-buffer code,  Next: insert-buffer interactive,  Up: insert-buffer
4615
4616The Code for ‘insert-buffer’
4617----------------------------
4618
4619Here is the earlier code:
4620
4621     (defun insert-buffer (buffer)
4622       "Insert after point the contents of BUFFER.
4623     Puts mark after the inserted text.
4624     BUFFER may be a buffer or a buffer name."
4625       (interactive "*bInsert buffer: ")
4626       (or (bufferp buffer)
4627           (setq buffer (get-buffer buffer)))
4628       (let (start end newmark)
4629         (save-excursion
4630           (save-excursion
4631             (set-buffer buffer)
4632             (setq start (point-min) end (point-max)))
4633           (insert-buffer-substring buffer start end)
4634           (setq newmark (point)))
4635         (push-mark newmark)))
4636
4637   As with other function definitions, you can use a template to see an
4638outline of the function:
4639
4640     (defun insert-buffer (buffer)
4641       "DOCUMENTATION..."
4642       (interactive "*bInsert buffer: ")
4643       BODY...)
4644
4645
4646File: eintr.info,  Node: insert-buffer interactive,  Next: insert-buffer body,  Prev: insert-buffer code,  Up: insert-buffer
4647
46485.2.1 The Interactive Expression in ‘insert-buffer’
4649---------------------------------------------------
4650
4651In ‘insert-buffer’, the argument to the ‘interactive’ declaration has
4652two parts, an asterisk, ‘*’, and ‘bInsert buffer: ’.
4653
4654* Menu:
4655
4656* Read-only buffer::            When a buffer cannot be modified.
4657* b for interactive::           An existing buffer or else its name.
4658
4659
4660File: eintr.info,  Node: Read-only buffer,  Next: b for interactive,  Up: insert-buffer interactive
4661
4662A Read-only Buffer
4663..................
4664
4665The asterisk is for the situation when the current buffer is a read-only
4666buffer—a buffer that cannot be modified.  If ‘insert-buffer’ is called
4667when the current buffer is read-only, a message to this effect is
4668printed in the echo area and the terminal may beep or blink at you; you
4669will not be permitted to insert anything into current buffer.  The
4670asterisk does not need to be followed by a newline to separate it from
4671the next argument.
4672
4673
4674File: eintr.info,  Node: b for interactive,  Prev: Read-only buffer,  Up: insert-buffer interactive
4675
4676‘b’ in an Interactive Expression
4677................................
4678
4679The next argument in the interactive expression starts with a lower case
4680‘b’.  (This is different from the code for ‘append-to-buffer’, which
4681uses an upper-case ‘B’.  *Note The Definition of ‘append-to-buffer’:
4682append-to-buffer.)  The lower-case ‘b’ tells the Lisp interpreter that
4683the argument for ‘insert-buffer’ should be an existing buffer or else
4684its name.  (The upper-case ‘B’ option provides for the possibility that
4685the buffer does not exist.)  Emacs will prompt you for the name of the
4686buffer, offering you a default buffer, with name completion enabled.  If
4687the buffer does not exist, you receive a message that says “No match”;
4688your terminal may beep at you as well.
4689
4690   The new and simplified code generates a list for ‘interactive’.  It
4691uses the ‘barf-if-buffer-read-only’ and ‘read-buffer’ functions with
4692which we are already familiar and the ‘progn’ special form with which we
4693are not.  (It will be described later.)
4694
4695
4696File: eintr.info,  Node: insert-buffer body,  Next: if & or,  Prev: insert-buffer interactive,  Up: insert-buffer
4697
46985.2.2 The Body of the ‘insert-buffer’ Function
4699----------------------------------------------
4700
4701The body of the ‘insert-buffer’ function has two major parts: an ‘or’
4702expression and a ‘let’ expression.  The purpose of the ‘or’ expression
4703is to ensure that the argument ‘buffer’ is bound to a buffer and not
4704just the name of a buffer.  The body of the ‘let’ expression contains
4705the code which copies the other buffer into the current buffer.
4706
4707   In outline, the two expressions fit into the ‘insert-buffer’ function
4708like this:
4709
4710     (defun insert-buffer (buffer)
4711       "DOCUMENTATION..."
4712       (interactive "*bInsert buffer: ")
4713       (or ...
4714           ...
4715       (let (VARLIST)
4716           BODY-OF-let... )
4717
4718   To understand how the ‘or’ expression ensures that the argument
4719‘buffer’ is bound to a buffer and not to the name of a buffer, it is
4720first necessary to understand the ‘or’ function.
4721
4722   Before doing this, let me rewrite this part of the function using
4723‘if’ so that you can see what is done in a manner that will be familiar.
4724
4725
4726File: eintr.info,  Node: if & or,  Next: Insert or,  Prev: insert-buffer body,  Up: insert-buffer
4727
47285.2.3 ‘insert-buffer’ With an ‘if’ Instead of an ‘or’
4729-----------------------------------------------------
4730
4731The job to be done is to make sure the value of ‘buffer’ is a buffer
4732itself and not the name of a buffer.  If the value is the name, then the
4733buffer itself must be got.
4734
4735   You can imagine yourself at a conference where an usher is wandering
4736around holding a list with your name on it and looking for you: the
4737usher is bound to your name, not to you; but when the usher finds you
4738and takes your arm, the usher becomes bound to you.
4739
4740   In Lisp, you might describe this situation like this:
4741
4742     (if (not (holding-on-to-guest))
4743         (find-and-take-arm-of-guest))
4744
4745   We want to do the same thing with a buffer—if we do not have the
4746buffer itself, we want to get it.
4747
4748   Using a predicate called ‘bufferp’ that tells us whether we have a
4749buffer (rather than its name), we can write the code like this:
4750
4751     (if (not (bufferp buffer))              ; if-part
4752         (setq buffer (get-buffer buffer)))  ; then-part
4753
4754Here, the true-or-false-test of the ‘if’ expression is
4755‘(not (bufferp buffer))’; and the then-part is the expression
4756‘(setq buffer (get-buffer buffer))’.
4757
4758   In the test, the function ‘bufferp’ returns true if its argument is a
4759buffer—but false if its argument is the name of the buffer.  (The last
4760character of the function name ‘bufferp’ is the character ‘p’; as we saw
4761earlier, such use of ‘p’ is a convention that indicates that the
4762function is a predicate, which is a term that means that the function
4763will determine whether some property is true or false.  *Note Using the
4764Wrong Type Object as an Argument: Wrong Type of Argument.)
4765
4766   The function ‘not’ precedes the expression ‘(bufferp buffer)’, so the
4767true-or-false-test looks like this:
4768
4769     (not (bufferp buffer))
4770
4771‘not’ is a function that returns true if its argument is false and false
4772if its argument is true.  So if ‘(bufferp buffer)’ returns true, the
4773‘not’ expression returns false and vice versa.
4774
4775   Using this test, the ‘if’ expression works as follows: when the value
4776of the variable ‘buffer’ is actually a buffer rather than its name, the
4777true-or-false-test returns false and the ‘if’ expression does not
4778evaluate the then-part.  This is fine, since we do not need to do
4779anything to the variable ‘buffer’ if it really is a buffer.
4780
4781   On the other hand, when the value of ‘buffer’ is not a buffer itself,
4782but the name of a buffer, the true-or-false-test returns true and the
4783then-part of the expression is evaluated.  In this case, the then-part
4784is ‘(setq buffer (get-buffer buffer))’.  This expression uses the
4785‘get-buffer’ function to return an actual buffer itself, given its name.
4786The ‘setq’ then sets the variable ‘buffer’ to the value of the buffer
4787itself, replacing its previous value (which was the name of the buffer).
4788
4789
4790File: eintr.info,  Node: Insert or,  Next: Insert let,  Prev: if & or,  Up: insert-buffer
4791
47925.2.4 The ‘or’ in the Body
4793--------------------------
4794
4795The purpose of the ‘or’ expression in the ‘insert-buffer’ function is to
4796ensure that the argument ‘buffer’ is bound to a buffer and not just to
4797the name of a buffer.  The previous section shows how the job could have
4798been done using an ‘if’ expression.  However, the ‘insert-buffer’
4799function actually uses ‘or’.  To understand this, it is necessary to
4800understand how ‘or’ works.
4801
4802   An ‘or’ function can have any number of arguments.  It evaluates each
4803argument in turn and returns the value of the first of its arguments
4804that is not ‘nil’.  Also, and this is a crucial feature of ‘or’, it does
4805not evaluate any subsequent arguments after returning the first
4806non-‘nil’ value.
4807
4808   The ‘or’ expression looks like this:
4809
4810     (or (bufferp buffer)
4811         (setq buffer (get-buffer buffer)))
4812
4813The first argument to ‘or’ is the expression ‘(bufferp buffer)’.  This
4814expression returns true (a non-‘nil’ value) if the buffer is actually a
4815buffer, and not just the name of a buffer.  In the ‘or’ expression, if
4816this is the case, the ‘or’ expression returns this true value and does
4817not evaluate the next expression—and this is fine with us, since we do
4818not want to do anything to the value of ‘buffer’ if it really is a
4819buffer.
4820
4821   On the other hand, if the value of ‘(bufferp buffer)’ is ‘nil’, which
4822it will be if the value of ‘buffer’ is the name of a buffer, the Lisp
4823interpreter evaluates the next element of the ‘or’ expression.  This is
4824the expression ‘(setq buffer (get-buffer buffer))’.  This expression
4825returns a non-‘nil’ value, which is the value to which it sets the
4826variable ‘buffer’—and this value is a buffer itself, not the name of a
4827buffer.
4828
4829   The result of all this is that the symbol ‘buffer’ is always bound to
4830a buffer itself rather than to the name of a buffer.  All this is
4831necessary because the ‘set-buffer’ function in a following line only
4832works with a buffer itself, not with the name to a buffer.
4833
4834   Incidentally, using ‘or’, the situation with the usher would be
4835written like this:
4836
4837     (or (holding-on-to-guest) (find-and-take-arm-of-guest))
4838
4839
4840File: eintr.info,  Node: Insert let,  Next: New insert-buffer,  Prev: Insert or,  Up: insert-buffer
4841
48425.2.5 The ‘let’ Expression in ‘insert-buffer’
4843---------------------------------------------
4844
4845After ensuring that the variable ‘buffer’ refers to a buffer itself and
4846not just to the name of a buffer, the ‘insert-buffer function’ continues
4847with a ‘let’ expression.  This specifies three local variables, ‘start’,
4848‘end’, and ‘newmark’ and binds them to the initial value ‘nil’.  These
4849variables are used inside the remainder of the ‘let’ and temporarily
4850hide any other occurrence of variables of the same name in Emacs until
4851the end of the ‘let’.
4852
4853   The body of the ‘let’ contains two ‘save-excursion’ expressions.
4854First, we will look at the inner ‘save-excursion’ expression in detail.
4855The expression looks like this:
4856
4857     (save-excursion
4858       (set-buffer buffer)
4859       (setq start (point-min) end (point-max)))
4860
4861The expression ‘(set-buffer buffer)’ changes Emacs’s attention from the
4862current buffer to the one from which the text will copied.  In that
4863buffer, the variables ‘start’ and ‘end’ are set to the beginning and end
4864of the buffer, using the commands ‘point-min’ and ‘point-max’.  Note
4865that we have here an illustration of how ‘setq’ is able to set two
4866variables in the same expression.  The first argument of ‘setq’ is set
4867to the value of its second, and its third argument is set to the value
4868of its fourth.
4869
4870   After the body of the inner ‘save-excursion’ is evaluated, the
4871‘save-excursion’ restores the original buffer, but ‘start’ and ‘end’
4872remain set to the values of the beginning and end of the buffer from
4873which the text will be copied.
4874
4875   The outer ‘save-excursion’ expression looks like this:
4876
4877     (save-excursion
4878       (INNER-save-excursion-EXPRESSION
4879          (GO-TO-NEW-BUFFER-AND-SET-start-AND-end)
4880       (insert-buffer-substring buffer start end)
4881       (setq newmark (point)))
4882
4883The ‘insert-buffer-substring’ function copies the text _into_ the
4884current buffer _from_ the region indicated by ‘start’ and ‘end’ in
4885‘buffer’.  Since the whole of the second buffer lies between ‘start’ and
4886‘end’, the whole of the second buffer is copied into the buffer you are
4887editing.  Next, the value of point, which will be at the end of the
4888inserted text, is recorded in the variable ‘newmark’.
4889
4890   After the body of the outer ‘save-excursion’ is evaluated, point is
4891relocated to its original place.
4892
4893   However, it is convenient to locate a mark at the end of the newly
4894inserted text and locate point at its beginning.  The ‘newmark’ variable
4895records the end of the inserted text.  In the last line of the ‘let’
4896expression, the ‘(push-mark newmark)’ expression function sets a mark to
4897this location.  (The previous location of the mark is still accessible;
4898it is recorded on the mark ring and you can go back to it with ‘C-u
4899C-<SPC>’.)  Meanwhile, point is located at the beginning of the inserted
4900text, which is where it was before you called the insert function, the
4901position of which was saved by the first ‘save-excursion’.
4902
4903   The whole ‘let’ expression looks like this:
4904
4905     (let (start end newmark)
4906       (save-excursion
4907         (save-excursion
4908           (set-buffer buffer)
4909           (setq start (point-min) end (point-max)))
4910         (insert-buffer-substring buffer start end)
4911         (setq newmark (point)))
4912       (push-mark newmark))
4913
4914   Like the ‘append-to-buffer’ function, the ‘insert-buffer’ function
4915uses ‘let’, ‘save-excursion’, and ‘set-buffer’.  In addition, the
4916function illustrates one way to use ‘or’.  All these functions are
4917building blocks that we will find and use again and again.
4918
4919
4920File: eintr.info,  Node: New insert-buffer,  Prev: Insert let,  Up: insert-buffer
4921
49225.2.6 New Body for ‘insert-buffer’
4923----------------------------------
4924
4925The body in the GNU Emacs 22 version is more confusing than the
4926original.
4927
4928   It consists of two expressions,
4929
4930       (push-mark
4931        (save-excursion
4932          (insert-buffer-substring (get-buffer buffer))
4933          (point)))
4934
4935        nil
4936
4937except, and this is what confuses novices, very important work is done
4938inside the ‘push-mark’ expression.
4939
4940   The ‘get-buffer’ function returns a buffer with the name provided.
4941You will note that the function is _not_ called ‘get-buffer-create’; it
4942does not create a buffer if one does not already exist.  The buffer
4943returned by ‘get-buffer’, an existing buffer, is passed to
4944‘insert-buffer-substring’, which inserts the whole of the buffer (since
4945you did not specify anything else).
4946
4947   The location into which the buffer is inserted is recorded by
4948‘push-mark’.  Then the function returns ‘nil’, the value of its last
4949command.  Put another way, the ‘insert-buffer’ function exists only to
4950produce a side effect, inserting another buffer, not to return any
4951value.
4952
4953
4954File: eintr.info,  Node: beginning-of-buffer,  Next: Second Buffer Related Review,  Prev: insert-buffer,  Up: More Complex
4955
49565.3 Complete Definition of ‘beginning-of-buffer’
4957================================================
4958
4959The basic structure of the ‘beginning-of-buffer’ function has already
4960been discussed.  (*Note A Simplified ‘beginning-of-buffer’ Definition:
4961simplified-beginning-of-buffer.)  This section describes the complex
4962part of the definition.
4963
4964   As previously described, when invoked without an argument,
4965‘beginning-of-buffer’ moves the cursor to the beginning of the buffer
4966(in truth, the beginning of the accessible portion of the buffer),
4967leaving the mark at the previous position.  However, when the command is
4968invoked with a number between one and ten, the function considers that
4969number to be a fraction of the length of the buffer, measured in tenths,
4970and Emacs moves the cursor that fraction of the way from the beginning
4971of the buffer.  Thus, you can either call this function with the key
4972command ‘M-<’, which will move the cursor to the beginning of the
4973buffer, or with a key command such as ‘C-u 7 M-<’ which will move the
4974cursor to a point 70% of the way through the buffer.  If a number bigger
4975than ten is used for the argument, it moves to the end of the buffer.
4976
4977   The ‘beginning-of-buffer’ function can be called with or without an
4978argument.  The use of the argument is optional.
4979
4980* Menu:
4981
4982* Optional Arguments::
4983* beginning-of-buffer opt arg::  Example with optional argument.
4984* beginning-of-buffer complete::
4985
4986
4987File: eintr.info,  Node: Optional Arguments,  Next: beginning-of-buffer opt arg,  Up: beginning-of-buffer
4988
49895.3.1 Optional Arguments
4990------------------------
4991
4992Unless told otherwise, Lisp expects that a function with an argument in
4993its function definition will be called with a value for that argument.
4994If that does not happen, you get an error and a message that says ‘Wrong
4995number of arguments’.
4996
4997   However, optional arguments are a feature of Lisp: a particular
4998“keyword” is used to tell the Lisp interpreter that an argument is
4999optional.  The keyword is ‘&optional’.  (The ‘&’ in front of ‘optional’
5000is part of the keyword.)  In a function definition, if an argument
5001follows the keyword ‘&optional’, no value need be passed to that
5002argument when the function is called.
5003
5004   The first line of the function definition of ‘beginning-of-buffer’
5005therefore looks like this:
5006
5007     (defun beginning-of-buffer (&optional arg)
5008
5009   In outline, the whole function looks like this:
5010
5011     (defun beginning-of-buffer (&optional arg)
5012       "DOCUMENTATION..."
5013       (interactive "P")
5014       (or (IS-THE-ARGUMENT-A-CONS-CELL arg)
5015           (and ARE-BOTH-TRANSIENT-MARK-MODE-AND-MARK-ACTIVE-TRUE)
5016           (push-mark))
5017       (let (DETERMINE-SIZE-AND-SET-IT)
5018       (goto-char
5019         (IF-THERE-IS-AN-ARGUMENT
5020             FIGURE-OUT-WHERE-TO-GO
5021           ELSE-GO-TO
5022           (point-min))))
5023        DO-NICETY
5024
5025   The function is similar to the ‘simplified-beginning-of-buffer’
5026function except that the ‘interactive’ expression has ‘"P"’ as an
5027argument and the ‘goto-char’ function is followed by an if-then-else
5028expression that figures out where to put the cursor if there is an
5029argument that is not a cons cell.
5030
5031   (Since I do not explain a cons cell for many more chapters, please
5032consider ignoring the function ‘consp’.  *Note How Lists are
5033Implemented: List Implementation, and *note Cons Cell and List Types:
5034(elisp)Cons Cell Type.)
5035
5036   The ‘"P"’ in the ‘interactive’ expression tells Emacs to pass a
5037prefix argument, if there is one, to the function in raw form.  A prefix
5038argument is made by typing the <META> key followed by a number, or by
5039typing ‘C-u’ and then a number.  (If you don’t type a number, ‘C-u’
5040defaults to a cons cell with a 4.  A lowercase ‘"p"’ in the
5041‘interactive’ expression causes the function to convert a prefix arg to
5042a number.)
5043
5044   The true-or-false-test of the ‘if’ expression looks complex, but it
5045is not: it checks whether ‘arg’ has a value that is not ‘nil’ and
5046whether it is a cons cell.  (That is what ‘consp’ does; it checks
5047whether its argument is a cons cell.)  If ‘arg’ has a value that is not
5048‘nil’ (and is not a cons cell), which will be the case if
5049‘beginning-of-buffer’ is called with a numeric argument, then this
5050true-or-false-test will return true and the then-part of the ‘if’
5051expression will be evaluated.  On the other hand, if
5052‘beginning-of-buffer’ is not called with an argument, the value of ‘arg’
5053will be ‘nil’ and the else-part of the ‘if’ expression will be
5054evaluated.  The else-part is simply ‘point-min’, and when this is the
5055outcome, the whole ‘goto-char’ expression is ‘(goto-char (point-min))’,
5056which is how we saw the ‘beginning-of-buffer’ function in its simplified
5057form.
5058
5059
5060File: eintr.info,  Node: beginning-of-buffer opt arg,  Next: beginning-of-buffer complete,  Prev: Optional Arguments,  Up: beginning-of-buffer
5061
50625.3.2 ‘beginning-of-buffer’ with an Argument
5063--------------------------------------------
5064
5065When ‘beginning-of-buffer’ is called with an argument, an expression is
5066evaluated which calculates what value to pass to ‘goto-char’.  This
5067expression is rather complicated at first sight.  It includes an inner
5068‘if’ expression and much arithmetic.  It looks like this:
5069
5070     (if (> (buffer-size) 10000)
5071         ;; Avoid overflow for large buffer sizes!
5072                               (* (prefix-numeric-value arg)
5073                                  (/ size 10))
5074       (/
5075        (+ 10
5076           (*
5077            size (prefix-numeric-value arg))) 10)))
5078
5079* Menu:
5080
5081* Disentangle beginning-of-buffer::
5082* Large buffer case::
5083* Small buffer case::
5084
5085
5086File: eintr.info,  Node: Disentangle beginning-of-buffer,  Next: Large buffer case,  Up: beginning-of-buffer opt arg
5087
5088Disentangle ‘beginning-of-buffer’
5089.................................
5090
5091Like other complex-looking expressions, the conditional expression
5092within ‘beginning-of-buffer’ can be disentangled by looking at it as
5093parts of a template, in this case, the template for an if-then-else
5094expression.  In skeletal form, the expression looks like this:
5095
5096     (if (BUFFER-IS-LARGE
5097         DIVIDE-BUFFER-SIZE-BY-10-AND-MULTIPLY-BY-ARG
5098       ELSE-USE-ALTERNATE-CALCULATION
5099
5100   The true-or-false-test of this inner ‘if’ expression checks the size
5101of the buffer.  The reason for this is that the old version 18 Emacs
5102used numbers that are no bigger than eight million or so and in the
5103computation that followed, the programmer feared that Emacs might try to
5104use over-large numbers if the buffer were large.  The term “overflow”,
5105mentioned in the comment, means numbers that are over large.  More
5106recent versions of Emacs use larger numbers, but this code has not been
5107touched, if only because people now look at buffers that are far, far
5108larger than ever before.
5109
5110   There are two cases: if the buffer is large and if it is not.
5111
5112
5113File: eintr.info,  Node: Large buffer case,  Next: Small buffer case,  Prev: Disentangle beginning-of-buffer,  Up: beginning-of-buffer opt arg
5114
5115What happens in a large buffer
5116..............................
5117
5118In ‘beginning-of-buffer’, the inner ‘if’ expression tests whether the
5119size of the buffer is greater than 10,000 characters.  To do this, it
5120uses the ‘>’ function and the computation of ‘size’ that comes from the
5121let expression.
5122
5123   In the old days, the function ‘buffer-size’ was used.  Not only was
5124that function called several times, it gave the size of the whole
5125buffer, not the accessible part.  The computation makes much more sense
5126when it handles just the accessible part.  (*Note Narrowing and
5127Widening: Narrowing & Widening, for more information on focusing
5128attention to an accessible part.)
5129
5130   The line looks like this:
5131
5132     (if (> size 10000)
5133
5134When the buffer is large, the then-part of the ‘if’ expression is
5135evaluated.  It reads like this (after formatting for easy reading):
5136
5137     (*
5138       (prefix-numeric-value arg)
5139       (/ size 10))
5140
5141This expression is a multiplication, with two arguments to the function
5142‘*’.
5143
5144   The first argument is ‘(prefix-numeric-value arg)’.  When ‘"P"’ is
5145used as the argument for ‘interactive’, the value passed to the function
5146as its argument is passed a “raw prefix argument”, and not a number.
5147(It is a number in a list.)  To perform the arithmetic, a conversion is
5148necessary, and ‘prefix-numeric-value’ does the job.
5149
5150   The second argument is ‘(/ size 10)’.  This expression divides the
5151numeric value by ten—the numeric value of the size of the accessible
5152portion of the buffer.  This produces a number that tells how many
5153characters make up one tenth of the buffer size.  (In Lisp, ‘/’ is used
5154for division, just as ‘*’ is used for multiplication.)
5155
5156   In the multiplication expression as a whole, this amount is
5157multiplied by the value of the prefix argument—the multiplication looks
5158like this:
5159
5160     (* NUMERIC-VALUE-OF-PREFIX-ARG
5161        NUMBER-OF-CHARACTERS-IN-ONE-TENTH-OF-THE-ACCESSIBLE-BUFFER)
5162
5163If, for example, the prefix argument is ‘7’, the one-tenth value will be
5164multiplied by 7 to give a position 70% of the way through.
5165
5166   The result of all this is that if the accessible portion of the
5167buffer is large, the ‘goto-char’ expression reads like this:
5168
5169     (goto-char (* (prefix-numeric-value arg)
5170                   (/ size 10)))
5171
5172   This puts the cursor where we want it.
5173
5174
5175File: eintr.info,  Node: Small buffer case,  Prev: Large buffer case,  Up: beginning-of-buffer opt arg
5176
5177What happens in a small buffer
5178..............................
5179
5180If the buffer contains fewer than 10,000 characters, a slightly
5181different computation is performed.  You might think this is not
5182necessary, since the first computation could do the job.  However, in a
5183small buffer, the first method may not put the cursor on exactly the
5184desired line; the second method does a better job.
5185
5186   The code looks like this:
5187
5188     (/ (+ 10 (* size (prefix-numeric-value arg))) 10))
5189
5190This is code in which you figure out what happens by discovering how the
5191functions are embedded in parentheses.  It is easier to read if you
5192reformat it with each expression indented more deeply than its enclosing
5193expression:
5194
5195       (/
5196        (+ 10
5197           (*
5198            size
5199            (prefix-numeric-value arg)))
5200        10))
5201
5202Looking at parentheses, we see that the innermost operation is
5203‘(prefix-numeric-value arg)’, which converts the raw argument to a
5204number.  In the following expression, this number is multiplied by the
5205size of the accessible portion of the buffer:
5206
5207     (* size (prefix-numeric-value arg))
5208
5209This multiplication creates a number that may be larger than the size of
5210the buffer—seven times larger if the argument is 7, for example.  Ten is
5211then added to this number and finally the large number is divided by ten
5212to provide a value that is one character larger than the percentage
5213position in the buffer.
5214
5215   The number that results from all this is passed to ‘goto-char’ and
5216the cursor is moved to that point.
5217
5218
5219File: eintr.info,  Node: beginning-of-buffer complete,  Prev: beginning-of-buffer opt arg,  Up: beginning-of-buffer
5220
52215.3.3 The Complete ‘beginning-of-buffer’
5222----------------------------------------
5223
5224Here is the complete text of the ‘beginning-of-buffer’ function:
5225
5226     (defun beginning-of-buffer (&optional arg)
5227       "Move point to the beginning of the buffer;
5228     leave mark at previous position.
5229     With \\[universal-argument] prefix,
5230     do not set mark at previous position.
5231     With numeric arg N,
5232     put point N/10 of the way from the beginning.
5233
5234     If the buffer is narrowed,
5235     this command uses the beginning and size
5236     of the accessible part of the buffer.
5237
5238     Don't use this command in Lisp programs!
5239     \(goto-char (point-min)) is faster
5240     and avoids clobbering the mark."
5241       (interactive "P")
5242       (or (consp arg)
5243           (and transient-mark-mode mark-active)
5244           (push-mark))
5245       (let ((size (- (point-max) (point-min))))
5246         (goto-char (if (and arg (not (consp arg)))
5247                        (+ (point-min)
5248                           (if (> size 10000)
5249                               ;; Avoid overflow for large buffer sizes!
5250                               (* (prefix-numeric-value arg)
5251                                  (/ size 10))
5252                             (/ (+ 10 (* size (prefix-numeric-value arg)))
5253                                10)))
5254                      (point-min))))
5255       (if (and arg (not (consp arg))) (forward-line 1)))
5256
5257Except for two small points, the previous discussion shows how this
5258function works.  The first point deals with a detail in the
5259documentation string, and the second point concerns the last line of the
5260function.
5261
5262   In the documentation string, there is reference to an expression:
5263
5264     \\[universal-argument]
5265
5266A ‘\\’ is used before the first square bracket of this expression.  This
5267‘\\’ tells the Lisp interpreter to substitute whatever key is currently
5268bound to the ‘[...]’.  In the case of ‘universal-argument’, that is
5269usually ‘C-u’, but it might be different.  (*Note Tips for Documentation
5270Strings: (elisp)Documentation Tips, for more information.)
5271
5272   Finally, the last line of the ‘beginning-of-buffer’ command says to
5273move point to the beginning of the next line if the command is invoked
5274with an argument:
5275
5276     (if (and arg (not (consp arg))) (forward-line 1))
5277
5278This puts the cursor at the beginning of the first line after the
5279appropriate tenths position in the buffer.  This is a flourish that
5280means that the cursor is always located _at least_ the requested tenths
5281of the way through the buffer, which is a nicety that is, perhaps, not
5282necessary, but which, if it did not occur, would be sure to draw
5283complaints.  (The ‘(not (consp arg))’ portion is so that if you specify
5284the command with a ‘C-u’, but without a number, that is to say, if the
5285raw prefix argument is simply a cons cell, the command does not put you
5286at the beginning of the second line.)
5287
5288
5289File: eintr.info,  Node: Second Buffer Related Review,  Next: optional Exercise,  Prev: beginning-of-buffer,  Up: More Complex
5290
52915.4 Review
5292==========
5293
5294Here is a brief summary of some of the topics covered in this chapter.
5295
5296‘or’
5297     Evaluate each argument in sequence, and return the value of the
5298     first argument that is not ‘nil’; if none return a value that is
5299     not ‘nil’, return ‘nil’.  In brief, return the first true value of
5300     the arguments; return a true value if one _or_ any of the others
5301     are true.
5302
5303‘and’
5304     Evaluate each argument in sequence, and if any are ‘nil’, return
5305     ‘nil’; if none are ‘nil’, return the value of the last argument.
5306     In brief, return a true value only if all the arguments are true;
5307     return a true value if one _and_ each of the others is true.
5308
5309‘&optional’
5310     A keyword used to indicate that an argument to a function
5311     definition is optional; this means that the function can be
5312     evaluated without the argument, if desired.
5313
5314‘prefix-numeric-value’
5315     Convert the raw prefix argument produced by ‘(interactive "P")’ to
5316     a numeric value.
5317
5318‘forward-line’
5319     Move point forward to the beginning of the next line, or if the
5320     argument is greater than one, forward that many lines.  If it can’t
5321     move as far forward as it is supposed to, ‘forward-line’ goes
5322     forward as far as it can and then returns a count of the number of
5323     additional lines it was supposed to move but couldn’t.
5324
5325‘erase-buffer’
5326     Delete the entire contents of the current buffer.
5327
5328‘bufferp’
5329     Return ‘t’ if its argument is a buffer; otherwise return ‘nil’.
5330
5331
5332File: eintr.info,  Node: optional Exercise,  Prev: Second Buffer Related Review,  Up: More Complex
5333
53345.5 ‘optional’ Argument Exercise
5335================================
5336
5337Write an interactive function with an optional argument that tests
5338whether its argument, a number, is greater than or equal to, or else,
5339less than the value of ‘fill-column’, and tells you which, in a message.
5340However, if you do not pass an argument to the function, use 56 as a
5341default value.
5342
5343
5344File: eintr.info,  Node: Narrowing & Widening,  Next: car cdr & cons,  Prev: More Complex,  Up: Top
5345
53466 Narrowing and Widening
5347************************
5348
5349Narrowing is a feature of Emacs that makes it possible for you to focus
5350on a specific part of a buffer, and work without accidentally changing
5351other parts.  Narrowing is normally disabled since it can confuse
5352novices.
5353
5354* Menu:
5355
5356* Narrowing advantages::        The advantages of narrowing
5357* save-restriction::            The ‘save-restriction’ special form.
5358* what-line::                   The number of the line that point is on.
5359* narrow Exercise::
5360
5361
5362File: eintr.info,  Node: Narrowing advantages,  Next: save-restriction,  Up: Narrowing & Widening
5363
5364The Advantages of Narrowing
5365===========================
5366
5367With narrowing, the rest of a buffer is made invisible, as if it weren’t
5368there.  This is an advantage if, for example, you want to replace a word
5369in one part of a buffer but not in another: you narrow to the part you
5370want and the replacement is carried out only in that section, not in the
5371rest of the buffer.  Searches will only work within a narrowed region,
5372not outside of one, so if you are fixing a part of a document, you can
5373keep yourself from accidentally finding parts you do not need to fix by
5374narrowing just to the region you want.  (The key binding for
5375‘narrow-to-region’ is ‘C-x n n’.)
5376
5377   However, narrowing does make the rest of the buffer invisible, which
5378can scare people who inadvertently invoke narrowing and think they have
5379deleted a part of their file.  Moreover, the ‘undo’ command (which is
5380usually bound to ‘C-x u’) does not turn off narrowing (nor should it),
5381so people can become quite desperate if they do not know that they can
5382return the rest of a buffer to visibility with the ‘widen’ command.
5383(The key binding for ‘widen’ is ‘C-x n w’.)
5384
5385   Narrowing is just as useful to the Lisp interpreter as to a human.
5386Often, an Emacs Lisp function is designed to work on just part of a
5387buffer; or conversely, an Emacs Lisp function needs to work on all of a
5388buffer that has been narrowed.  The ‘what-line’ function, for example,
5389removes the narrowing from a buffer, if it has any narrowing and when it
5390has finished its job, restores the narrowing to what it was.  On the
5391other hand, the ‘count-lines’ function uses narrowing to restrict itself
5392to just that portion of the buffer in which it is interested and then
5393restores the previous situation.
5394
5395
5396File: eintr.info,  Node: save-restriction,  Next: what-line,  Prev: Narrowing advantages,  Up: Narrowing & Widening
5397
53986.1 The ‘save-restriction’ Special Form
5399=======================================
5400
5401In Emacs Lisp, you can use the ‘save-restriction’ special form to keep
5402track of whatever narrowing is in effect, if any.  When the Lisp
5403interpreter meets with ‘save-restriction’, it executes the code in the
5404body of the ‘save-restriction’ expression, and then undoes any changes
5405to narrowing that the code caused.  If, for example, the buffer is
5406narrowed and the code that follows ‘save-restriction’ gets rid of the
5407narrowing, ‘save-restriction’ returns the buffer to its narrowed region
5408afterwards.  In the ‘what-line’ command, any narrowing the buffer may
5409have is undone by the ‘widen’ command that immediately follows the
5410‘save-restriction’ command.  Any original narrowing is restored just
5411before the completion of the function.
5412
5413   The template for a ‘save-restriction’ expression is simple:
5414
5415     (save-restriction
5416       BODY... )
5417
5418The body of the ‘save-restriction’ is one or more expressions that will
5419be evaluated in sequence by the Lisp interpreter.
5420
5421   Finally, a point to note: when you use both ‘save-excursion’ and
5422‘save-restriction’, one right after the other, you should use
5423‘save-excursion’ outermost.  If you write them in reverse order, you may
5424fail to record narrowing in the buffer to which Emacs switches after
5425calling ‘save-excursion’.  Thus, when written together, ‘save-excursion’
5426and ‘save-restriction’ should be written like this:
5427
5428     (save-excursion
5429       (save-restriction
5430         BODY...))
5431
5432   In other circumstances, when not written together, the
5433‘save-excursion’ and ‘save-restriction’ special forms must be written in
5434the order appropriate to the function.
5435
5436   For example,
5437
5438       (save-restriction
5439         (widen)
5440         (save-excursion
5441         BODY...))
5442
5443
5444File: eintr.info,  Node: what-line,  Next: narrow Exercise,  Prev: save-restriction,  Up: Narrowing & Widening
5445
54466.2 ‘what-line’
5447===============
5448
5449The ‘what-line’ command tells you the number of the line in which the
5450cursor is located.  The function illustrates the use of the
5451‘save-restriction’ and ‘save-excursion’ commands.  Here is the original
5452text of the function:
5453
5454     (defun what-line ()
5455       "Print the current line number (in the buffer) of point."
5456       (interactive)
5457       (save-restriction
5458         (widen)
5459         (save-excursion
5460           (beginning-of-line)
5461           (message "Line %d"
5462                    (1+ (count-lines 1 (point)))))))
5463
5464   (In recent versions of GNU Emacs, the ‘what-line’ function has been
5465expanded to tell you your line number in a narrowed buffer as well as
5466your line number in a widened buffer.  The recent version is more
5467complex than the version shown here.  If you feel adventurous, you might
5468want to look at it after figuring out how this version works.  You will
5469probably need to use ‘C-h f’ (‘describe-function’).  The newer version
5470uses a conditional to determine whether the buffer has been narrowed.
5471
5472   (Also, it uses ‘line-number-at-pos’, which among other simple
5473expressions, such as ‘(goto-char (point-min))’, moves point to the
5474beginning of the current line with ‘(forward-line 0)’ rather than
5475‘beginning-of-line’.)
5476
5477   The ‘what-line’ function as shown here has a documentation line and
5478is interactive, as you would expect.  The next two lines use the
5479functions ‘save-restriction’ and ‘widen’.
5480
5481   The ‘save-restriction’ special form notes whatever narrowing is in
5482effect, if any, in the current buffer and restores that narrowing after
5483the code in the body of the ‘save-restriction’ has been evaluated.
5484
5485   The ‘save-restriction’ special form is followed by ‘widen’.  This
5486function undoes any narrowing the current buffer may have had when
5487‘what-line’ was called.  (The narrowing that was there is the narrowing
5488that ‘save-restriction’ remembers.)  This widening makes it possible for
5489the line counting commands to count from the beginning of the buffer.
5490Otherwise, they would have been limited to counting within the
5491accessible region.  Any original narrowing is restored just before the
5492completion of the function by the ‘save-restriction’ special form.
5493
5494   The call to ‘widen’ is followed by ‘save-excursion’, which saves the
5495location of the cursor (i.e., of point), and restores it after the code
5496in the body of the ‘save-excursion’ uses the ‘beginning-of-line’
5497function to move point.
5498
5499   (Note that the ‘(widen)’ expression comes between the
5500‘save-restriction’ and ‘save-excursion’ special forms.  When you write
5501the two ‘save- ...’ expressions in sequence, write ‘save-excursion’
5502outermost.)
5503
5504   The last two lines of the ‘what-line’ function are functions to count
5505the number of lines in the buffer and then print the number in the echo
5506area.
5507
5508     (message "Line %d"
5509              (1+ (count-lines 1 (point)))))))
5510
5511   The ‘message’ function prints a one-line message at the bottom of the
5512Emacs screen.  The first argument is inside of quotation marks and is
5513printed as a string of characters.  However, it may contain a ‘%d’
5514expression to print a following argument.  ‘%d’ prints the argument as a
5515decimal, so the message will say something such as ‘Line 243’.
5516
5517   The number that is printed in place of the ‘%d’ is computed by the
5518last line of the function:
5519
5520     (1+ (count-lines 1 (point)))
5521
5522What this does is count the lines from the first position of the buffer,
5523indicated by the ‘1’, up to ‘(point)’, and then add one to that number.
5524(The ‘1+’ function adds one to its argument.)  We add one to it because
5525line 2 has only one line before it, and ‘count-lines’ counts only the
5526lines _before_ the current line.
5527
5528   After ‘count-lines’ has done its job, and the message has been
5529printed in the echo area, the ‘save-excursion’ restores point to its
5530original position; and ‘save-restriction’ restores the original
5531narrowing, if any.
5532
5533
5534File: eintr.info,  Node: narrow Exercise,  Prev: what-line,  Up: Narrowing & Widening
5535
55366.3 Exercise with Narrowing
5537===========================
5538
5539Write a function that will display the first 60 characters of the
5540current buffer, even if you have narrowed the buffer to its latter half
5541so that the first line is inaccessible.  Restore point, mark, and
5542narrowing.  For this exercise, you need to use a whole potpourri of
5543functions, including ‘save-restriction’, ‘widen’, ‘goto-char’,
5544‘point-min’, ‘message’, and ‘buffer-substring’.
5545
5546   (‘buffer-substring’ is a previously unmentioned function you will
5547have to investigate yourself; or perhaps you will have to use
5548‘buffer-substring-no-properties’ or ‘filter-buffer-substring’ ..., yet
5549other functions.  Text properties are a feature otherwise not discussed
5550here.  *Note Text Properties: (elisp)Text Properties.)
5551
5552   Additionally, do you really need ‘goto-char’ or ‘point-min’?  Or can
5553you write the function without them?
5554
5555
5556File: eintr.info,  Node: car cdr & cons,  Next: Cutting & Storing Text,  Prev: Narrowing & Widening,  Up: Top
5557
55587 ‘car’, ‘cdr’, ‘cons’: Fundamental Functions
5559*********************************************
5560
5561In Lisp, ‘car’, ‘cdr’, and ‘cons’ are fundamental functions.  The ‘cons’
5562function is used to construct lists, and the ‘car’ and ‘cdr’ functions
5563are used to take them apart.
5564
5565   In the walk through of the ‘copy-region-as-kill’ function, we will
5566see ‘cons’ as well as two variants on ‘cdr’, namely, ‘setcdr’ and
5567‘nthcdr’.  (*Note copy-region-as-kill::.)
5568
5569* Menu:
5570
5571* Strange Names::               A historical aside: why the strange names?
5572* car & cdr::                   Functions for extracting part of a list.
5573* cons::                        Constructing a list.
5574* nthcdr::                      Calling ‘cdr’ repeatedly.
5575* nth::
5576* setcar::                      Changing the first element of a list.
5577* setcdr::                      Changing the rest of a list.
5578* cons Exercise::
5579
5580
5581File: eintr.info,  Node: Strange Names,  Next: car & cdr,  Up: car cdr & cons
5582
5583Strange Names
5584=============
5585
5586The name of the ‘cons’ function is not unreasonable: it is an
5587abbreviation of the word “construct”.  The origins of the names for
5588‘car’ and ‘cdr’, on the other hand, are esoteric: ‘car’ is an acronym
5589from the phrase “Contents of the Address part of the Register”; and
5590‘cdr’ (pronounced “could-er”) is an acronym from the phrase “Contents of
5591the Decrement part of the Register”.  These phrases refer to specific
5592pieces of hardware on the very early computer on which the original Lisp
5593was developed.  Besides being obsolete, the phrases have been completely
5594irrelevant for more than 25 years to anyone thinking about Lisp.
5595Nonetheless, although a few brave scholars have begun to use more
5596reasonable names for these functions, the old terms are still in use.
5597In particular, since the terms are used in the Emacs Lisp source code,
5598we will use them in this introduction.
5599
5600
5601File: eintr.info,  Node: car & cdr,  Next: cons,  Prev: Strange Names,  Up: car cdr & cons
5602
56037.1 ‘car’ and ‘cdr’
5604===================
5605
5606The CAR of a list is, quite simply, the first item in the list.  Thus
5607the CAR of the list ‘(rose violet daisy buttercup)’ is ‘rose’.
5608
5609   If you are reading this in Info in GNU Emacs, you can see this by
5610evaluating the following:
5611
5612     (car '(rose violet daisy buttercup))
5613
5614After evaluating the expression, ‘rose’ will appear in the echo area.
5615
5616   Clearly, a more reasonable name for the ‘car’ function would be
5617‘first’ and this is often suggested.
5618
5619   ‘car’ does not remove the first item from the list; it only reports
5620what it is.  After ‘car’ has been applied to a list, the list is still
5621the same as it was.  In the jargon, ‘car’ is “non-destructive”.  This
5622feature turns out to be important.
5623
5624   The CDR of a list is the rest of the list, that is, the ‘cdr’
5625function returns the part of the list that follows the first item.
5626Thus, while the CAR of the list ‘'(rose violet daisy buttercup)’ is
5627‘rose’, the rest of the list, the value returned by the ‘cdr’ function,
5628is ‘(violet daisy buttercup)’.
5629
5630   You can see this by evaluating the following in the usual way:
5631
5632     (cdr '(rose violet daisy buttercup))
5633
5634When you evaluate this, ‘(violet daisy buttercup)’ will appear in the
5635echo area.
5636
5637   Like ‘car’, ‘cdr’ does not remove any elements from the list—it just
5638returns a report of what the second and subsequent elements are.
5639
5640   Incidentally, in the example, the list of flowers is quoted.  If it
5641were not, the Lisp interpreter would try to evaluate the list by calling
5642‘rose’ as a function.  In this example, we do not want to do that.
5643
5644   Clearly, a more reasonable name for ‘cdr’ would be ‘rest’.
5645
5646   (There is a lesson here: when you name new functions, consider very
5647carefully what you are doing, since you may be stuck with the names for
5648far longer than you expect.  The reason this document perpetuates these
5649names is that the Emacs Lisp source code uses them, and if I did not use
5650them, you would have a hard time reading the code; but do, please, try
5651to avoid using these terms yourself.  The people who come after you will
5652be grateful to you.)
5653
5654   When ‘car’ and ‘cdr’ are applied to a list made up of symbols, such
5655as the list ‘(pine fir oak maple)’, the element of the list returned by
5656the function ‘car’ is the symbol ‘pine’ without any parentheses around
5657it.  ‘pine’ is the first element in the list.  However, the CDR of the
5658list is a list itself, ‘(fir oak maple)’, as you can see by evaluating
5659the following expressions in the usual way:
5660
5661     (car '(pine fir oak maple))
5662
5663     (cdr '(pine fir oak maple))
5664
5665   On the other hand, in a list of lists, the first element is itself a
5666list.  ‘car’ returns this first element as a list.  For example, the
5667following list contains three sub-lists, a list of carnivores, a list of
5668herbivores and a list of sea mammals:
5669
5670     (car '((lion tiger cheetah)
5671            (gazelle antelope zebra)
5672            (whale dolphin seal)))
5673
5674In this example, the first element or CAR of the list is the list of
5675carnivores, ‘(lion tiger cheetah)’, and the rest of the list is
5676‘((gazelle antelope zebra) (whale dolphin seal))’.
5677
5678     (cdr '((lion tiger cheetah)
5679            (gazelle antelope zebra)
5680            (whale dolphin seal)))
5681
5682   It is worth saying again that ‘car’ and ‘cdr’ are
5683non-destructive—that is, they do not modify or change lists to which
5684they are applied.  This is very important for how they are used.
5685
5686   Also, in the first chapter, in the discussion about atoms, I said
5687that in Lisp, certain kinds of atom, such as an array, can be separated
5688into parts; but the mechanism for doing this is different from the
5689mechanism for splitting a list.  As far as Lisp is concerned, the atoms
5690of a list are unsplittable.  (*Note Lisp Atoms::.)  The ‘car’ and ‘cdr’
5691functions are used for splitting lists and are considered fundamental to
5692Lisp.  Since they cannot split or gain access to the parts of an array,
5693an array is considered an atom.  Conversely, the other fundamental
5694function, ‘cons’, can put together or construct a list, but not an
5695array.  (Arrays are handled by array-specific functions.  *Note Arrays:
5696(elisp)Arrays.)
5697
5698
5699File: eintr.info,  Node: cons,  Next: nthcdr,  Prev: car & cdr,  Up: car cdr & cons
5700
57017.2 ‘cons’
5702==========
5703
5704The ‘cons’ function constructs lists; it is the inverse of ‘car’ and
5705‘cdr’.  For example, ‘cons’ can be used to make a four element list from
5706the three element list, ‘(fir oak maple)’:
5707
5708     (cons 'pine '(fir oak maple))
5709
5710After evaluating this list, you will see
5711
5712     (pine fir oak maple)
5713
5714appear in the echo area.  ‘cons’ causes the creation of a new list in
5715which the element is followed by the elements of the original list.
5716
5717   We often say that ‘cons’ puts a new element at the beginning of a
5718list, or that it attaches or pushes elements onto the list, but this
5719phrasing can be misleading, since ‘cons’ does not change an existing
5720list, but creates a new one.
5721
5722   Like ‘car’ and ‘cdr’, ‘cons’ is non-destructive.
5723
5724* Menu:
5725
5726* Build a list::
5727* length::                      How to find the length of a list.
5728
5729
5730File: eintr.info,  Node: Build a list,  Next: length,  Up: cons
5731
5732Build a list
5733------------
5734
5735‘cons’ must have a list to attach to.(1)  You cannot start from
5736absolutely nothing.  If you are building a list, you need to provide at
5737least an empty list at the beginning.  Here is a series of ‘cons’
5738expressions that build up a list of flowers.  If you are reading this in
5739Info in GNU Emacs, you can evaluate each of the expressions in the usual
5740way; the value is printed in this text after ‘⇒’, which you may read as
5741“evaluates to”.
5742
5743     (cons 'buttercup ())
5744          ⇒ (buttercup)
5745
5746     (cons 'daisy '(buttercup))
5747          ⇒ (daisy buttercup)
5748
5749     (cons 'violet '(daisy buttercup))
5750          ⇒ (violet daisy buttercup)
5751
5752     (cons 'rose '(violet daisy buttercup))
5753          ⇒ (rose violet daisy buttercup)
5754
5755In the first example, the empty list is shown as ‘()’ and a list made up
5756of ‘buttercup’ followed by the empty list is constructed.  As you can
5757see, the empty list is not shown in the list that was constructed.  All
5758that you see is ‘(buttercup)’.  The empty list is not counted as an
5759element of a list because there is nothing in an empty list.  Generally
5760speaking, an empty list is invisible.
5761
5762   The second example, ‘(cons 'daisy '(buttercup))’ constructs a new,
5763two element list by putting ‘daisy’ in front of ‘buttercup’; and the
5764third example constructs a three element list by putting ‘violet’ in
5765front of ‘daisy’ and ‘buttercup’.
5766
5767   ---------- Footnotes ----------
5768
5769   (1) Actually, you can ‘cons’ an element to an atom to produce a
5770dotted pair.  Dotted pairs are not discussed here; see *note Dotted Pair
5771Notation: (elisp)Dotted Pair Notation.
5772
5773
5774File: eintr.info,  Node: length,  Prev: Build a list,  Up: cons
5775
57767.2.1 Find the Length of a List: ‘length’
5777-----------------------------------------
5778
5779You can find out how many elements there are in a list by using the Lisp
5780function ‘length’, as in the following examples:
5781
5782     (length '(buttercup))
5783          ⇒ 1
5784
5785     (length '(daisy buttercup))
5786          ⇒ 2
5787
5788     (length (cons 'violet '(daisy buttercup)))
5789          ⇒ 3
5790
5791In the third example, the ‘cons’ function is used to construct a three
5792element list which is then passed to the ‘length’ function as its
5793argument.
5794
5795   We can also use ‘length’ to count the number of elements in an empty
5796list:
5797
5798     (length ())
5799          ⇒ 0
5800
5801As you would expect, the number of elements in an empty list is zero.
5802
5803   An interesting experiment is to find out what happens if you try to
5804find the length of no list at all; that is, if you try to call ‘length’
5805without giving it an argument, not even an empty list:
5806
5807     (length )
5808
5809What you see, if you evaluate this, is the error message
5810
5811     Lisp error: (wrong-number-of-arguments length 0)
5812
5813This means that the function receives the wrong number of arguments,
5814zero, when it expects some other number of arguments.  In this case, one
5815argument is expected, the argument being a list whose length the
5816function is measuring.  (Note that _one_ list is _one_ argument, even if
5817the list has many elements inside it.)
5818
5819   The part of the error message that says ‘length’ is the name of the
5820function.
5821
5822
5823File: eintr.info,  Node: nthcdr,  Next: nth,  Prev: cons,  Up: car cdr & cons
5824
58257.3 ‘nthcdr’
5826============
5827
5828The ‘nthcdr’ function is associated with the ‘cdr’ function.  What it
5829does is take the CDR of a list repeatedly.
5830
5831   If you take the CDR of the list ‘(pine fir oak maple)’, you will be
5832returned the list ‘(fir oak maple)’.  If you repeat this on what was
5833returned, you will be returned the list ‘(oak maple)’.  (Of course,
5834repeated CDRing on the original list will just give you the original CDR
5835since the function does not change the list.  You need to evaluate the
5836CDR of the CDR and so on.)  If you continue this, eventually you will be
5837returned an empty list, which in this case, instead of being shown as
5838‘()’ is shown as ‘nil’.
5839
5840   For review, here is a series of repeated CDRs, the text following the
5841‘⇒’ shows what is returned.
5842
5843     (cdr '(pine fir oak maple))
5844          ⇒(fir oak maple)
5845
5846     (cdr '(fir oak maple))
5847          ⇒ (oak maple)
5848
5849     (cdr '(oak maple))
5850          ⇒(maple)
5851
5852     (cdr '(maple))
5853          ⇒ nil
5854
5855     (cdr 'nil)
5856          ⇒ nil
5857
5858     (cdr ())
5859          ⇒ nil
5860
5861   You can also do several CDRs without printing the values in between,
5862like this:
5863
5864     (cdr (cdr '(pine fir oak maple)))
5865          ⇒ (oak maple)
5866
5867In this example, the Lisp interpreter evaluates the innermost list
5868first.  The innermost list is quoted, so it just passes the list as it
5869is to the innermost ‘cdr’.  This ‘cdr’ passes a list made up of the
5870second and subsequent elements of the list to the outermost ‘cdr’, which
5871produces a list composed of the third and subsequent elements of the
5872original list.  In this example, the ‘cdr’ function is repeated and
5873returns a list that consists of the original list without its first two
5874elements.
5875
5876   The ‘nthcdr’ function does the same as repeating the call to ‘cdr’.
5877In the following example, the argument 2 is passed to the function
5878‘nthcdr’, along with the list, and the value returned is the list
5879without its first two items, which is exactly the same as repeating
5880‘cdr’ twice on the list:
5881
5882     (nthcdr 2 '(pine fir oak maple))
5883          ⇒ (oak maple)
5884
5885   Using the original four element list, we can see what happens when
5886various numeric arguments are passed to ‘nthcdr’, including 0, 1, and 5:
5887
5888     ;; Leave the list as it was.
5889     (nthcdr 0 '(pine fir oak maple))
5890          ⇒ (pine fir oak maple)
5891
5892     ;; Return a copy without the first element.
5893     (nthcdr 1 '(pine fir oak maple))
5894          ⇒ (fir oak maple)
5895
5896     ;; Return a copy of the list without three elements.
5897     (nthcdr 3 '(pine fir oak maple))
5898          ⇒ (maple)
5899
5900     ;; Return a copy lacking all four elements.
5901     (nthcdr 4 '(pine fir oak maple))
5902          ⇒ nil
5903
5904     ;; Return a copy lacking all elements.
5905     (nthcdr 5 '(pine fir oak maple))
5906          ⇒ nil
5907
5908
5909File: eintr.info,  Node: nth,  Next: setcar,  Prev: nthcdr,  Up: car cdr & cons
5910
59117.4 ‘nth’
5912=========
5913
5914The ‘nthcdr’ function takes the CDR of a list repeatedly.  The ‘nth’
5915function takes the CAR of the result returned by ‘nthcdr’.  It returns
5916the Nth element of the list.
5917
5918   Thus, if it were not defined in C for speed, the definition of ‘nth’
5919would be:
5920
5921     (defun nth (n list)
5922       "Returns the Nth element of LIST.
5923     N counts from zero.  If LIST is not that long, nil is returned."
5924       (car (nthcdr n list)))
5925
5926(Originally, ‘nth’ was defined in Emacs Lisp in ‘subr.el’, but its
5927definition was redone in C in the 1980s.)
5928
5929   The ‘nth’ function returns a single element of a list.  This can be
5930very convenient.
5931
5932   Note that the elements are numbered from zero, not one.  That is to
5933say, the first element of a list, its CAR is the zeroth element.  This
5934zero-based counting often bothers people who are accustomed to the first
5935element in a list being number one, which is one-based.
5936
5937   For example:
5938
5939     (nth 0 '("one" "two" "three"))
5940         ⇒ "one"
5941
5942     (nth 1 '("one" "two" "three"))
5943         ⇒ "two"
5944
5945   It is worth mentioning that ‘nth’, like ‘nthcdr’ and ‘cdr’, does not
5946change the original list—the function is non-destructive.  This is in
5947sharp contrast to the ‘setcar’ and ‘setcdr’ functions.
5948
5949
5950File: eintr.info,  Node: setcar,  Next: setcdr,  Prev: nth,  Up: car cdr & cons
5951
59527.5 ‘setcar’
5953============
5954
5955As you might guess from their names, the ‘setcar’ and ‘setcdr’ functions
5956set the CAR or the CDR of a list to a new value.  They actually change
5957the original list, unlike ‘car’ and ‘cdr’ which leave the original list
5958as it was.  One way to find out how this works is to experiment.  We
5959will start with the ‘setcar’ function.
5960
5961   First, we can make a list and then set the value of a variable to the
5962list, using the ‘setq’ special form.  Because we intend to use ‘setcar’
5963to change the list, this ‘setq’ should not use the quoted form
5964‘'(antelope giraffe lion tiger)’, as that would yield a list that is
5965part of the program and bad things could happen if we tried to change
5966part of the program while running it.  Generally speaking an Emacs Lisp
5967program’s components should be constant (or unchanged) while the program
5968is running.  So we instead construct an animal list by using the ‘list’
5969function, as follows:
5970
5971     (setq animals (list 'antelope 'giraffe 'lion 'tiger))
5972
5973If you are reading this in Info inside of GNU Emacs, you can evaluate
5974this expression in the usual fashion, by positioning the cursor after
5975the expression and typing ‘C-x C-e’.  (I’m doing this right here as I
5976write this.  This is one of the advantages of having the interpreter
5977built into the computing environment.  Incidentally, when there is
5978nothing on the line after the final parentheses, such as a comment,
5979point can be on the next line.  Thus, if your cursor is in the first
5980column of the next line, you do not need to move it.  Indeed, Emacs
5981permits any amount of white space after the final parenthesis.)
5982
5983   When we evaluate the variable ‘animals’, we see that it is bound to
5984the list ‘(antelope giraffe lion tiger)’:
5985
5986     animals
5987          ⇒ (antelope giraffe lion tiger)
5988
5989Put another way, the variable ‘animals’ points to the list ‘(antelope
5990giraffe lion tiger)’.
5991
5992   Next, evaluate the function ‘setcar’ while passing it two arguments,
5993the variable ‘animals’ and the quoted symbol ‘hippopotamus’; this is
5994done by writing the three element list ‘(setcar animals 'hippopotamus)’
5995and then evaluating it in the usual fashion:
5996
5997     (setcar animals 'hippopotamus)
5998
5999After evaluating this expression, evaluate the variable ‘animals’ again.
6000You will see that the list of animals has changed:
6001
6002     animals
6003          ⇒ (hippopotamus giraffe lion tiger)
6004
6005The first element on the list, ‘antelope’ is replaced by ‘hippopotamus’.
6006
6007   So we can see that ‘setcar’ did not add a new element to the list as
6008‘cons’ would have; it replaced ‘antelope’ with ‘hippopotamus’; it
6009_changed_ the list.
6010
6011
6012File: eintr.info,  Node: setcdr,  Next: cons Exercise,  Prev: setcar,  Up: car cdr & cons
6013
60147.6 ‘setcdr’
6015============
6016
6017The ‘setcdr’ function is similar to the ‘setcar’ function, except that
6018the function replaces the second and subsequent elements of a list
6019rather than the first element.
6020
6021   (To see how to change the last element of a list, look ahead to *note
6022The ‘kill-new’ function: kill-new function, which uses the ‘nthcdr’ and
6023‘setcdr’ functions.)
6024
6025   To see how this works, set the value of the variable to a list of
6026domesticated animals by evaluating the following expression:
6027
6028     (setq domesticated-animals (list 'horse 'cow 'sheep 'goat))
6029
6030If you now evaluate the list, you will be returned the list ‘(horse cow
6031sheep goat)’:
6032
6033     domesticated-animals
6034          ⇒ (horse cow sheep goat)
6035
6036   Next, evaluate ‘setcdr’ with two arguments, the name of the variable
6037which has a list as its value, and the list to which the CDR of the
6038first list will be set;
6039
6040     (setcdr domesticated-animals '(cat dog))
6041
6042If you evaluate this expression, the list ‘(cat dog)’ will appear in the
6043echo area.  This is the value returned by the function.  The result we
6044are interested in is the side effect, which we can see by evaluating the
6045variable ‘domesticated-animals’:
6046
6047     domesticated-animals
6048          ⇒ (horse cat dog)
6049
6050Indeed, the list is changed from ‘(horse cow sheep goat)’ to ‘(horse cat
6051dog)’.  The CDR of the list is changed from ‘(cow sheep goat)’ to ‘(cat
6052dog)’.
6053
6054
6055File: eintr.info,  Node: cons Exercise,  Prev: setcdr,  Up: car cdr & cons
6056
60577.7 Exercise
6058============
6059
6060Construct a list of four birds by evaluating several expressions with
6061‘cons’.  Find out what happens when you ‘cons’ a list onto itself.
6062Replace the first element of the list of four birds with a fish.
6063Replace the rest of that list with a list of other fish.
6064
6065
6066File: eintr.info,  Node: Cutting & Storing Text,  Next: List Implementation,  Prev: car cdr & cons,  Up: Top
6067
60688 Cutting and Storing Text
6069**************************
6070
6071Whenever you cut or clip text out of a buffer with a “kill” command in
6072GNU Emacs, it is stored in a list and you can bring it back with a
6073“yank” command.
6074
6075   (The use of the word “kill” in Emacs for processes which specifically
6076_do not_ destroy the values of the entities is an unfortunate historical
6077accident.  A much more appropriate word would be “clip” since that is
6078what the kill commands do; they clip text out of a buffer and put it
6079into storage from which it can be brought back.  I have often been
6080tempted to replace globally all occurrences of “kill” in the Emacs
6081sources with “clip” and all occurrences of “killed” with “clipped”.)
6082
6083* Menu:
6084
6085* Storing Text::                Text is stored in a list.
6086* zap-to-char::                 Cutting out text up to a character.
6087* kill-region::                 Cutting text out of a region.
6088* copy-region-as-kill::         A definition for copying text.
6089* Digression into C::           Minor note on C programming language macros.
6090* defvar::                      How to give a variable an initial value.
6091* cons & search-fwd Review::
6092* search Exercises::
6093
6094
6095File: eintr.info,  Node: Storing Text,  Next: zap-to-char,  Up: Cutting & Storing Text
6096
6097Storing Text in a List
6098======================
6099
6100When text is cut out of a buffer, it is stored on a list.  Successive
6101pieces of text are stored on the list successively, so the list might
6102look like this:
6103
6104     ("a piece of text" "previous piece")
6105
6106The function ‘cons’ can be used to create a new list from a piece of
6107text (an “atom”, to use the jargon) and an existing list, like this:
6108
6109     (cons "another piece"
6110           '("a piece of text" "previous piece"))
6111
6112If you evaluate this expression, a list of three elements will appear in
6113the echo area:
6114
6115     ("another piece" "a piece of text" "previous piece")
6116
6117   With the ‘car’ and ‘nthcdr’ functions, you can retrieve whichever
6118piece of text you want.  For example, in the following code, ‘nthcdr 1
6119...’ returns the list with the first item removed; and the ‘car’ returns
6120the first element of that remainder—the second element of the original
6121list:
6122
6123     (car (nthcdr 1 '("another piece"
6124                      "a piece of text"
6125                      "previous piece")))
6126          ⇒ "a piece of text"
6127
6128   The actual functions in Emacs are more complex than this, of course.
6129The code for cutting and retrieving text has to be written so that Emacs
6130can figure out which element in the list you want—the first, second,
6131third, or whatever.  In addition, when you get to the end of the list,
6132Emacs should give you the first element of the list, rather than nothing
6133at all.
6134
6135   The list that holds the pieces of text is called the “kill ring”.
6136This chapter leads up to a description of the kill ring and how it is
6137used by first tracing how the ‘zap-to-char’ function works.  This
6138function calls a function that invokes a function that manipulates the
6139kill ring.  Thus, before reaching the mountains, we climb the foothills.
6140
6141   A subsequent chapter describes how text that is cut from the buffer
6142is retrieved.  *Note Yanking Text Back: Yanking.
6143
6144
6145File: eintr.info,  Node: zap-to-char,  Next: kill-region,  Prev: Storing Text,  Up: Cutting & Storing Text
6146
61478.1 ‘zap-to-char’
6148=================
6149
6150Let us look at the interactive ‘zap-to-char’ function.
6151
6152* Menu:
6153
6154* Complete zap-to-char::        The complete implementation.
6155* zap-to-char interactive::     A three part interactive expression.
6156* zap-to-char body::            A short overview.
6157* search-forward::              How to search for a string.
6158* progn::                       The ‘progn’ special form.
6159* Summing up zap-to-char::      Using ‘point’ and ‘search-forward’.
6160
6161
6162File: eintr.info,  Node: Complete zap-to-char,  Next: zap-to-char interactive,  Up: zap-to-char
6163
6164The Complete ‘zap-to-char’ Implementation
6165-----------------------------------------
6166
6167The ‘zap-to-char’ function removes the text in the region between the
6168location of the cursor (i.e., of point) up to and including the next
6169occurrence of a specified character.  The text that ‘zap-to-char’
6170removes is put in the kill ring; and it can be retrieved from the kill
6171ring by typing ‘C-y’ (‘yank’).  If the command is given an argument, it
6172removes text through that number of occurrences.  Thus, if the cursor
6173were at the beginning of this sentence and the character were ‘s’,
6174‘Thus’ would be removed.  If the argument were two, ‘Thus, if the curs’
6175would be removed, up to and including the ‘s’ in ‘cursor’.
6176
6177   If the specified character is not found, ‘zap-to-char’ will say
6178“Search failed”, tell you the character you typed, and not remove any
6179text.
6180
6181   In order to determine how much text to remove, ‘zap-to-char’ uses a
6182search function.  Searches are used extensively in code that manipulates
6183text, and we will focus attention on them as well as on the deletion
6184command.
6185
6186   Here is the complete text of the version 22 implementation of the
6187function:
6188
6189     (defun zap-to-char (arg char)
6190       "Kill up to and including ARG'th occurrence of CHAR.
6191     Case is ignored if `case-fold-search' is non-nil in the current buffer.
6192     Goes backward if ARG is negative; error if CHAR not found."
6193       (interactive "p\ncZap to char: ")
6194       (if (char-table-p translation-table-for-input)
6195           (setq char (or (aref translation-table-for-input char) char)))
6196       (kill-region (point) (progn
6197                              (search-forward (char-to-string char)
6198                                              nil nil arg)
6199                              (point))))
6200
6201   The documentation is thorough.  You do need to know the jargon
6202meaning of the word “kill”.
6203
6204   The version 22 documentation string for ‘zap-to-char’ uses ASCII
6205grave accent and apostrophe to quote a symbol, so it appears as
6206`case-fold-search'.  This quoting style was inspired by 1970s-era
6207displays in which grave accent and apostrophe were often mirror images
6208suitable for use as quotes.  On most modern displays this is no longer
6209true, and when these two ASCII characters appear in documentation
6210strings or diagnostic message formats, Emacs typically transliterates
6211them to “curved quotes” (left and right single quotation marks), so that
6212the abovequoted symbol appears as ‘case-fold-search’.  Source-code
6213strings can also simply use curved quotes directly.
6214
6215
6216File: eintr.info,  Node: zap-to-char interactive,  Next: zap-to-char body,  Prev: Complete zap-to-char,  Up: zap-to-char
6217
62188.1.1 The ‘interactive’ Expression
6219----------------------------------
6220
6221The interactive expression in the ‘zap-to-char’ command looks like this:
6222
6223     (interactive "p\ncZap to char: ")
6224
6225   The part within quotation marks, ‘"p\ncZap to char: "’, specifies two
6226different things.  First, and most simply, is the ‘p’.  This part is
6227separated from the next part by a newline, ‘\n’.  The ‘p’ means that the
6228first argument to the function will be passed the value of a “processed
6229prefix”.  The prefix argument is passed by typing ‘C-u’ and a number, or
6230‘M-’ and a number.  If the function is called interactively without a
6231prefix, 1 is passed to this argument.
6232
6233   The second part of ‘"p\ncZap to char: "’ is ‘cZap to char: ’.  In
6234this part, the lower case ‘c’ indicates that ‘interactive’ expects a
6235prompt and that the argument will be a character.  The prompt follows
6236the ‘c’ and is the string ‘Zap to char: ’ (with a space after the colon
6237to make it look good).
6238
6239   What all this does is prepare the arguments to ‘zap-to-char’ so they
6240are of the right type, and give the user a prompt.
6241
6242   In a read-only buffer, the ‘zap-to-char’ function copies the text to
6243the kill ring, but does not remove it.  The echo area displays a message
6244saying that the buffer is read-only.  Also, the terminal may beep or
6245blink at you.
6246
6247
6248File: eintr.info,  Node: zap-to-char body,  Next: search-forward,  Prev: zap-to-char interactive,  Up: zap-to-char
6249
62508.1.2 The Body of ‘zap-to-char’
6251-------------------------------
6252
6253The body of the ‘zap-to-char’ function contains the code that kills
6254(that is, removes) the text in the region from the current position of
6255the cursor up to and including the specified character.
6256
6257   The first part of the code looks like this:
6258
6259     (if (char-table-p translation-table-for-input)
6260         (setq char (or (aref translation-table-for-input char) char)))
6261     (kill-region (point) (progn
6262                            (search-forward (char-to-string char) nil nil arg)
6263                            (point)))
6264
6265‘char-table-p’ is a hitherto unseen function.  It determines whether its
6266argument is a character table.  When it is, it sets the character passed
6267to ‘zap-to-char’ to one of them, if that character exists, or to the
6268character itself.  (This becomes important for certain characters in
6269non-European languages.  The ‘aref’ function extracts an element from an
6270array.  It is an array-specific function that is not described in this
6271document.  *Note Arrays: (elisp)Arrays.)
6272
6273‘(point)’ is the current position of the cursor.
6274
6275   The next part of the code is an expression using ‘progn’.  The body
6276of the ‘progn’ consists of calls to ‘search-forward’ and ‘point’.
6277
6278   It is easier to understand how ‘progn’ works after learning about
6279‘search-forward’, so we will look at ‘search-forward’ and then at
6280‘progn’.
6281
6282
6283File: eintr.info,  Node: search-forward,  Next: progn,  Prev: zap-to-char body,  Up: zap-to-char
6284
62858.1.3 The ‘search-forward’ Function
6286-----------------------------------
6287
6288The ‘search-forward’ function is used to locate the zapped-for-character
6289in ‘zap-to-char’.  If the search is successful, ‘search-forward’ leaves
6290point immediately after the last character in the target string.  (In
6291‘zap-to-char’, the target string is just one character long.
6292‘zap-to-char’ uses the function ‘char-to-string’ to ensure that the
6293computer treats that character as a string.)  If the search is
6294backwards, ‘search-forward’ leaves point just before the first character
6295in the target.  Also, ‘search-forward’ returns ‘t’ for true.  (Moving
6296point is therefore a side effect.)
6297
6298   In ‘zap-to-char’, the ‘search-forward’ function looks like this:
6299
6300     (search-forward (char-to-string char) nil nil arg)
6301
6302   The ‘search-forward’ function takes four arguments:
6303
6304  1. The first argument is the target, what is searched for.  This must
6305     be a string, such as ‘"z"’.
6306
6307     As it happens, the argument passed to ‘zap-to-char’ is a single
6308     character.  Because of the way computers are built, the Lisp
6309     interpreter may treat a single character as being different from a
6310     string of characters.  Inside the computer, a single character has
6311     a different electronic format than a string of one character.  (A
6312     single character can often be recorded in the computer using
6313     exactly one byte; but a string may be longer, and the computer
6314     needs to be ready for this.)  Since the ‘search-forward’ function
6315     searches for a string, the character that the ‘zap-to-char’
6316     function receives as its argument must be converted inside the
6317     computer from one format to the other; otherwise the
6318     ‘search-forward’ function will fail.  The ‘char-to-string’ function
6319     is used to make this conversion.
6320
6321  2. The second argument bounds the search; it is specified as a
6322     position in the buffer.  In this case, the search can go to the end
6323     of the buffer, so no bound is set and the second argument is ‘nil’.
6324
6325  3. The third argument tells the function what it should do if the
6326     search fails—it can signal an error (and print a message) or it can
6327     return ‘nil’.  A ‘nil’ as the third argument causes the function to
6328     signal an error when the search fails.
6329
6330  4. The fourth argument to ‘search-forward’ is the repeat count—how
6331     many occurrences of the string to look for.  This argument is
6332     optional and if the function is called without a repeat count, this
6333     argument is passed the value 1.  If this argument is negative, the
6334     search goes backwards.
6335
6336   In template form, a ‘search-forward’ expression looks like this:
6337
6338     (search-forward "TARGET-STRING"
6339                     LIMIT-OF-SEARCH
6340                     WHAT-TO-DO-IF-SEARCH-FAILS
6341                     REPEAT-COUNT)
6342
6343   We will look at ‘progn’ next.
6344
6345
6346File: eintr.info,  Node: progn,  Next: Summing up zap-to-char,  Prev: search-forward,  Up: zap-to-char
6347
63488.1.4 The ‘progn’ Special Form
6349------------------------------
6350
6351‘progn’ is a special form that causes each of its arguments to be
6352evaluated in sequence and then returns the value of the last one.  The
6353preceding expressions are evaluated only for the side effects they
6354perform.  The values produced by them are discarded.
6355
6356   The template for a ‘progn’ expression is very simple:
6357
6358     (progn
6359       BODY...)
6360
6361   In ‘zap-to-char’, the ‘progn’ expression has to do two things: put
6362point in exactly the right position; and return the location of point so
6363that ‘kill-region’ will know how far to kill to.
6364
6365   The first argument to the ‘progn’ is ‘search-forward’.  When
6366‘search-forward’ finds the string, the function leaves point immediately
6367after the last character in the target string.  (In this case the target
6368string is just one character long.)  If the search is backwards,
6369‘search-forward’ leaves point just before the first character in the
6370target.  The movement of point is a side effect.
6371
6372   The second and last argument to ‘progn’ is the expression ‘(point)’.
6373This expression returns the value of point, which in this case will be
6374the location to which it has been moved by ‘search-forward’.  (In the
6375source, a line that tells the function to go to the previous character,
6376if it is going forward, was commented out in 1999; I don’t remember
6377whether that feature or mis-feature was ever a part of the distributed
6378source.)  The value of ‘point’ is returned by the ‘progn’ expression and
6379is passed to ‘kill-region’ as ‘kill-region’’s second argument.
6380
6381
6382File: eintr.info,  Node: Summing up zap-to-char,  Prev: progn,  Up: zap-to-char
6383
63848.1.5 Summing up ‘zap-to-char’
6385------------------------------
6386
6387Now that we have seen how ‘search-forward’ and ‘progn’ work, we can see
6388how the ‘zap-to-char’ function works as a whole.
6389
6390   The first argument to ‘kill-region’ is the position of the cursor
6391when the ‘zap-to-char’ command is given—the value of point at that time.
6392Within the ‘progn’, the search function then moves point to just after
6393the zapped-to-character and ‘point’ returns the value of this location.
6394The ‘kill-region’ function puts together these two values of point, the
6395first one as the beginning of the region and the second one as the end
6396of the region, and removes the region.
6397
6398   The ‘progn’ special form is necessary because the ‘kill-region’
6399command takes two arguments; and it would fail if ‘search-forward’ and
6400‘point’ expressions were written in sequence as two additional
6401arguments.  The ‘progn’ expression is a single argument to ‘kill-region’
6402and returns the one value that ‘kill-region’ needs for its second
6403argument.
6404
6405
6406File: eintr.info,  Node: kill-region,  Next: copy-region-as-kill,  Prev: zap-to-char,  Up: Cutting & Storing Text
6407
64088.2 ‘kill-region’
6409=================
6410
6411The ‘zap-to-char’ function uses the ‘kill-region’ function.  This
6412function clips text from a region and copies that text to the kill ring,
6413from which it may be retrieved.
6414
6415   The Emacs 22 version of that function uses ‘condition-case’ and
6416‘copy-region-as-kill’, both of which we will explain.  ‘condition-case’
6417is an important special form.
6418
6419   In essence, the ‘kill-region’ function calls ‘condition-case’, which
6420takes three arguments.  In this function, the first argument does
6421nothing.  The second argument contains the code that does the work when
6422all goes well.  The third argument contains the code that is called in
6423the event of an error.
6424
6425* Menu:
6426
6427* Complete kill-region::        The function definition.
6428* condition-case::              Dealing with a problem.
6429* Lisp macro::
6430
6431
6432File: eintr.info,  Node: Complete kill-region,  Next: condition-case,  Up: kill-region
6433
6434The Complete ‘kill-region’ Definition
6435-------------------------------------
6436
6437We will go through the ‘condition-case’ code in a moment.  First, let us
6438look at the definition of ‘kill-region’, with comments added:
6439
6440     (defun kill-region (beg end)
6441       "Kill (\"cut\") text between point and mark.
6442     This deletes the text from the buffer and saves it in the kill ring.
6443     The command \\[yank] can retrieve it from there. ... "
6444
6445       ;; • Since order matters, pass point first.
6446       (interactive (list (point) (mark)))
6447       ;; • And tell us if we cannot cut the text.
6448       ;; 'unless' is an 'if' without a then-part.
6449       (unless (and beg end)
6450         (error "The mark is not set now, so there is no region"))
6451
6452       ;; • 'condition-case' takes three arguments.
6453       ;;    If the first argument is nil, as it is here,
6454       ;;    information about the error signal is not
6455       ;;    stored for use by another function.
6456       (condition-case nil
6457
6458           ;; • The second argument to 'condition-case' tells the
6459           ;;    Lisp interpreter what to do when all goes well.
6460
6461           ;;    It starts with a 'let' function that extracts the string
6462           ;;    and tests whether it exists.  If so (that is what the
6463           ;;    'when' checks), it calls an 'if' function that determines
6464           ;;    whether the previous command was another call to
6465           ;;    'kill-region'; if it was, then the new text is appended to
6466           ;;    the previous text; if not, then a different function,
6467           ;;    'kill-new', is called.
6468
6469           ;;    The 'kill-append' function concatenates the new string and
6470           ;;    the old.  The 'kill-new' function inserts text into a new
6471           ;;    item in the kill ring.
6472
6473           ;;    'when' is an 'if' without an else-part.  The second 'when'
6474           ;;    again checks whether the current string exists; in
6475           ;;    addition, it checks whether the previous command was
6476           ;;    another call to 'kill-region'.  If one or the other
6477           ;;    condition is true, then it sets the current command to
6478           ;;    be 'kill-region'.
6479           (let ((string (filter-buffer-substring beg end t)))
6480             (when string                    ;STRING is nil if BEG = END
6481               ;; Add that string to the kill ring, one way or another.
6482               (if (eq last-command 'kill-region)
6483                   ;;    − 'yank-handler' is an optional argument to
6484                   ;;    'kill-region' that tells the 'kill-append' and
6485                   ;;    'kill-new' functions how deal with properties
6486                   ;;    added to the text, such as 'bold' or 'italics'.
6487                   (kill-append string (< end beg) yank-handler)
6488                 (kill-new string nil yank-handler)))
6489             (when (or string (eq last-command 'kill-region))
6490               (setq this-command 'kill-region))
6491             nil)
6492
6493         ;;  • The third argument to 'condition-case' tells the interpreter
6494         ;;    what to do with an error.
6495         ;;    The third argument has a conditions part and a body part.
6496         ;;    If the conditions are met (in this case,
6497         ;;             if text or buffer are read-only)
6498         ;;    then the body is executed.
6499         ;;    The first part of the third argument is the following:
6500         ((buffer-read-only text-read-only) ;; the if-part
6501          ;; ...  the then-part
6502          (copy-region-as-kill beg end)
6503          ;;    Next, also as part of the then-part, set this-command, so
6504          ;;    it will be set in an error
6505          (setq this-command 'kill-region)
6506          ;;    Finally, in the then-part, send a message if you may copy
6507          ;;    the text to the kill ring without signaling an error, but
6508          ;;    don't if you may not.
6509          (if kill-read-only-ok
6510              (progn (message "Read only text copied to kill ring") nil)
6511            (barf-if-buffer-read-only)
6512            ;; If the buffer isn't read-only, the text is.
6513            (signal 'text-read-only (list (current-buffer)))))
6514
6515
6516File: eintr.info,  Node: condition-case,  Next: Lisp macro,  Prev: Complete kill-region,  Up: kill-region
6517
65188.2.1 ‘condition-case’
6519----------------------
6520
6521As we have seen earlier (*note Generate an Error Message: Making
6522Errors.), when the Emacs Lisp interpreter has trouble evaluating an
6523expression, it provides you with help; in the jargon, this is called
6524“signaling an error”.  Usually, the computer stops the program and shows
6525you a message.
6526
6527   However, some programs undertake complicated actions.  They should
6528not simply stop on an error.  In the ‘kill-region’ function, the most
6529likely error is that you will try to kill text that is read-only and
6530cannot be removed.  So the ‘kill-region’ function contains code to
6531handle this circumstance.  This code, which makes up the body of the
6532‘kill-region’ function, is inside of a ‘condition-case’ special form.
6533
6534   The template for ‘condition-case’ looks like this:
6535
6536     (condition-case
6537       VAR
6538       BODYFORM
6539       ERROR-HANDLER...)
6540
6541   The second argument, BODYFORM, is straightforward.  The
6542‘condition-case’ special form causes the Lisp interpreter to evaluate
6543the code in BODYFORM.  If no error occurs, the special form returns the
6544code’s value and produces the side-effects, if any.
6545
6546   In short, the BODYFORM part of a ‘condition-case’ expression
6547determines what should happen when everything works correctly.
6548
6549   However, if an error occurs, among its other actions, the function
6550generating the error signal will define one or more error condition
6551names.
6552
6553   An error handler is the third argument to ‘condition-case’.  An error
6554handler has two parts, a CONDITION-NAME and a BODY.  If the
6555CONDITION-NAME part of an error handler matches a condition name
6556generated by an error, then the BODY part of the error handler is run.
6557
6558   As you will expect, the CONDITION-NAME part of an error handler may
6559be either a single condition name or a list of condition names.
6560
6561   Also, a complete ‘condition-case’ expression may contain more than
6562one error handler.  When an error occurs, the first applicable handler
6563is run.
6564
6565   Lastly, the first argument to the ‘condition-case’ expression, the
6566VAR argument, is sometimes bound to a variable that contains information
6567about the error.  However, if that argument is nil, as is the case in
6568‘kill-region’, that information is discarded.
6569
6570   In brief, in the ‘kill-region’ function, the code ‘condition-case’
6571works like this:
6572
6573     IF NO ERRORS, RUN ONLY THIS CODE
6574         BUT, IF ERRORS, RUN THIS OTHER CODE.
6575
6576
6577File: eintr.info,  Node: Lisp macro,  Prev: condition-case,  Up: kill-region
6578
65798.2.2 Lisp macro
6580----------------
6581
6582The part of the ‘condition-case’ expression that is evaluated in the
6583expectation that all goes well has a ‘when’.  The code uses ‘when’ to
6584determine whether the ‘string’ variable points to text that exists.
6585
6586   A ‘when’ expression is simply a programmers’ convenience.  It is an
6587‘if’ without the possibility of an else clause.  In your mind, you can
6588replace ‘when’ with ‘if’ and understand what goes on.  That is what the
6589Lisp interpreter does.
6590
6591   Technically speaking, ‘when’ is a Lisp macro.  A Lisp macro enables
6592you to define new control constructs and other language features.  It
6593tells the interpreter how to compute another Lisp expression which will
6594in turn compute the value.  In this case, the other expression is an
6595‘if’ expression.
6596
6597   The ‘kill-region’ function definition also has an ‘unless’ macro; it
6598is the converse of ‘when’.  The ‘unless’ macro is an ‘if’ without a then
6599clause
6600
6601   For more about Lisp macros, see *note Macros: (elisp)Macros.  The C
6602programming language also provides macros.  These are different, but
6603also useful.
6604
6605   Regarding the ‘when’ macro, in the ‘condition-case’ expression, when
6606the string has content, then another conditional expression is executed.
6607This is an ‘if’ with both a then-part and an else-part.
6608
6609     (if (eq last-command 'kill-region)
6610         (kill-append string (< end beg) yank-handler)
6611       (kill-new string nil yank-handler))
6612
6613   The then-part is evaluated if the previous command was another call
6614to ‘kill-region’; if not, the else-part is evaluated.
6615
6616   ‘yank-handler’ is an optional argument to ‘kill-region’ that tells
6617the ‘kill-append’ and ‘kill-new’ functions how deal with properties
6618added to the text, such as bold or italics.
6619
6620   ‘last-command’ is a variable that comes with Emacs that we have not
6621seen before.  Normally, whenever a function is executed, Emacs sets the
6622value of ‘last-command’ to the previous command.
6623
6624   In this segment of the definition, the ‘if’ expression checks whether
6625the previous command was ‘kill-region’.  If it was,
6626
6627     (kill-append string (< end beg) yank-handler)
6628
6629concatenates a copy of the newly clipped text to the just previously
6630clipped text in the kill ring.
6631
6632
6633File: eintr.info,  Node: copy-region-as-kill,  Next: Digression into C,  Prev: kill-region,  Up: Cutting & Storing Text
6634
66358.3 ‘copy-region-as-kill’
6636=========================
6637
6638The ‘copy-region-as-kill’ function copies a region of text from a buffer
6639and (via either ‘kill-append’ or ‘kill-new’) saves it in the
6640‘kill-ring’.
6641
6642   If you call ‘copy-region-as-kill’ immediately after a ‘kill-region’
6643command, Emacs appends the newly copied text to the previously copied
6644text.  This means that if you yank back the text, you get it all, from
6645both this and the previous operation.  On the other hand, if some other
6646command precedes the ‘copy-region-as-kill’, the function copies the text
6647into a separate entry in the kill ring.
6648
6649* Menu:
6650
6651* Complete copy-region-as-kill::  The complete function definition.
6652* copy-region-as-kill body::      The body of ‘copy-region-as-kill’.
6653
6654
6655File: eintr.info,  Node: Complete copy-region-as-kill,  Next: copy-region-as-kill body,  Up: copy-region-as-kill
6656
6657The complete ‘copy-region-as-kill’ function definition
6658------------------------------------------------------
6659
6660Here is the complete text of the version 22 ‘copy-region-as-kill’
6661function:
6662
6663     (defun copy-region-as-kill (beg end)
6664       "Save the region as if killed, but don't kill it.
6665     In Transient Mark mode, deactivate the mark.
6666     If `interprogram-cut-function' is non-nil, also save the text for a window
6667     system cut and paste."
6668       (interactive "r")
6669       (if (eq last-command 'kill-region)
6670           (kill-append (filter-buffer-substring beg end) (< end beg))
6671         (kill-new (filter-buffer-substring beg end)))
6672       (if transient-mark-mode
6673           (setq deactivate-mark t))
6674       nil)
6675
6676   As usual, this function can be divided into its component parts:
6677
6678     (defun copy-region-as-kill (ARGUMENT-LIST)
6679       "DOCUMENTATION..."
6680       (interactive "r")
6681       BODY...)
6682
6683   The arguments are ‘beg’ and ‘end’ and the function is interactive
6684with ‘"r"’, so the two arguments must refer to the beginning and end of
6685the region.  If you have been reading through this document from the
6686beginning, understanding these parts of a function is almost becoming
6687routine.
6688
6689   The documentation is somewhat confusing unless you remember that the
6690word “kill” has a meaning different from usual.  The Transient Mark and
6691‘interprogram-cut-function’ comments explain certain side-effects.
6692
6693   After you once set a mark, a buffer always contains a region.  If you
6694wish, you can use Transient Mark mode to highlight the region
6695temporarily.  (No one wants to highlight the region all the time, so
6696Transient Mark mode highlights it only at appropriate times.  Many
6697people turn off Transient Mark mode, so the region is never
6698highlighted.)
6699
6700   Also, a windowing system allows you to copy, cut, and paste among
6701different programs.  In the X windowing system, for example, the
6702‘interprogram-cut-function’ function is ‘x-select-text’, which works
6703with the windowing system’s equivalent of the Emacs kill ring.
6704
6705   The body of the ‘copy-region-as-kill’ function starts with an ‘if’
6706clause.  What this clause does is distinguish between two different
6707situations: whether or not this command is executed immediately after a
6708previous ‘kill-region’ command.  In the first case, the new region is
6709appended to the previously copied text.  Otherwise, it is inserted into
6710the beginning of the kill ring as a separate piece of text from the
6711previous piece.
6712
6713   The last two lines of the function prevent the region from lighting
6714up if Transient Mark mode is turned on.
6715
6716   The body of ‘copy-region-as-kill’ merits discussion in detail.
6717
6718
6719File: eintr.info,  Node: copy-region-as-kill body,  Prev: Complete copy-region-as-kill,  Up: copy-region-as-kill
6720
67218.3.1 The Body of ‘copy-region-as-kill’
6722---------------------------------------
6723
6724The ‘copy-region-as-kill’ function works in much the same way as the
6725‘kill-region’ function.  Both are written so that two or more kills in a
6726row combine their text into a single entry.  If you yank back the text
6727from the kill ring, you get it all in one piece.  Moreover, kills that
6728kill forward from the current position of the cursor are added to the
6729end of the previously copied text and commands that copy text backwards
6730add it to the beginning of the previously copied text.  This way, the
6731words in the text stay in the proper order.
6732
6733   Like ‘kill-region’, the ‘copy-region-as-kill’ function makes use of
6734the ‘last-command’ variable that keeps track of the previous Emacs
6735command.
6736
6737* Menu:
6738
6739* last-command & this-command::
6740* kill-append function::
6741* kill-new function::
6742
6743
6744File: eintr.info,  Node: last-command & this-command,  Next: kill-append function,  Up: copy-region-as-kill body
6745
6746‘last-command’ and ‘this-command’
6747.................................
6748
6749Normally, whenever a function is executed, Emacs sets the value of
6750‘this-command’ to the function being executed (which in this case would
6751be ‘copy-region-as-kill’).  At the same time, Emacs sets the value of
6752‘last-command’ to the previous value of ‘this-command’.
6753
6754   In the first part of the body of the ‘copy-region-as-kill’ function,
6755an ‘if’ expression determines whether the value of ‘last-command’ is
6756‘kill-region’.  If so, the then-part of the ‘if’ expression is
6757evaluated; it uses the ‘kill-append’ function to concatenate the text
6758copied at this call to the function with the text already in the first
6759element (the CAR) of the kill ring.  On the other hand, if the value of
6760‘last-command’ is not ‘kill-region’, then the ‘copy-region-as-kill’
6761function attaches a new element to the kill ring using the ‘kill-new’
6762function.
6763
6764   The ‘if’ expression reads as follows; it uses ‘eq’:
6765
6766       (if (eq last-command 'kill-region)
6767           ;; then-part
6768           (kill-append  (filter-buffer-substring beg end) (< end beg))
6769         ;; else-part
6770         (kill-new  (filter-buffer-substring beg end)))
6771
6772   (The ‘filter-buffer-substring’ function returns a filtered substring
6773of the buffer, if any.  Optionally—the arguments are not here, so
6774neither is done—the function may delete the initial text or return the
6775text without its properties; this function is a replacement for the
6776older ‘buffer-substring’ function, which came before text properties
6777were implemented.)
6778
6779The ‘eq’ function tests whether its first argument is the same Lisp
6780object as its second argument.  The ‘eq’ function is similar to the
6781‘equal’ function in that it is used to test for equality, but differs in
6782that it determines whether two representations are actually the same
6783object inside the computer, but with different names.  ‘equal’
6784determines whether the structure and contents of two expressions are the
6785same.
6786
6787   If the previous command was ‘kill-region’, then the Emacs Lisp
6788interpreter calls the ‘kill-append’ function
6789
6790
6791File: eintr.info,  Node: kill-append function,  Next: kill-new function,  Prev: last-command & this-command,  Up: copy-region-as-kill body
6792
6793The ‘kill-append’ function
6794..........................
6795
6796The ‘kill-append’ function looks like this:
6797
6798     (defun kill-append (string before-p &optional yank-handler)
6799       "Append STRING to the end of the latest kill in the kill ring.
6800     If BEFORE-P is non-nil, prepend STRING to the kill.
6801     ... "
6802       (let* ((cur (car kill-ring)))
6803         (kill-new (if before-p (concat string cur) (concat cur string))
6804                   (or (= (length cur) 0)
6805                       (equal yank-handler
6806                              (get-text-property 0 'yank-handler cur)))
6807                   yank-handler)))
6808
6809The ‘kill-append’ function is fairly straightforward.  It uses the
6810‘kill-new’ function, which we will discuss in more detail in a moment.
6811
6812   (Also, the function provides an optional argument called
6813‘yank-handler’; when invoked, this argument tells the function how to
6814deal with properties added to the text, such as bold or italics.)
6815
6816   It has a ‘let*’ function to set the value of the first element of the
6817kill ring to ‘cur’.  (I do not know why the function does not use ‘let’
6818instead; only one value is set in the expression.  Perhaps this is a bug
6819that produces no problems?)
6820
6821   Consider the conditional that is one of the two arguments to
6822‘kill-new’.  It uses ‘concat’ to concatenate the new text to the CAR of
6823the kill ring.  Whether it prepends or appends the text depends on the
6824results of an ‘if’ expression:
6825
6826     (if before-p                            ; if-part
6827         (concat string cur)                 ; then-part
6828       (concat cur string))                  ; else-part
6829
6830If the region being killed is before the region that was killed in the
6831last command, then it should be prepended before the material that was
6832saved in the previous kill; and conversely, if the killed text follows
6833what was just killed, it should be appended after the previous text.
6834The ‘if’ expression depends on the predicate ‘before-p’ to decide
6835whether the newly saved text should be put before or after the
6836previously saved text.
6837
6838   The symbol ‘before-p’ is the name of one of the arguments to
6839‘kill-append’.  When the ‘kill-append’ function is evaluated, it is
6840bound to the value returned by evaluating the actual argument.  In this
6841case, this is the expression ‘(< end beg)’.  This expression does not
6842directly determine whether the killed text in this command is located
6843before or after the kill text of the last command; what it does is
6844determine whether the value of the variable ‘end’ is less than the value
6845of the variable ‘beg’.  If it is, it means that the user is most likely
6846heading towards the beginning of the buffer.  Also, the result of
6847evaluating the predicate expression, ‘(< end beg)’, will be true and the
6848text will be prepended before the previous text.  On the other hand, if
6849the value of the variable ‘end’ is greater than the value of the
6850variable ‘beg’, the text will be appended after the previous text.
6851
6852   When the newly saved text will be prepended, then the string with the
6853new text will be concatenated before the old text:
6854
6855     (concat string cur)
6856
6857But if the text will be appended, it will be concatenated after the old
6858text:
6859
6860     (concat cur string))
6861
6862   To understand how this works, we first need to review the ‘concat’
6863function.  The ‘concat’ function links together or unites two strings of
6864text.  The result is a string.  For example:
6865
6866     (concat "abc" "def")
6867          ⇒ "abcdef"
6868
6869     (concat "new "
6870             (car '("first element" "second element")))
6871          ⇒ "new first element"
6872
6873     (concat (car
6874             '("first element" "second element")) " modified")
6875          ⇒ "first element modified"
6876
6877   We can now make sense of ‘kill-append’: it modifies the contents of
6878the kill ring.  The kill ring is a list, each element of which is saved
6879text.  The ‘kill-append’ function uses the ‘kill-new’ function which in
6880turn uses the ‘setcar’ function.
6881
6882
6883File: eintr.info,  Node: kill-new function,  Prev: kill-append function,  Up: copy-region-as-kill body
6884
6885The ‘kill-new’ function
6886.......................
6887
6888In version 22 the ‘kill-new’ function looks like this:
6889
6890     (defun kill-new (string &optional replace yank-handler)
6891       "Make STRING the latest kill in the kill ring.
6892     Set `kill-ring-yank-pointer' to point to it.
6893
6894     If `interprogram-cut-function' is non-nil, apply it to STRING.
6895     Optional second argument REPLACE non-nil means that STRING will replace
6896     the front of the kill ring, rather than being added to the list.
6897     ..."
6898       (if (> (length string) 0)
6899           (if yank-handler
6900               (put-text-property 0 (length string)
6901                                  'yank-handler yank-handler string))
6902         (if yank-handler
6903             (signal 'args-out-of-range
6904                     (list string "yank-handler specified for empty string"))))
6905       (if (fboundp 'menu-bar-update-yank-menu)
6906           (menu-bar-update-yank-menu string (and replace (car kill-ring))))
6907       (if (and replace kill-ring)
6908           (setcar kill-ring string)
6909         (push string kill-ring)
6910         (if (> (length kill-ring) kill-ring-max)
6911             (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
6912       (setq kill-ring-yank-pointer kill-ring)
6913       (if interprogram-cut-function
6914           (funcall interprogram-cut-function string (not replace))))
6915
6916   (Notice that the function is not interactive.)
6917
6918   As usual, we can look at this function in parts.
6919
6920   The function definition has an optional ‘yank-handler’ argument,
6921which when invoked tells the function how to deal with properties added
6922to the text, such as bold or italics.  We will skip that.
6923
6924   The first line of the documentation makes sense:
6925
6926     Make STRING the latest kill in the kill ring.
6927
6928Let’s skip over the rest of the documentation for the moment.
6929
6930Also, let’s skip over the initial ‘if’ expression and those lines of
6931code involving ‘menu-bar-update-yank-menu’.  We will explain them below.
6932
6933   The critical lines are these:
6934
6935       (if (and replace kill-ring)
6936           ;; then
6937           (setcar kill-ring string)
6938         ;; else
6939         (push string kill-ring)
6940         (if (> (length kill-ring) kill-ring-max)
6941             ;; avoid overly long kill ring
6942             (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
6943       (setq kill-ring-yank-pointer kill-ring)
6944       (if interprogram-cut-function
6945           (funcall interprogram-cut-function string (not replace))))
6946
6947   The conditional test is ‘(and replace kill-ring)’.  This will be true
6948when two conditions are met: the kill ring has something in it, and the
6949‘replace’ variable is true.
6950
6951   When the ‘kill-append’ function sets ‘replace’ to be true and when
6952the kill ring has at least one item in it, the ‘setcar’ expression is
6953executed:
6954
6955     (setcar kill-ring string)
6956
6957   The ‘setcar’ function actually changes the first element of the
6958‘kill-ring’ list to the value of ‘string’.  It replaces the first
6959element.
6960
6961   On the other hand, if the kill ring is empty, or replace is false,
6962the else-part of the condition is executed:
6963
6964     (push string kill-ring)
6965
6966‘push’ puts its first argument onto the second.  It is similar to the
6967older
6968
6969     (setq kill-ring (cons string kill-ring))
6970
6971or the newer
6972
6973     (add-to-list kill-ring string)
6974
6975When it is false, the expression first constructs a new version of the
6976kill ring by prepending ‘string’ to the existing kill ring as a new
6977element (that is what the ‘push’ does).  Then it executes a second ‘if’
6978clause.  This second ‘if’ clause keeps the kill ring from growing too
6979long.
6980
6981   Let’s look at these two expressions in order.
6982
6983   The ‘push’ line of the else-part sets the new value of the kill ring
6984to what results from adding the string being killed to the old kill
6985ring.
6986
6987   We can see how this works with an example.
6988
6989   First,
6990
6991     (setq example-list '("here is a clause" "another clause"))
6992
6993After evaluating this expression with ‘C-x C-e’, you can evaluate
6994‘example-list’ and see what it returns:
6995
6996     example-list
6997          ⇒ ("here is a clause" "another clause")
6998
6999Now, we can add a new element on to this list by evaluating the
7000following expression:
7001
7002     (push "a third clause" example-list)
7003
7004When we evaluate ‘example-list’, we find its value is:
7005
7006     example-list
7007          ⇒ ("a third clause" "here is a clause" "another clause")
7008
7009Thus, the third clause is added to the list by ‘push’.
7010
7011   Now for the second part of the ‘if’ clause.  This expression keeps
7012the kill ring from growing too long.  It looks like this:
7013
7014     (if (> (length kill-ring) kill-ring-max)
7015         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
7016
7017   The code checks whether the length of the kill ring is greater than
7018the maximum permitted length.  This is the value of ‘kill-ring-max’
7019(which is 60, by default).  If the length of the kill ring is too long,
7020then this code sets the last element of the kill ring to ‘nil’.  It does
7021this by using two functions, ‘nthcdr’ and ‘setcdr’.
7022
7023   We looked at ‘setcdr’ earlier (*note ‘setcdr’: setcdr.).  It sets the
7024CDR of a list, just as ‘setcar’ sets the CAR of a list.  In this case,
7025however, ‘setcdr’ will not be setting the CDR of the whole kill ring;
7026the ‘nthcdr’ function is used to cause it to set the CDR of the next to
7027last element of the kill ring—this means that since the CDR of the next
7028to last element is the last element of the kill ring, it will set the
7029last element of the kill ring.
7030
7031   The ‘nthcdr’ function works by repeatedly taking the CDR of a list—it
7032takes the CDR of the CDR of the CDR ... It does this N times and returns
7033the results.  (*Note ‘nthcdr’: nthcdr.)
7034
7035   Thus, if we had a four element list that was supposed to be three
7036elements long, we could set the CDR of the next to last element to
7037‘nil’, and thereby shorten the list.  (If you set the last element to
7038some other value than ‘nil’, which you could do, then you would not have
7039shortened the list.  *Note ‘setcdr’: setcdr.)
7040
7041   You can see shortening by evaluating the following three expressions
7042in turn.  First set the value of ‘trees’ to ‘(maple oak pine birch)’,
7043then set the CDR of its second CDR to ‘nil’ and then find the value of
7044‘trees’:
7045
7046     (setq trees (list 'maple 'oak 'pine 'birch))
7047          ⇒ (maple oak pine birch)
7048
7049     (setcdr (nthcdr 2 trees) nil)
7050          ⇒ nil
7051
7052     trees
7053          ⇒ (maple oak pine)
7054
7055(The value returned by the ‘setcdr’ expression is ‘nil’ since that is
7056what the CDR is set to.)
7057
7058   To repeat, in ‘kill-new’, the ‘nthcdr’ function takes the CDR a
7059number of times that is one less than the maximum permitted size of the
7060kill ring and ‘setcdr’ sets the CDR of that element (which will be the
7061rest of the elements in the kill ring) to ‘nil’.  This prevents the kill
7062ring from growing too long.
7063
7064   The next to last expression in the ‘kill-new’ function is
7065
7066     (setq kill-ring-yank-pointer kill-ring)
7067
7068   The ‘kill-ring-yank-pointer’ is a global variable that is set to be
7069the ‘kill-ring’.
7070
7071   Even though the ‘kill-ring-yank-pointer’ is called a ‘pointer’, it is
7072a variable just like the kill ring.  However, the name has been chosen
7073to help humans understand how the variable is used.
7074
7075   Now, to return to an early expression in the body of the function:
7076
7077       (if (fboundp 'menu-bar-update-yank-menu)
7078            (menu-bar-update-yank-menu string (and replace (car kill-ring))))
7079
7080It starts with an ‘if’ expression
7081
7082   In this case, the expression tests first to see whether
7083‘menu-bar-update-yank-menu’ exists as a function, and if so, calls it.
7084The ‘fboundp’ function returns true if the symbol it is testing has a
7085function definition that is not void.  If the symbol’s function
7086definition were void, we would receive an error message, as we did when
7087we created errors intentionally (*note Generate an Error Message: Making
7088Errors.).
7089
7090The then-part contains an expression whose first element is the function
7091‘and’.
7092
7093   The ‘and’ special form evaluates each of its arguments until one of
7094the arguments returns a value of ‘nil’, in which case the ‘and’
7095expression returns ‘nil’; however, if none of the arguments returns a
7096value of ‘nil’, the value resulting from evaluating the last argument is
7097returned.  (Since such a value is not ‘nil’, it is considered true in
7098Emacs Lisp.)  In other words, an ‘and’ expression returns a true value
7099only if all its arguments are true.  (*Note Second Buffer Related
7100Review::.)
7101
7102   The expression determines whether the second argument to
7103‘menu-bar-update-yank-menu’ is true or not.
7104
7105   ‘menu-bar-update-yank-menu’ is one of the functions that make it
7106possible to use the “Select and Paste” menu in the Edit item of a menu
7107bar; using a mouse, you can look at the various pieces of text you have
7108saved and select one piece to paste.
7109
7110   The last expression in the ‘kill-new’ function adds the newly copied
7111string to whatever facility exists for copying and pasting among
7112different programs running in a windowing system.  In the X Windowing
7113system, for example, the ‘x-select-text’ function takes the string and
7114stores it in memory operated by X.  You can paste the string in another
7115program, such as an Xterm.
7116
7117   The expression looks like this:
7118
7119       (if interprogram-cut-function
7120           (funcall interprogram-cut-function string (not replace))))
7121
7122   If an ‘interprogram-cut-function’ exists, then Emacs executes
7123‘funcall’, which in turn calls its first argument as a function and
7124passes the remaining arguments to it.  (Incidentally, as far as I can
7125see, this ‘if’ expression could be replaced by an ‘and’ expression
7126similar to the one in the first part of the function.)
7127
7128   We are not going to discuss windowing systems and other programs
7129further, but merely note that this is a mechanism that enables GNU Emacs
7130to work easily and well with other programs.
7131
7132   This code for placing text in the kill ring, either concatenated with
7133an existing element or as a new element, leads us to the code for
7134bringing back text that has been cut out of the buffer—the yank
7135commands.  However, before discussing the yank commands, it is better to
7136learn how lists are implemented in a computer.  This will make clear
7137such mysteries as the use of the term “pointer”.  But before that, we
7138will digress into C.
7139
7140
7141File: eintr.info,  Node: Digression into C,  Next: defvar,  Prev: copy-region-as-kill,  Up: Cutting & Storing Text
7142
71438.4 Digression into C
7144=====================
7145
7146The ‘copy-region-as-kill’ function (*note ‘copy-region-as-kill’:
7147copy-region-as-kill.) uses the ‘filter-buffer-substring’ function, which
7148in turn uses the ‘delete-and-extract-region’ function.  It removes the
7149contents of a region and you cannot get them back.
7150
7151   Unlike the other code discussed here, the ‘delete-and-extract-region’
7152function is not written in Emacs Lisp; it is written in C and is one of
7153the primitives of the GNU Emacs system.  Since it is very simple, I will
7154digress briefly from Lisp and describe it here.
7155
7156   Like many of the other Emacs primitives, ‘delete-and-extract-region’
7157is written as an instance of a C macro, a macro being a template for
7158code.  The complete macro looks like this:
7159
7160     DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
7161            Sdelete_and_extract_region, 2, 2, 0,
7162            doc: /* Delete the text between START and END and return it.  */)
7163       (Lisp_Object start, Lisp_Object end)
7164     {
7165       validate_region (&start, &end);
7166       if (XFIXNUM (start) == XFIXNUM (end))
7167         return empty_unibyte_string;
7168       return del_range_1 (XFIXNUM (start), XFIXNUM (end), 1, 1);
7169     }
7170
7171   Without going into the details of the macro writing process, let me
7172point out that this macro starts with the word ‘DEFUN’.  The word
7173‘DEFUN’ was chosen since the code serves the same purpose as ‘defun’
7174does in Lisp.  (The ‘DEFUN’ C macro is defined in ‘emacs/src/lisp.h’.)
7175
7176   The word ‘DEFUN’ is followed by seven parts inside of parentheses:
7177
7178   • The first part is the name given to the function in Lisp,
7179     ‘delete-and-extract-region’.
7180
7181   • The second part is the name of the function in C,
7182     ‘Fdelete_and_extract_region’.  By convention, it starts with ‘F’.
7183     Since C does not use hyphens in names, underscores are used
7184     instead.
7185
7186   • The third part is the name for the C constant structure that
7187     records information on this function for internal use.  It is the
7188     name of the function in C but begins with an ‘S’ instead of an ‘F’.
7189
7190   • The fourth and fifth parts specify the minimum and maximum number
7191     of arguments the function can have.  This function demands exactly
7192     2 arguments.
7193
7194   • The sixth part is nearly like the argument that follows the
7195     ‘interactive’ declaration in a function written in Lisp: a letter
7196     followed, perhaps, by a prompt.  The only difference from Lisp is
7197     when the macro is called with no arguments.  Then you write a ‘0’
7198     (which is a null string), as in this macro.
7199
7200     If you were to specify arguments, you would place them between
7201     quotation marks.  The C macro for ‘goto-char’ includes ‘"NGoto
7202     char: "’ in this position to indicate that the function expects a
7203     raw prefix, in this case, a numerical location in a buffer, and
7204     provides a prompt.
7205
7206   • The seventh part is a documentation string, just like the one for a
7207     function written in Emacs Lisp.  This is written as a C comment.
7208     (When you build Emacs, the program ‘lib-src/make-docfile’ extracts
7209     these comments and uses them to make the documentation.)
7210
7211   In a C macro, the formal parameters come next, with a statement of
7212what kind of object they are, followed by the body of the macro.  For
7213‘delete-and-extract-region’ the body consists of the following four
7214lines:
7215
7216     validate_region (&start, &end);
7217     if (XFIXNUM (start) == XFIXNUM (end))
7218       return empty_unibyte_string;
7219     return del_range_1 (XFIXNUM (start), XFIXNUM (end), 1, 1);
7220
7221   The ‘validate_region’ function checks whether the values passed as
7222the beginning and end of the region are the proper type and are within
7223range.  If the beginning and end positions are the same, then return an
7224empty string.
7225
7226   The ‘del_range_1’ function actually deletes the text.  It is a
7227complex function we will not look into.  It updates the buffer and does
7228other things.  However, it is worth looking at the two arguments passed
7229to ‘del_range_1’.  These are ‘XFIXNUM (start)’ and ‘XFIXNUM (end)’.
7230
7231   As far as the C language is concerned, ‘start’ and ‘end’ are two
7232opaque values that mark the beginning and end of the region to be
7233deleted.  More precisely, and requiring more expert knowledge to
7234understand, the two values are of type ‘Lisp_Object’, which might be a C
7235pointer, a C integer, or a C ‘struct’; C code ordinarily should not care
7236how ‘Lisp_Object’ is implemented.
7237
7238   ‘Lisp_Object’ widths depend on the machine, and are typically 32 or
723964 bits.  A few of the bits are used to specify the type of information;
7240the remaining bits are used as content.
7241
7242   ‘XFIXNUM’ is a C macro that extracts the relevant integer from the
7243longer collection of bits; the type bits are discarded.
7244
7245   The command in ‘delete-and-extract-region’ looks like this:
7246
7247     del_range_1 (XFIXNUM (start), XFIXNUM (end), 1, 1);
7248
7249It deletes the region between the beginning position, ‘start’, and the
7250ending position, ‘end’.
7251
7252   From the point of view of the person writing Lisp, Emacs is all very
7253simple; but hidden underneath is a great deal of complexity to make it
7254all work.
7255
7256
7257File: eintr.info,  Node: defvar,  Next: cons & search-fwd Review,  Prev: Digression into C,  Up: Cutting & Storing Text
7258
72598.5 Initializing a Variable with ‘defvar’
7260=========================================
7261
7262The ‘copy-region-as-kill’ function is written in Emacs Lisp.  Two
7263functions within it, ‘kill-append’ and ‘kill-new’, copy a region in a
7264buffer and save it in a variable called the ‘kill-ring’.  This section
7265describes how the ‘kill-ring’ variable is created and initialized using
7266the ‘defvar’ special form.
7267
7268   (Again we note that the term ‘kill-ring’ is a misnomer.  The text
7269that is clipped out of the buffer can be brought back; it is not a ring
7270of corpses, but a ring of resurrectable text.)
7271
7272   In Emacs Lisp, a variable such as the ‘kill-ring’ is created and
7273given an initial value by using the ‘defvar’ special form.  The name
7274comes from “define variable”.
7275
7276   The ‘defvar’ special form is similar to ‘setq’ in that it sets the
7277value of a variable.  It is unlike ‘setq’ in two ways: first, it only
7278sets the value of the variable if the variable does not already have a
7279value.  If the variable already has a value, ‘defvar’ does not override
7280the existing value.  Second, ‘defvar’ has a documentation string.
7281
7282   (There is a related macro, ‘defcustom’, designed for variables that
7283people customize.  It has more features than ‘defvar’.  (*Note Setting
7284Variables with ‘defcustom’: defcustom.)
7285
7286* Menu:
7287
7288* See variable current value::
7289* defvar and asterisk::
7290
7291
7292File: eintr.info,  Node: See variable current value,  Next: defvar and asterisk,  Up: defvar
7293
7294Seeing the Current Value of a Variable
7295--------------------------------------
7296
7297You can see the current value of a variable, any variable, by using the
7298‘describe-variable’ function, which is usually invoked by typing ‘C-h
7299v’.  If you type ‘C-h v’ and then ‘kill-ring’ (followed by <RET>) when
7300prompted, you will see what is in your current kill ring—this may be
7301quite a lot!  Conversely, if you have been doing nothing this Emacs
7302session except read this document, you may have nothing in it.  Also,
7303you will see the documentation for ‘kill-ring’:
7304
7305     Documentation:
7306     List of killed text sequences.
7307     Since the kill ring is supposed to interact nicely with cut-and-paste
7308     facilities offered by window systems, use of this variable should
7309     interact nicely with `interprogram-cut-function' and
7310     `interprogram-paste-function'.  The functions `kill-new',
7311     `kill-append', and `current-kill' are supposed to implement this
7312     interaction; you may want to use them instead of manipulating the kill
7313     ring directly.
7314
7315   The kill ring is defined by a ‘defvar’ in the following way:
7316
7317     (defvar kill-ring nil
7318       "List of killed text sequences.
7319     ...")
7320
7321In this variable definition, the variable is given an initial value of
7322‘nil’, which makes sense, since if you have saved nothing, you want
7323nothing back if you give a ‘yank’ command.  The documentation string is
7324written just like the documentation string of a ‘defun’.  As with the
7325documentation string of the ‘defun’, the first line of the documentation
7326should be a complete sentence, since some commands, like ‘apropos’,
7327print only the first line of documentation.  Succeeding lines should not
7328be indented; otherwise they look odd when you use ‘C-h v’
7329(‘describe-variable’).
7330
7331
7332File: eintr.info,  Node: defvar and asterisk,  Prev: See variable current value,  Up: defvar
7333
73348.5.1 ‘defvar’ and an asterisk
7335------------------------------
7336
7337In the past, Emacs used the ‘defvar’ special form both for internal
7338variables that you would not expect a user to change and for variables
7339that you do expect a user to change.  Although you can still use
7340‘defvar’ for user customizable variables, please use ‘defcustom’
7341instead, since it provides a path into the Customization commands.
7342(*Note Specifying Variables using ‘defcustom’: defcustom.)
7343
7344   When you specified a variable using the ‘defvar’ special form, you
7345could distinguish a variable that a user might want to change from
7346others by typing an asterisk, ‘*’, in the first column of its
7347documentation string.  For example:
7348
7349     (defvar shell-command-default-error-buffer nil
7350       "*Buffer name for `shell-command' ... error output.
7351     ... ")
7352
7353You could (and still can) use the ‘set-variable’ command to change the
7354value of ‘shell-command-default-error-buffer’ temporarily.  However,
7355options set using ‘set-variable’ are set only for the duration of your
7356editing session.  The new values are not saved between sessions.  Each
7357time Emacs starts, it reads the original value, unless you change the
7358value within your ‘.emacs’ file, either by setting it manually or by
7359using ‘customize’.  *Note Your ‘.emacs’ File: Emacs Initialization.
7360
7361   For me, the major use of the ‘set-variable’ command is to suggest
7362variables that I might want to set in my ‘.emacs’ file.  There are now
7363more than 700 such variables, far too many to remember readily.
7364Fortunately, you can press <TAB> after calling the ‘M-x set-variable’
7365command to see the list of variables.  (*Note Examining and Setting
7366Variables: (emacs)Examining.)
7367
7368
7369File: eintr.info,  Node: cons & search-fwd Review,  Next: search Exercises,  Prev: defvar,  Up: Cutting & Storing Text
7370
73718.6 Review
7372==========
7373
7374Here is a brief summary of some recently introduced functions.
7375
7376‘car’
7377‘cdr’
7378     ‘car’ returns the first element of a list; ‘cdr’ returns the second
7379     and subsequent elements of a list.
7380
7381     For example:
7382
7383          (car '(1 2 3 4 5 6 7))
7384               ⇒ 1
7385          (cdr '(1 2 3 4 5 6 7))
7386               ⇒ (2 3 4 5 6 7)
7387
7388‘cons’
7389     ‘cons’ constructs a list by prepending its first argument to its
7390     second argument.
7391
7392     For example:
7393
7394          (cons 1 '(2 3 4))
7395               ⇒ (1 2 3 4)
7396
7397‘funcall’
7398     ‘funcall’ evaluates its first argument as a function.  It passes
7399     its remaining arguments to its first argument.
7400
7401‘nthcdr’
7402     Return the result of taking CDR N times on a list.  The “rest of
7403     the rest”, as it were.
7404
7405     For example:
7406
7407          (nthcdr 3 '(1 2 3 4 5 6 7))
7408               ⇒ (4 5 6 7)
7409
7410‘setcar’
7411‘setcdr’
7412     ‘setcar’ changes the first element of a list; ‘setcdr’ changes the
7413     second and subsequent elements of a list.
7414
7415     For example:
7416
7417          (setq triple (list 1 2 3))
7418
7419          (setcar triple '37)
7420
7421          triple
7422               ⇒ (37 2 3)
7423
7424          (setcdr triple '("foo" "bar"))
7425
7426          triple
7427               ⇒ (37 "foo" "bar")
7428
7429‘progn’
7430     Evaluate each argument in sequence and then return the value of the
7431     last.
7432
7433     For example:
7434
7435          (progn 1 2 3 4)
7436               ⇒ 4
7437
7438‘save-restriction’
7439     Record whatever narrowing is in effect in the current buffer, if
7440     any, and restore that narrowing after evaluating the arguments.
7441
7442‘search-forward’
7443     Search for a string, and if the string is found, move point.  With
7444     a regular expression, use the similar ‘re-search-forward’.  (*Note
7445     Regular Expression Searches: Regexp Search, for an explanation of
7446     regular expression patterns and searches.)
7447
7448     ‘search-forward’ and ‘re-search-forward’ take four arguments:
7449
7450       1. The string or regular expression to search for.
7451
7452       2. Optionally, the limit of the search.
7453
7454       3. Optionally, what to do if the search fails, return ‘nil’ or an
7455          error message.
7456
7457       4. Optionally, how many times to repeat the search; if negative,
7458          the search goes backwards.
7459
7460‘kill-region’
7461‘delete-and-extract-region’
7462‘copy-region-as-kill’
7463
7464     ‘kill-region’ cuts the text between point and mark from the buffer
7465     and stores that text in the kill ring, so you can get it back by
7466     yanking.
7467
7468     ‘copy-region-as-kill’ copies the text between point and mark into
7469     the kill ring, from which you can get it by yanking.  The function
7470     does not cut or remove the text from the buffer.
7471
7472   ‘delete-and-extract-region’ removes the text between point and mark
7473from the buffer and throws it away.  You cannot get it back.  (This is
7474not an interactive command.)
7475
7476
7477File: eintr.info,  Node: search Exercises,  Prev: cons & search-fwd Review,  Up: Cutting & Storing Text
7478
74798.7 Searching Exercises
7480=======================
7481
7482   • Write an interactive function that searches for a string.  If the
7483     search finds the string, leave point after it and display a message
7484     that says “Found!”.  (Do not use ‘search-forward’ for the name of
7485     this function; if you do, you will overwrite the existing version
7486     of ‘search-forward’ that comes with Emacs.  Use a name such as
7487     ‘test-search’ instead.)
7488
7489   • Write a function that prints the third element of the kill ring in
7490     the echo area, if any; if the kill ring does not contain a third
7491     element, print an appropriate message.
7492
7493
7494File: eintr.info,  Node: List Implementation,  Next: Yanking,  Prev: Cutting & Storing Text,  Up: Top
7495
74969 How Lists are Implemented
7497***************************
7498
7499In Lisp, atoms are recorded in a straightforward fashion; if the
7500implementation is not straightforward in practice, it is, nonetheless,
7501straightforward in theory.  The atom ‘rose’, for example, is recorded as
7502the four contiguous letters ‘r’, ‘o’, ‘s’, ‘e’.  A list, on the other
7503hand, is kept differently.  The mechanism is equally simple, but it
7504takes a moment to get used to the idea.  A list is kept using a series
7505of pairs of pointers.  In the series, the first pointer in each pair
7506points to an atom or to another list, and the second pointer in each
7507pair points to the next pair, or to the symbol ‘nil’, which marks the
7508end of the list.
7509
7510   A pointer itself is quite simply the electronic address of what is
7511pointed to.  Hence, a list is kept as a series of electronic addresses.
7512
7513* Menu:
7514
7515* Lists diagrammed::
7516* Symbols as Chest::            Exploring a powerful metaphor.
7517* List Exercise::
7518
7519
7520File: eintr.info,  Node: Lists diagrammed,  Next: Symbols as Chest,  Up: List Implementation
7521
7522Lists diagrammed
7523================
7524
7525For example, the list ‘(rose violet buttercup)’ has three elements,
7526‘rose’, ‘violet’, and ‘buttercup’.  In the computer, the electronic
7527address of ‘rose’ is recorded in a segment of computer memory along with
7528the address that gives the electronic address of where the atom ‘violet’
7529is located; and that address (the one that tells where ‘violet’ is
7530located) is kept along with an address that tells where the address for
7531the atom ‘buttercup’ is located.
7532
7533   This sounds more complicated than it is and is easier seen in a
7534diagram:
7535
7536         ___ ___      ___ ___      ___ ___
7537        |___|___|--> |___|___|--> |___|___|--> nil
7538          |            |            |
7539          |            |            |
7540           --> rose     --> violet   --> buttercup
7541
7542
7543In the diagram, each box represents a word of computer memory that holds
7544a Lisp object, usually in the form of a memory address.  The boxes,
7545i.e., the addresses, are in pairs.  Each arrow points to what the
7546address is the address of, either an atom or another pair of addresses.
7547The first box is the electronic address of ‘rose’ and the arrow points
7548to ‘rose’; the second box is the address of the next pair of boxes, the
7549first part of which is the address of ‘violet’ and the second part of
7550which is the address of the next pair.  The very last box points to the
7551symbol ‘nil’, which marks the end of the list.
7552
7553   When a variable is set to a list with an operation such as ‘setq’, it
7554stores the address of the first box in the variable.  Thus, evaluation
7555of the expression
7556
7557     (setq bouquet '(rose violet buttercup))
7558
7559creates a situation like this:
7560
7561     bouquet
7562          |
7563          |     ___ ___      ___ ___      ___ ___
7564           --> |___|___|--> |___|___|--> |___|___|--> nil
7565                 |            |            |
7566                 |            |            |
7567                  --> rose     --> violet   --> buttercup
7568
7569
7570In this example, the symbol ‘bouquet’ holds the address of the first
7571pair of boxes.
7572
7573   This same list can be illustrated in a different sort of box notation
7574like this:
7575
7576     bouquet
7577      |
7578      |    --------------       ---------------       ----------------
7579      |   | car   | cdr  |     | car    | cdr  |     | car     | cdr  |
7580       -->| rose  |   o------->| violet |   o------->| butter- |  nil |
7581          |       |      |     |        |      |     | cup     |      |
7582           --------------       ---------------       ----------------
7583
7584
7585   (Symbols consist of more than pairs of addresses, but the structure
7586of a symbol is made up of addresses.  Indeed, the symbol ‘bouquet’
7587consists of a group of address-boxes, one of which is the address of the
7588printed word ‘bouquet’, a second of which is the address of a function
7589definition attached to the symbol, if any, a third of which is the
7590address of the first pair of address-boxes for the list ‘(rose violet
7591buttercup)’, and so on.  Here we are showing that the symbol’s third
7592address-box points to the first pair of address-boxes for the list.)
7593
7594   If a symbol is set to the CDR of a list, the list itself is not
7595changed; the symbol simply has an address further down the list.  (In
7596the jargon, CAR and CDR are “non-destructive”.)  Thus, evaluation of the
7597following expression
7598
7599     (setq flowers (cdr bouquet))
7600
7601produces this:
7602
7603
7604     bouquet        flowers
7605       |              |
7606       |     ___ ___  |     ___ ___      ___ ___
7607        --> |   |   |  --> |   |   |    |   |   |
7608            |___|___|----> |___|___|--> |___|___|--> nil
7609              |              |            |
7610              |              |            |
7611               --> rose       --> violet   --> buttercup
7612
7613
7614
7615The value of ‘flowers’ is ‘(violet buttercup)’, which is to say, the
7616symbol ‘flowers’ holds the address of the pair of address-boxes, the
7617first of which holds the address of ‘violet’, and the second of which
7618holds the address of ‘buttercup’.
7619
7620   A pair of address-boxes is called a “cons cell” or “dotted pair”.
7621*Note Cons Cell and List Types: (elisp)Cons Cell Type, and *note Dotted
7622Pair Notation: (elisp)Dotted Pair Notation, for more information about
7623cons cells and dotted pairs.
7624
7625   The function ‘cons’ adds a new pair of addresses to the front of a
7626series of addresses like that shown above.  For example, evaluating the
7627expression
7628
7629     (setq bouquet (cons 'lily bouquet))
7630
7631produces:
7632
7633
7634     bouquet                       flowers
7635       |                             |
7636       |     ___ ___        ___ ___  |     ___ ___       ___ ___
7637        --> |   |   |      |   |   |  --> |   |   |     |   |   |
7638            |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
7639              |              |              |             |
7640              |              |              |             |
7641               --> lily      --> rose       --> violet    --> buttercup
7642
7643
7644
7645However, this does not change the value of the symbol ‘flowers’, as you
7646can see by evaluating the following,
7647
7648     (eq (cdr (cdr bouquet)) flowers)
7649
7650which returns ‘t’ for true.
7651
7652   Until it is reset, ‘flowers’ still has the value ‘(violet
7653buttercup)’; that is, it has the address of the cons cell whose first
7654address is of ‘violet’.  Also, this does not alter any of the
7655pre-existing cons cells; they are all still there.
7656
7657   Thus, in Lisp, to get the CDR of a list, you just get the address of
7658the next cons cell in the series; to get the CAR of a list, you get the
7659address of the first element of the list; to ‘cons’ a new element on a
7660list, you add a new cons cell to the front of the list.  That is all
7661there is to it!  The underlying structure of Lisp is brilliantly simple!
7662
7663   And what does the last address in a series of cons cells refer to?
7664It is the address of the empty list, of ‘nil’.
7665
7666   In summary, when a Lisp variable is set to a value, it is provided
7667with the address of the list to which the variable refers.
7668
7669
7670File: eintr.info,  Node: Symbols as Chest,  Next: List Exercise,  Prev: Lists diagrammed,  Up: List Implementation
7671
76729.1 Symbols as a Chest of Drawers
7673=================================
7674
7675In an earlier section, I suggested that you might imagine a symbol as
7676being a chest of drawers.  The function definition is put in one drawer,
7677the value in another, and so on.  What is put in the drawer holding the
7678value can be changed without affecting the contents of the drawer
7679holding the function definition, and vice versa.
7680
7681   Actually, what is put in each drawer is the address of the value or
7682function definition.  It is as if you found an old chest in the attic,
7683and in one of its drawers you found a map giving you directions to where
7684the buried treasure lies.
7685
7686   (In addition to its name, symbol definition, and variable value, a
7687symbol has a drawer for a “property list” which can be used to record
7688other information.  Property lists are not discussed here; see *note
7689Property Lists: (elisp)Property Lists.)
7690
7691   Here is a fanciful representation:
7692
7693
7694                 Chest of Drawers            Contents of Drawers
7695
7696                 __   o0O0o   __
7697               /                 \
7698              ---------------------
7699             |    directions to    |            [map to]
7700             |     symbol name     |             bouquet
7701             |                     |
7702             +---------------------+
7703             |    directions to    |
7704             |  symbol definition  |             [none]
7705             |                     |
7706             +---------------------+
7707             |    directions to    |            [map to]
7708             |    variable value   |             (rose violet buttercup)
7709             |                     |
7710             +---------------------+
7711             |    directions to    |
7712             |    property list    |             [not described here]
7713             |                     |
7714             +---------------------+
7715             |/                   \|
7716
7717
7718
7719
7720File: eintr.info,  Node: List Exercise,  Prev: Symbols as Chest,  Up: List Implementation
7721
77229.2 Exercise
7723============
7724
7725Set ‘flowers’ to ‘violet’ and ‘buttercup’.  Cons two more flowers on to
7726this list and set this new list to ‘more-flowers’.  Set the CAR of
7727‘flowers’ to a fish.  What does the ‘more-flowers’ list now contain?
7728
7729
7730File: eintr.info,  Node: Yanking,  Next: Loops & Recursion,  Prev: List Implementation,  Up: Top
7731
773210 Yanking Text Back
7733********************
7734
7735Whenever you cut text out of a buffer with a kill command in GNU Emacs,
7736you can bring it back with a yank command.  The text that is cut out of
7737the buffer is put in the kill ring and the yank commands insert the
7738appropriate contents of the kill ring back into a buffer (not
7739necessarily the original buffer).
7740
7741   A simple ‘C-y’ (‘yank’) command inserts the first item from the kill
7742ring into the current buffer.  If the ‘C-y’ command is followed
7743immediately by ‘M-y’, the first element is replaced by the second
7744element.  Successive ‘M-y’ commands replace the second element with the
7745third, fourth, or fifth element, and so on.  When the last element in
7746the kill ring is reached, it is replaced by the first element and the
7747cycle is repeated.  (Thus the kill ring is called a “ring” rather than
7748just a “list”.  However, the actual data structure that holds the text
7749is a list.  *Note Handling the Kill Ring: Kill Ring, for the details of
7750how the list is handled as a ring.)
7751
7752* Menu:
7753
7754* Kill Ring Overview::
7755* kill-ring-yank-pointer::      The kill ring is a list.
7756* yank nthcdr Exercises::       The ‘kill-ring-yank-pointer’ variable.
7757
7758
7759File: eintr.info,  Node: Kill Ring Overview,  Next: kill-ring-yank-pointer,  Up: Yanking
7760
776110.1 Kill Ring Overview
7762=======================
7763
7764The kill ring is a list of textual strings.  This is what it looks like:
7765
7766     ("some text" "a different piece of text" "yet more text")
7767
7768   If this were the contents of my kill ring and I pressed ‘C-y’, the
7769string of characters saying ‘some text’ would be inserted in this buffer
7770where my cursor is located.
7771
7772   The ‘yank’ command is also used for duplicating text by copying it.
7773The copied text is not cut from the buffer, but a copy of it is put on
7774the kill ring and is inserted by yanking it back.
7775
7776   Three functions are used for bringing text back from the kill ring:
7777‘yank’, which is usually bound to ‘C-y’; ‘yank-pop’, which is usually
7778bound to ‘M-y’; and ‘rotate-yank-pointer’, which is used by the two
7779other functions.
7780
7781   These functions refer to the kill ring through a variable called the
7782‘kill-ring-yank-pointer’.  Indeed, the insertion code for both the
7783‘yank’ and ‘yank-pop’ functions is:
7784
7785     (insert (car kill-ring-yank-pointer))
7786
7787(Well, no more.  In GNU Emacs 22, the function has been replaced by
7788‘insert-for-yank’ which calls ‘insert-for-yank-1’ repetitively for each
7789‘yank-handler’ segment.  In turn, ‘insert-for-yank-1’ strips text
7790properties from the inserted text according to
7791‘yank-excluded-properties’.  Otherwise, it is just like ‘insert’.  We
7792will stick with plain ‘insert’ since it is easier to understand.)
7793
7794   To begin to understand how ‘yank’ and ‘yank-pop’ work, it is first
7795necessary to look at the ‘kill-ring-yank-pointer’ variable.
7796
7797
7798File: eintr.info,  Node: kill-ring-yank-pointer,  Next: yank nthcdr Exercises,  Prev: Kill Ring Overview,  Up: Yanking
7799
780010.2 The ‘kill-ring-yank-pointer’ Variable
7801==========================================
7802
7803‘kill-ring-yank-pointer’ is a variable, just as ‘kill-ring’ is a
7804variable.  It points to something by being bound to the value of what it
7805points to, like any other Lisp variable.
7806
7807   Thus, if the value of the kill ring is:
7808
7809     ("some text" "a different piece of text" "yet more text")
7810
7811and the ‘kill-ring-yank-pointer’ points to the second clause, the value
7812of ‘kill-ring-yank-pointer’ is:
7813
7814     ("a different piece of text" "yet more text")
7815
7816   As explained in the previous chapter (*note List Implementation::),
7817the computer does not keep two different copies of the text being
7818pointed to by both the ‘kill-ring’ and the ‘kill-ring-yank-pointer’.
7819The words “a different piece of text” and “yet more text” are not
7820duplicated.  Instead, the two Lisp variables point to the same pieces of
7821text.  Here is a diagram:
7822
7823     kill-ring     kill-ring-yank-pointer
7824         |               |
7825         |      ___ ___  |     ___ ___      ___ ___
7826          ---> |   |   |  --> |   |   |    |   |   |
7827               |___|___|----> |___|___|--> |___|___|--> nil
7828                 |              |            |
7829                 |              |            |
7830                 |              |             --> "yet more text"
7831                 |              |
7832                 |               --> "a different piece of text"
7833                 |
7834                  --> "some text"
7835
7836
7837
7838   Both the variable ‘kill-ring’ and the variable
7839‘kill-ring-yank-pointer’ are pointers.  But the kill ring itself is
7840usually described as if it were actually what it is composed of.  The
7841‘kill-ring’ is spoken of as if it were the list rather than that it
7842points to the list.  Conversely, the ‘kill-ring-yank-pointer’ is spoken
7843of as pointing to a list.
7844
7845   These two ways of talking about the same thing sound confusing at
7846first but make sense on reflection.  The kill ring is generally thought
7847of as the complete structure of data that holds the information of what
7848has recently been cut out of the Emacs buffers.  The
7849‘kill-ring-yank-pointer’ on the other hand, serves to indicate—that is,
7850to point to—that part of the kill ring of which the first element (the
7851CAR) will be inserted.
7852
7853
7854File: eintr.info,  Node: yank nthcdr Exercises,  Prev: kill-ring-yank-pointer,  Up: Yanking
7855
785610.3 Exercises with ‘yank’ and ‘nthcdr’
7857=======================================
7858
7859   • Using ‘C-h v’ (‘describe-variable’), look at the value of your kill
7860     ring.  Add several items to your kill ring; look at its value
7861     again.  Using ‘M-y’ (‘yank-pop)’, move all the way around the kill
7862     ring.  How many items were in your kill ring?  Find the value of
7863     ‘kill-ring-max’.  Was your kill ring full, or could you have kept
7864     more blocks of text within it?
7865
7866   • Using ‘nthcdr’ and ‘car’, construct a series of expressions to
7867     return the first, second, third, and fourth elements of a list.
7868
7869
7870File: eintr.info,  Node: Loops & Recursion,  Next: Regexp Search,  Prev: Yanking,  Up: Top
7871
787211 Loops and Recursion
7873**********************
7874
7875Emacs Lisp has two primary ways to cause an expression, or a series of
7876expressions, to be evaluated repeatedly: one uses a ‘while’ loop, and
7877the other uses “recursion”.
7878
7879   Repetition can be very valuable.  For example, to move forward four
7880sentences, you need only write a program that will move forward one
7881sentence and then repeat the process four times.  Since a computer does
7882not get bored or tired, such repetitive action does not have the
7883deleterious effects that excessive or the wrong kinds of repetition can
7884have on humans.
7885
7886   People mostly write Emacs Lisp functions using ‘while’ loops and
7887their kin; but you can use recursion, which provides a very powerful way
7888to think about and then to solve problems(1).
7889
7890* Menu:
7891
7892* while::                       Causing a stretch of code to repeat.
7893* dolist dotimes::
7894* Recursion::                   Causing a function to call itself.
7895* Looping exercise::
7896
7897   ---------- Footnotes ----------
7898
7899   (1) You can write recursive functions to be frugal or wasteful of
7900mental or computer resources; as it happens, methods that people find
7901easy—that are frugal of mental resources—sometimes use considerable
7902computer resources.  Emacs was designed to run on machines that we now
7903consider limited and its default settings are conservative.  You may
7904want to increase the values of ‘max-specpdl-size’ and
7905‘max-lisp-eval-depth’.  In my ‘.emacs’ file, I set them to 15 and 30
7906times their default value.
7907
7908
7909File: eintr.info,  Node: while,  Next: dolist dotimes,  Up: Loops & Recursion
7910
791111.1 ‘while’
7912============
7913
7914The ‘while’ special form tests whether the value returned by evaluating
7915its first argument is true or false.  This is similar to what the Lisp
7916interpreter does with an ‘if’; what the interpreter does next, however,
7917is different.
7918
7919   In a ‘while’ expression, if the value returned by evaluating the
7920first argument is false, the Lisp interpreter skips the rest of the
7921expression (the “body” of the expression) and does not evaluate it.
7922However, if the value is true, the Lisp interpreter evaluates the body
7923of the expression and then again tests whether the first argument to
7924‘while’ is true or false.  If the value returned by evaluating the first
7925argument is again true, the Lisp interpreter again evaluates the body of
7926the expression.
7927
7928   The template for a ‘while’ expression looks like this:
7929
7930     (while TRUE-OR-FALSE-TEST
7931       BODY...)
7932
7933* Menu:
7934
7935* Looping with while::          Repeat so long as test returns true.
7936* Loop Example::                A ‘while’ loop that uses a list.
7937* print-elements-of-list::      Uses ‘while’, ‘car’, ‘cdr’.
7938* Incrementing Loop::           A loop with an incrementing counter.
7939* Incrementing Loop Details::
7940* Decrementing Loop::           A loop with a decrementing counter.
7941
7942
7943File: eintr.info,  Node: Looping with while,  Next: Loop Example,  Up: while
7944
7945Looping with ‘while’
7946--------------------
7947
7948So long as the true-or-false-test of the ‘while’ expression returns a
7949true value when it is evaluated, the body is repeatedly evaluated.  This
7950process is called a loop since the Lisp interpreter repeats the same
7951thing again and again, like an airplane doing a loop.  When the result
7952of evaluating the true-or-false-test is false, the Lisp interpreter does
7953not evaluate the rest of the ‘while’ expression and exits the loop.
7954
7955   Clearly, if the value returned by evaluating the first argument to
7956‘while’ is always true, the body following will be evaluated again and
7957again ... and again ... forever.  Conversely, if the value returned is
7958never true, the expressions in the body will never be evaluated.  The
7959craft of writing a ‘while’ loop consists of choosing a mechanism such
7960that the true-or-false-test returns true just the number of times that
7961you want the subsequent expressions to be evaluated, and then have the
7962test return false.
7963
7964   The value returned by evaluating a ‘while’ is the value of the
7965true-or-false-test.  An interesting consequence of this is that a
7966‘while’ loop that evaluates without error will return ‘nil’ or false
7967regardless of whether it has looped 1 or 100 times or none at all.  A
7968‘while’ expression that evaluates successfully never returns a true
7969value!  What this means is that ‘while’ is always evaluated for its side
7970effects, which is to say, the consequences of evaluating the expressions
7971within the body of the ‘while’ loop.  This makes sense.  It is not the
7972mere act of looping that is desired, but the consequences of what
7973happens when the expressions in the loop are repeatedly evaluated.
7974
7975
7976File: eintr.info,  Node: Loop Example,  Next: print-elements-of-list,  Prev: Looping with while,  Up: while
7977
797811.1.1 A ‘while’ Loop and a List
7979--------------------------------
7980
7981A common way to control a ‘while’ loop is to test whether a list has any
7982elements.  If it does, the loop is repeated; but if it does not, the
7983repetition is ended.  Since this is an important technique, we will
7984create a short example to illustrate it.
7985
7986   A simple way to test whether a list has elements is to evaluate the
7987list: if it has no elements, it is an empty list and will return the
7988empty list, ‘()’, which is a synonym for ‘nil’ or false.  On the other
7989hand, a list with elements will return those elements when it is
7990evaluated.  Since Emacs Lisp considers as true any value that is not
7991‘nil’, a list that returns elements will test true in a ‘while’ loop.
7992
7993   For example, you can set the variable ‘empty-list’ to ‘nil’ by
7994evaluating the following ‘setq’ expression:
7995
7996     (setq empty-list ())
7997
7998After evaluating the ‘setq’ expression, you can evaluate the variable
7999‘empty-list’ in the usual way, by placing the cursor after the symbol
8000and typing ‘C-x C-e’; ‘nil’ will appear in your echo area:
8001
8002     empty-list
8003
8004   On the other hand, if you set a variable to be a list with elements,
8005the list will appear when you evaluate the variable, as you can see by
8006evaluating the following two expressions:
8007
8008     (setq animals '(gazelle giraffe lion tiger))
8009
8010     animals
8011
8012   Thus, to create a ‘while’ loop that tests whether there are any items
8013in the list ‘animals’, the first part of the loop will be written like
8014this:
8015
8016     (while animals
8017            ...
8018
8019When the ‘while’ tests its first argument, the variable ‘animals’ is
8020evaluated.  It returns a list.  So long as the list has elements, the
8021‘while’ considers the results of the test to be true; but when the list
8022is empty, it considers the results of the test to be false.
8023
8024   To prevent the ‘while’ loop from running forever, some mechanism
8025needs to be provided to empty the list eventually.  An oft-used
8026technique is to have one of the subsequent forms in the ‘while’
8027expression set the value of the list to be the CDR of the list.  Each
8028time the ‘cdr’ function is evaluated, the list will be made shorter,
8029until eventually only the empty list will be left.  At this point, the
8030test of the ‘while’ loop will return false, and the arguments to the
8031‘while’ will no longer be evaluated.
8032
8033   For example, the list of animals bound to the variable ‘animals’ can
8034be set to be the CDR of the original list with the following expression:
8035
8036     (setq animals (cdr animals))
8037
8038If you have evaluated the previous expressions and then evaluate this
8039expression, you will see ‘(giraffe lion tiger)’ appear in the echo area.
8040If you evaluate the expression again, ‘(lion tiger)’ will appear in the
8041echo area.  If you evaluate it again and yet again, ‘(tiger)’ appears
8042and then the empty list, shown by ‘nil’.
8043
8044   A template for a ‘while’ loop that uses the ‘cdr’ function repeatedly
8045to cause the true-or-false-test eventually to test false looks like
8046this:
8047
8048     (while TEST-WHETHER-LIST-IS-EMPTY
8049       BODY...
8050       SET-LIST-TO-CDR-OF-LIST)
8051
8052   This test and use of ‘cdr’ can be put together in a function that
8053goes through a list and prints each element of the list on a line of its
8054own.
8055
8056
8057File: eintr.info,  Node: print-elements-of-list,  Next: Incrementing Loop,  Prev: Loop Example,  Up: while
8058
805911.1.2 An Example: ‘print-elements-of-list’
8060-------------------------------------------
8061
8062The ‘print-elements-of-list’ function illustrates a ‘while’ loop with a
8063list.
8064
8065   The function requires several lines for its output.  If you are
8066reading this in a recent instance of GNU Emacs, you can evaluate the
8067following expression inside of Info, as usual.
8068
8069   If you are using an earlier version of Emacs, you need to copy the
8070necessary expressions to your ‘*scratch*’ buffer and evaluate them
8071there.  This is because the echo area had only one line in the earlier
8072versions.
8073
8074   You can copy the expressions by marking the beginning of the region
8075with ‘C-<SPC>’ (‘set-mark-command’), moving the cursor to the end of the
8076region and then copying the region using ‘M-w’ (‘kill-ring-save’, which
8077calls ‘copy-region-as-kill’ and then provides visual feedback).  In the
8078‘*scratch*’ buffer, you can yank the expressions back by typing ‘C-y’
8079(‘yank’).
8080
8081   After you have copied the expressions to the ‘*scratch*’ buffer,
8082evaluate each expression in turn.  Be sure to evaluate the last
8083expression, ‘(print-elements-of-list animals)’, by typing ‘C-u C-x C-e’,
8084that is, by giving an argument to ‘eval-last-sexp’.  This will cause the
8085result of the evaluation to be printed in the ‘*scratch*’ buffer instead
8086of being printed in the echo area.  (Otherwise you will see something
8087like this in your echo area:
8088‘^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil’, in which each ‘^J’ stands
8089for a newline.)
8090
8091   In a recent instance of GNU Emacs, you can evaluate these expressions
8092directly in the Info buffer, and the echo area will grow to show the
8093results.
8094
8095     (setq animals '(gazelle giraffe lion tiger))
8096
8097     (defun print-elements-of-list (list)
8098       "Print each element of LIST on a line of its own."
8099       (while list
8100         (print (car list))
8101         (setq list (cdr list))))
8102
8103     (print-elements-of-list animals)
8104
8105When you evaluate the three expressions in sequence, you will see this:
8106
8107     gazelle
8108
8109     giraffe
8110
8111     lion
8112
8113     tiger
8114     nil
8115
8116   Each element of the list is printed on a line of its own (that is
8117what the function ‘print’ does) and then the value returned by the
8118function is printed.  Since the last expression in the function is the
8119‘while’ loop, and since ‘while’ loops always return ‘nil’, a ‘nil’ is
8120printed after the last element of the list.
8121
8122
8123File: eintr.info,  Node: Incrementing Loop,  Next: Incrementing Loop Details,  Prev: print-elements-of-list,  Up: while
8124
812511.1.3 A Loop with an Incrementing Counter
8126------------------------------------------
8127
8128A loop is not useful unless it stops when it ought.  Besides controlling
8129a loop with a list, a common way of stopping a loop is to write the
8130first argument as a test that returns false when the correct number of
8131repetitions are complete.  This means that the loop must have a
8132counter—an expression that counts how many times the loop repeats
8133itself.
8134
8135
8136File: eintr.info,  Node: Incrementing Loop Details,  Next: Decrementing Loop,  Prev: Incrementing Loop,  Up: while
8137
8138Details of an Incrementing Loop
8139-------------------------------
8140
8141The test for a loop with an incrementing counter can be an expression
8142such as ‘(< count desired-number)’ which returns ‘t’ for true if the
8143value of ‘count’ is less than the ‘desired-number’ of repetitions and
8144‘nil’ for false if the value of ‘count’ is equal to or is greater than
8145the ‘desired-number’.  The expression that increments the count can be a
8146simple ‘setq’ such as ‘(setq count (1+ count))’, where ‘1+’ is a
8147built-in function in Emacs Lisp that adds 1 to its argument.  (The
8148expression ‘(1+ count)’ has the same result as ‘(+ count 1)’, but is
8149easier for a human to read.)
8150
8151   The template for a ‘while’ loop controlled by an incrementing counter
8152looks like this:
8153
8154     SET-COUNT-TO-INITIAL-VALUE
8155     (while (< count desired-number)         ; true-or-false-test
8156       BODY...
8157       (setq count (1+ count)))              ; incrementer
8158
8159Note that you need to set the initial value of ‘count’; usually it is
8160set to 1.
8161
8162* Menu:
8163
8164* Incrementing Example::        Counting pebbles in a triangle.
8165* Inc Example parts::           The parts of the function definition.
8166* Inc Example altogether::      Putting the function definition together.
8167
8168
8169File: eintr.info,  Node: Incrementing Example,  Next: Inc Example parts,  Up: Incrementing Loop Details
8170
8171Example with incrementing counter
8172.................................
8173
8174Suppose you are playing on the beach and decide to make a triangle of
8175pebbles, putting one pebble in the first row, two in the second row,
8176three in the third row and so on, like this:
8177
8178
8179                    *
8180                   * *
8181                  * * *
8182                 * * * *
8183
8184(About 2500 years ago, Pythagoras and others developed the beginnings of
8185number theory by considering questions such as this.)
8186
8187   Suppose you want to know how many pebbles you will need to make a
8188triangle with 7 rows?
8189
8190   Clearly, what you need to do is add up the numbers from 1 to 7.
8191There are two ways to do this; start with the smallest number, one, and
8192add up the list in sequence, 1, 2, 3, 4 and so on; or start with the
8193largest number and add the list going down: 7, 6, 5, 4 and so on.
8194Because both mechanisms illustrate common ways of writing ‘while’ loops,
8195we will create two examples, one counting up and the other counting
8196down.  In this first example, we will start with 1 and add 2, 3, 4 and
8197so on.
8198
8199   If you are just adding up a short list of numbers, the easiest way to
8200do it is to add up all the numbers at once.  However, if you do not know
8201ahead of time how many numbers your list will have, or if you want to be
8202prepared for a very long list, then you need to design your addition so
8203that what you do is repeat a simple process many times instead of doing
8204a more complex process once.
8205
8206   For example, instead of adding up all the pebbles all at once, what
8207you can do is add the number of pebbles in the first row, 1, to the
8208number in the second row, 2, and then add the total of those two rows to
8209the third row, 3.  Then you can add the number in the fourth row, 4, to
8210the total of the first three rows; and so on.
8211
8212   The critical characteristic of the process is that each repetitive
8213action is simple.  In this case, at each step we add only two numbers,
8214the number of pebbles in the row and the total already found.  This
8215process of adding two numbers is repeated again and again until the last
8216row has been added to the total of all the preceding rows.  In a more
8217complex loop the repetitive action might not be so simple, but it will
8218be simpler than doing everything all at once.
8219
8220
8221File: eintr.info,  Node: Inc Example parts,  Next: Inc Example altogether,  Prev: Incrementing Example,  Up: Incrementing Loop Details
8222
8223The parts of the function definition
8224....................................
8225
8226The preceding analysis gives us the bones of our function definition:
8227first, we will need a variable that we can call ‘total’ that will be the
8228total number of pebbles.  This will be the value returned by the
8229function.
8230
8231   Second, we know that the function will require an argument: this
8232argument will be the total number of rows in the triangle.  It can be
8233called ‘number-of-rows’.
8234
8235   Finally, we need a variable to use as a counter.  We could call this
8236variable ‘counter’, but a better name is ‘row-number’.  That is because
8237what the counter does in this function is count rows, and a program
8238should be written to be as understandable as possible.
8239
8240   When the Lisp interpreter first starts evaluating the expressions in
8241the function, the value of ‘total’ should be set to zero, since we have
8242not added anything to it.  Then the function should add the number of
8243pebbles in the first row to the total, and then add the number of
8244pebbles in the second to the total, and then add the number of pebbles
8245in the third row to the total, and so on, until there are no more rows
8246left to add.
8247
8248   Both ‘total’ and ‘row-number’ are used only inside the function, so
8249they can be declared as local variables with ‘let’ and given initial
8250values.  Clearly, the initial value for ‘total’ should be 0.  The
8251initial value of ‘row-number’ should be 1, since we start with the first
8252row.  This means that the ‘let’ statement will look like this:
8253
8254       (let ((total 0)
8255             (row-number 1))
8256         BODY...)
8257
8258   After the internal variables are declared and bound to their initial
8259values, we can begin the ‘while’ loop.  The expression that serves as
8260the test should return a value of ‘t’ for true so long as the
8261‘row-number’ is less than or equal to the ‘number-of-rows’.  (If the
8262expression tests true only so long as the row number is less than the
8263number of rows in the triangle, the last row will never be added to the
8264total; hence the row number has to be either less than or equal to the
8265number of rows.)
8266
8267   Lisp provides the ‘<=’ function that returns true if the value of its
8268first argument is less than or equal to the value of its second argument
8269and false otherwise.  So the expression that the ‘while’ will evaluate
8270as its test should look like this:
8271
8272     (<= row-number number-of-rows)
8273
8274   The total number of pebbles can be found by repeatedly adding the
8275number of pebbles in a row to the total already found.  Since the number
8276of pebbles in the row is equal to the row number, the total can be found
8277by adding the row number to the total.  (Clearly, in a more complex
8278situation, the number of pebbles in the row might be related to the row
8279number in a more complicated way; if this were the case, the row number
8280would be replaced by the appropriate expression.)
8281
8282     (setq total (+ total row-number))
8283
8284What this does is set the new value of ‘total’ to be equal to the sum of
8285adding the number of pebbles in the row to the previous total.
8286
8287   After setting the value of ‘total’, the conditions need to be
8288established for the next repetition of the loop, if there is one.  This
8289is done by incrementing the value of the ‘row-number’ variable, which
8290serves as a counter.  After the ‘row-number’ variable has been
8291incremented, the true-or-false-test at the beginning of the ‘while’ loop
8292tests whether its value is still less than or equal to the value of the
8293‘number-of-rows’ and if it is, adds the new value of the ‘row-number’
8294variable to the ‘total’ of the previous repetition of the loop.
8295
8296   The built-in Emacs Lisp function ‘1+’ adds 1 to a number, so the
8297‘row-number’ variable can be incremented with this expression:
8298
8299     (setq row-number (1+ row-number))
8300
8301
8302File: eintr.info,  Node: Inc Example altogether,  Prev: Inc Example parts,  Up: Incrementing Loop Details
8303
8304Putting the function definition together
8305........................................
8306
8307We have created the parts for the function definition; now we need to
8308put them together.
8309
8310   First, the contents of the ‘while’ expression:
8311
8312     (while (<= row-number number-of-rows)   ; true-or-false-test
8313       (setq total (+ total row-number))
8314       (setq row-number (1+ row-number)))    ; incrementer
8315
8316   Along with the ‘let’ expression varlist, this very nearly completes
8317the body of the function definition.  However, it requires one final
8318element, the need for which is somewhat subtle.
8319
8320   The final touch is to place the variable ‘total’ on a line by itself
8321after the ‘while’ expression.  Otherwise, the value returned by the
8322whole function is the value of the last expression that is evaluated in
8323the body of the ‘let’, and this is the value returned by the ‘while’,
8324which is always ‘nil’.
8325
8326   This may not be evident at first sight.  It almost looks as if the
8327incrementing expression is the last expression of the whole function.
8328But that expression is part of the body of the ‘while’; it is the last
8329element of the list that starts with the symbol ‘while’.  Moreover, the
8330whole of the ‘while’ loop is a list within the body of the ‘let’.
8331
8332   In outline, the function will look like this:
8333
8334     (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
8335       "DOCUMENTATION..."
8336       (let (VARLIST)
8337         (while (TRUE-OR-FALSE-TEST)
8338           BODY-OF-WHILE... )
8339         ... ))                    ; Need final expression here.
8340
8341   The result of evaluating the ‘let’ is what is going to be returned by
8342the ‘defun’ since the ‘let’ is not embedded within any containing list,
8343except for the ‘defun’ as a whole.  However, if the ‘while’ is the last
8344element of the ‘let’ expression, the function will always return ‘nil’.
8345This is not what we want!  Instead, what we want is the value of the
8346variable ‘total’.  This is returned by simply placing the symbol as the
8347last element of the list starting with ‘let’.  It gets evaluated after
8348the preceding elements of the list are evaluated, which means it gets
8349evaluated after it has been assigned the correct value for the total.
8350
8351   It may be easier to see this by printing the list starting with ‘let’
8352all on one line.  This format makes it evident that the VARLIST and
8353‘while’ expressions are the second and third elements of the list
8354starting with ‘let’, and the ‘total’ is the last element:
8355
8356     (let (VARLIST) (while (TRUE-OR-FALSE-TEST) BODY-OF-WHILE... ) total)
8357
8358   Putting everything together, the ‘triangle’ function definition looks
8359like this:
8360
8361     (defun triangle (number-of-rows)    ; Version with
8362                                         ;   incrementing counter.
8363       "Add up the number of pebbles in a triangle.
8364     The first row has one pebble, the second row two pebbles,
8365     the third row three pebbles, and so on.
8366     The argument is NUMBER-OF-ROWS."
8367       (let ((total 0)
8368             (row-number 1))
8369         (while (<= row-number number-of-rows)
8370           (setq total (+ total row-number))
8371           (setq row-number (1+ row-number)))
8372         total))
8373
8374   After you have installed ‘triangle’ by evaluating the function, you
8375can try it out.  Here are two examples:
8376
8377     (triangle 4)
8378
8379     (triangle 7)
8380
8381The sum of the first four numbers is 10 and the sum of the first seven
8382numbers is 28.
8383
8384
8385File: eintr.info,  Node: Decrementing Loop,  Prev: Incrementing Loop Details,  Up: while
8386
838711.1.4 Loop with a Decrementing Counter
8388---------------------------------------
8389
8390Another common way to write a ‘while’ loop is to write the test so that
8391it determines whether a counter is greater than zero.  So long as the
8392counter is greater than zero, the loop is repeated.  But when the
8393counter is equal to or less than zero, the loop is stopped.  For this to
8394work, the counter has to start out greater than zero and then be made
8395smaller and smaller by a form that is evaluated repeatedly.
8396
8397   The test will be an expression such as ‘(> counter 0)’ which returns
8398‘t’ for true if the value of ‘counter’ is greater than zero, and ‘nil’
8399for false if the value of ‘counter’ is equal to or less than zero.  The
8400expression that makes the number smaller and smaller can be a simple
8401‘setq’ such as ‘(setq counter (1- counter))’, where ‘1-’ is a built-in
8402function in Emacs Lisp that subtracts 1 from its argument.
8403
8404   The template for a decrementing ‘while’ loop looks like this:
8405
8406     (while (> counter 0)                    ; true-or-false-test
8407       BODY...
8408       (setq counter (1- counter)))          ; decrementer
8409
8410* Menu:
8411
8412* Decrementing Example::        More pebbles on the beach.
8413* Dec Example parts::           The parts of the function definition.
8414* Dec Example altogether::      Putting the function definition together.
8415
8416
8417File: eintr.info,  Node: Decrementing Example,  Next: Dec Example parts,  Up: Decrementing Loop
8418
8419Example with decrementing counter
8420.................................
8421
8422To illustrate a loop with a decrementing counter, we will rewrite the
8423‘triangle’ function so the counter decreases to zero.
8424
8425   This is the reverse of the earlier version of the function.  In this
8426case, to find out how many pebbles are needed to make a triangle with 3
8427rows, add the number of pebbles in the third row, 3, to the number in
8428the preceding row, 2, and then add the total of those two rows to the
8429row that precedes them, which is 1.
8430
8431   Likewise, to find the number of pebbles in a triangle with 7 rows,
8432add the number of pebbles in the seventh row, 7, to the number in the
8433preceding row, which is 6, and then add the total of those two rows to
8434the row that precedes them, which is 5, and so on.  As in the previous
8435example, each addition only involves adding two numbers, the total of
8436the rows already added up and the number of pebbles in the row that is
8437being added to the total.  This process of adding two numbers is
8438repeated again and again until there are no more pebbles to add.
8439
8440   We know how many pebbles to start with: the number of pebbles in the
8441last row is equal to the number of rows.  If the triangle has seven
8442rows, the number of pebbles in the last row is 7.  Likewise, we know how
8443many pebbles are in the preceding row: it is one less than the number in
8444the row.
8445
8446
8447File: eintr.info,  Node: Dec Example parts,  Next: Dec Example altogether,  Prev: Decrementing Example,  Up: Decrementing Loop
8448
8449The parts of the function definition
8450....................................
8451
8452We start with three variables: the total number of rows in the triangle;
8453the number of pebbles in a row; and the total number of pebbles, which
8454is what we want to calculate.  These variables can be named
8455‘number-of-rows’, ‘number-of-pebbles-in-row’, and ‘total’, respectively.
8456
8457   Both ‘total’ and ‘number-of-pebbles-in-row’ are used only inside the
8458function and are declared with ‘let’.  The initial value of ‘total’
8459should, of course, be zero.  However, the initial value of
8460‘number-of-pebbles-in-row’ should be equal to the number of rows in the
8461triangle, since the addition will start with the longest row.
8462
8463   This means that the beginning of the ‘let’ expression will look like
8464this:
8465
8466     (let ((total 0)
8467           (number-of-pebbles-in-row number-of-rows))
8468       BODY...)
8469
8470   The total number of pebbles can be found by repeatedly adding the
8471number of pebbles in a row to the total already found, that is, by
8472repeatedly evaluating the following expression:
8473
8474     (setq total (+ total number-of-pebbles-in-row))
8475
8476After the ‘number-of-pebbles-in-row’ is added to the ‘total’, the
8477‘number-of-pebbles-in-row’ should be decremented by one, since the next
8478time the loop repeats, the preceding row will be added to the total.
8479
8480   The number of pebbles in a preceding row is one less than the number
8481of pebbles in a row, so the built-in Emacs Lisp function ‘1-’ can be
8482used to compute the number of pebbles in the preceding row.  This can be
8483done with the following expression:
8484
8485     (setq number-of-pebbles-in-row
8486           (1- number-of-pebbles-in-row))
8487
8488   Finally, we know that the ‘while’ loop should stop making repeated
8489additions when there are no pebbles in a row.  So the test for the
8490‘while’ loop is simply:
8491
8492     (while (> number-of-pebbles-in-row 0)
8493
8494
8495File: eintr.info,  Node: Dec Example altogether,  Prev: Dec Example parts,  Up: Decrementing Loop
8496
8497Putting the function definition together
8498........................................
8499
8500We can put these expressions together to create a function definition
8501that works.  However, on examination, we find that one of the local
8502variables is unneeded!
8503
8504   The function definition looks like this:
8505
8506     ;;; First subtractive version.
8507     (defun triangle (number-of-rows)
8508       "Add up the number of pebbles in a triangle."
8509       (let ((total 0)
8510             (number-of-pebbles-in-row number-of-rows))
8511         (while (> number-of-pebbles-in-row 0)
8512           (setq total (+ total number-of-pebbles-in-row))
8513           (setq number-of-pebbles-in-row
8514                 (1- number-of-pebbles-in-row)))
8515         total))
8516
8517   As written, this function works.
8518
8519   However, we do not need ‘number-of-pebbles-in-row’.
8520
8521   When the ‘triangle’ function is evaluated, the symbol
8522‘number-of-rows’ will be bound to a number, giving it an initial value.
8523That number can be changed in the body of the function as if it were a
8524local variable, without any fear that such a change will effect the
8525value of the variable outside of the function.  This is a very useful
8526characteristic of Lisp; it means that the variable ‘number-of-rows’ can
8527be used anywhere in the function where ‘number-of-pebbles-in-row’ is
8528used.
8529
8530   Here is a second version of the function written a bit more cleanly:
8531
8532     (defun triangle (number)                ; Second version.
8533       "Return sum of numbers 1 through NUMBER inclusive."
8534       (let ((total 0))
8535         (while (> number 0)
8536           (setq total (+ total number))
8537           (setq number (1- number)))
8538         total))
8539
8540   In brief, a properly written ‘while’ loop will consist of three
8541parts:
8542
8543  1. A test that will return false after the loop has repeated itself
8544     the correct number of times.
8545
8546  2. An expression the evaluation of which will return the value desired
8547     after being repeatedly evaluated.
8548
8549  3. An expression to change the value passed to the true-or-false-test
8550     so that the test returns false after the loop has repeated itself
8551     the right number of times.
8552
8553
8554File: eintr.info,  Node: dolist dotimes,  Next: Recursion,  Prev: while,  Up: Loops & Recursion
8555
855611.2 Save your time: ‘dolist’ and ‘dotimes’
8557===========================================
8558
8559In addition to ‘while’, both ‘dolist’ and ‘dotimes’ provide for looping.
8560Sometimes these are quicker to write than the equivalent ‘while’ loop.
8561Both are Lisp macros.  (*Note Macros: (elisp)Macros.  )
8562
8563   ‘dolist’ works like a ‘while’ loop that CDRs down a list: ‘dolist’
8564automatically shortens the list each time it loops—takes the CDR of the
8565list—and binds the CAR of each shorter version of the list to the first
8566of its arguments.
8567
8568   ‘dotimes’ loops a specific number of times: you specify the number.
8569
8570* Menu:
8571
8572* dolist::
8573* dotimes::
8574
8575
8576File: eintr.info,  Node: dolist,  Next: dotimes,  Up: dolist dotimes
8577
8578The ‘dolist’ Macro
8579------------------
8580
8581Suppose, for example, you want to reverse a list, so that “first”
8582“second” “third” becomes “third” “second” “first”.
8583
8584   In practice, you would use the ‘reverse’ function, like this:
8585
8586     (setq animals '(gazelle giraffe lion tiger))
8587
8588     (reverse animals)
8589
8590Here is how you could reverse the list using a ‘while’ loop:
8591
8592     (setq animals '(gazelle giraffe lion tiger))
8593
8594     (defun reverse-list-with-while (list)
8595       "Using while, reverse the order of LIST."
8596       (let (value)  ; make sure list starts empty
8597         (while list
8598           (setq value (cons (car list) value))
8599           (setq list (cdr list)))
8600         value))
8601
8602     (reverse-list-with-while animals)
8603
8604And here is how you could use the ‘dolist’ macro:
8605
8606     (setq animals '(gazelle giraffe lion tiger))
8607
8608     (defun reverse-list-with-dolist (list)
8609       "Using dolist, reverse the order of LIST."
8610       (let (value)  ; make sure list starts empty
8611         (dolist (element list value)
8612           (setq value (cons element value)))))
8613
8614     (reverse-list-with-dolist animals)
8615
8616In Info, you can place your cursor after the closing parenthesis of each
8617expression and type ‘C-x C-e’; in each case, you should see
8618
8619     (tiger lion giraffe gazelle)
8620
8621in the echo area.
8622
8623   For this example, the existing ‘reverse’ function is obviously best.
8624The ‘while’ loop is just like our first example (*note A ‘while’ Loop
8625and a List: Loop Example.).  The ‘while’ first checks whether the list
8626has elements; if so, it constructs a new list by adding the first
8627element of the list to the existing list (which in the first iteration
8628of the loop is ‘nil’).  Since the second element is prepended in front
8629of the first element, and the third element is prepended in front of the
8630second element, the list is reversed.
8631
8632   In the expression using a ‘while’ loop, the ‘(setq list (cdr list))’
8633expression shortens the list, so the ‘while’ loop eventually stops.  In
8634addition, it provides the ‘cons’ expression with a new first element by
8635creating a new and shorter list at each repetition of the loop.
8636
8637   The ‘dolist’ expression does very much the same as the ‘while’
8638expression, except that the ‘dolist’ macro does some of the work you
8639have to do when writing a ‘while’ expression.
8640
8641   Like a ‘while’ loop, a ‘dolist’ loops.  What is different is that it
8642automatically shortens the list each time it loops—it CDRs down the list
8643on its own—and it automatically binds the CAR of each shorter version of
8644the list to the first of its arguments.
8645
8646   In the example, the CAR of each shorter version of the list is
8647referred to using the symbol ‘element’, the list itself is called
8648‘list’, and the value returned is called ‘value’.  The remainder of the
8649‘dolist’ expression is the body.
8650
8651   The ‘dolist’ expression binds the CAR of each shorter version of the
8652list to ‘element’ and then evaluates the body of the expression; and
8653repeats the loop.  The result is returned in ‘value’.
8654
8655
8656File: eintr.info,  Node: dotimes,  Prev: dolist,  Up: dolist dotimes
8657
8658The ‘dotimes’ Macro
8659-------------------
8660
8661The ‘dotimes’ macro is similar to ‘dolist’, except that it loops a
8662specific number of times.
8663
8664   The first argument to ‘dotimes’ is assigned the numbers 0, 1, 2 and
8665so forth each time around the loop.  You need to provide the value of
8666the second argument, which is how many times the macro loops.
8667
8668   For example, the following binds the numbers from 0 up to, but not
8669including, the number 3 to the first argument, NUMBER, and then
8670constructs a list of the three numbers.  (The first number is 0, the
8671second number is 1, and the third number is 2; this makes a total of
8672three numbers in all, starting with zero as the first number.)
8673
8674     (let (value)      ; otherwise a value is a void variable
8675       (dotimes (number 3)
8676         (setq value (cons number value)))
8677       value)
8678
8679     ⇒ (2 1 0)
8680
8681The way to use ‘dotimes’ is to operate on some expression NUMBER number
8682of times and then return the result, either as a list or an atom.
8683
8684   Here is an example of a ‘defun’ that uses ‘dotimes’ to add up the
8685number of pebbles in a triangle.
8686
8687     (defun triangle-using-dotimes (number-of-rows)
8688       "Using `dotimes', add up the number of pebbles in a triangle."
8689     (let ((total 0))  ; otherwise a total is a void variable
8690       (dotimes (number number-of-rows)
8691         (setq total (+ total (1+ number))))
8692       total))
8693
8694     (triangle-using-dotimes 4)
8695
8696
8697File: eintr.info,  Node: Recursion,  Next: Looping exercise,  Prev: dolist dotimes,  Up: Loops & Recursion
8698
869911.3 Recursion
8700==============
8701
8702A recursive function contains code that tells the Lisp interpreter to
8703call a program that runs exactly like itself, but with slightly
8704different arguments.  The code runs exactly the same because it has the
8705same name.  However, even though the program has the same name, it is
8706not the same entity.  It is different.  In the jargon, it is a different
8707“instance”.
8708
8709   Eventually, if the program is written correctly, the slightly
8710different arguments will become sufficiently different from the first
8711arguments that the final instance will stop.
8712
8713* Menu:
8714
8715* Building Robots::             Same model, different serial number ...
8716* Recursive Definition Parts::  Walk until you stop ...
8717* Recursion with list::         Using a list as the test whether to recurse.
8718* Recursive triangle function::
8719* Recursion with cond::
8720* Recursive Patterns::          Often used templates.
8721* No Deferment::                Don’t store up work ...
8722* No deferment solution::
8723
8724
8725File: eintr.info,  Node: Building Robots,  Next: Recursive Definition Parts,  Up: Recursion
8726
872711.3.1 Building Robots: Extending the Metaphor
8728----------------------------------------------
8729
8730It is sometimes helpful to think of a running program as a robot that
8731does a job.  In doing its job, a recursive function calls on a second
8732robot to help it.  The second robot is identical to the first in every
8733way, except that the second robot helps the first and has been passed
8734different arguments than the first.
8735
8736   In a recursive function, the second robot may call a third; and the
8737third may call a fourth, and so on.  Each of these is a different
8738entity; but all are clones.
8739
8740   Since each robot has slightly different instructions—the arguments
8741will differ from one robot to the next—the last robot should know when
8742to stop.
8743
8744   Let’s expand on the metaphor in which a computer program is a robot.
8745
8746   A function definition provides the blueprints for a robot.  When you
8747install a function definition, that is, when you evaluate a ‘defun’
8748macro, you install the necessary equipment to build robots.  It is as if
8749you were in a factory, setting up an assembly line.  Robots with the
8750same name are built according to the same blueprints.  So they have the
8751same model number, but a different serial number.
8752
8753   We often say that a recursive function “calls itself”.  What we mean
8754is that the instructions in a recursive function cause the Lisp
8755interpreter to run a different function that has the same name and does
8756the same job as the first, but with different arguments.
8757
8758   It is important that the arguments differ from one instance to the
8759next; otherwise, the process will never stop.
8760
8761
8762File: eintr.info,  Node: Recursive Definition Parts,  Next: Recursion with list,  Prev: Building Robots,  Up: Recursion
8763
876411.3.2 The Parts of a Recursive Definition
8765------------------------------------------
8766
8767A recursive function typically contains a conditional expression which
8768has three parts:
8769
8770  1. A true-or-false-test that determines whether the function is called
8771     again, here called the “do-again-test”.
8772
8773  2. The name of the function.  When this name is called, a new instance
8774     of the function—a new robot, as it were—is created and told what to
8775     do.
8776
8777  3. An expression that returns a different value each time the function
8778     is called, here called the “next-step-expression”.  Consequently,
8779     the argument (or arguments) passed to the new instance of the
8780     function will be different from that passed to the previous
8781     instance.  This causes the conditional expression, the
8782     “do-again-test”, to test false after the correct number of
8783     repetitions.
8784
8785   Recursive functions can be much simpler than any other kind of
8786function.  Indeed, when people first start to use them, they often look
8787so mysteriously simple as to be incomprehensible.  Like riding a
8788bicycle, reading a recursive function definition takes a certain knack
8789which is hard at first but then seems simple.
8790
8791   There are several different common recursive patterns.  A very simple
8792pattern looks like this:
8793
8794     (defun NAME-OF-RECURSIVE-FUNCTION (ARGUMENT-LIST)
8795       "DOCUMENTATION..."
8796       (if DO-AGAIN-TEST
8797         BODY...
8798         (NAME-OF-RECURSIVE-FUNCTION
8799              NEXT-STEP-EXPRESSION)))
8800
8801   Each time a recursive function is evaluated, a new instance of it is
8802created and told what to do.  The arguments tell the instance what to
8803do.
8804
8805   An argument is bound to the value of the next-step-expression.  Each
8806instance runs with a different value of the next-step-expression.
8807
8808   The value in the next-step-expression is used in the do-again-test.
8809
8810   The value returned by the next-step-expression is passed to the new
8811instance of the function, which evaluates it (or some transmogrification
8812of it) to determine whether to continue or stop.  The
8813next-step-expression is designed so that the do-again-test returns false
8814when the function should no longer be repeated.
8815
8816   The do-again-test is sometimes called the “stop condition”, since it
8817stops the repetitions when it tests false.
8818
8819
8820File: eintr.info,  Node: Recursion with list,  Next: Recursive triangle function,  Prev: Recursive Definition Parts,  Up: Recursion
8821
882211.3.3 Recursion with a List
8823----------------------------
8824
8825The example of a ‘while’ loop that printed the elements of a list of
8826numbers can be written recursively.  Here is the code, including an
8827expression to set the value of the variable ‘animals’ to a list.
8828
8829   If you are reading this in Info in Emacs, you can evaluate this
8830expression directly in Info.  Otherwise, you must copy the example to
8831the ‘*scratch*’ buffer and evaluate each expression there.  Use ‘C-u C-x
8832C-e’ to evaluate the ‘(print-elements-recursively animals)’ expression
8833so that the results are printed in the buffer; otherwise the Lisp
8834interpreter will try to squeeze the results into the one line of the
8835echo area.
8836
8837   Also, place your cursor immediately after the last closing
8838parenthesis of the ‘print-elements-recursively’ function, before the
8839comment.  Otherwise, the Lisp interpreter will try to evaluate the
8840comment.
8841
8842     (setq animals '(gazelle giraffe lion tiger))
8843
8844     (defun print-elements-recursively (list)
8845       "Print each element of LIST on a line of its own.
8846     Uses recursion."
8847       (when list                            ; do-again-test
8848             (print (car list))              ; body
8849             (print-elements-recursively     ; recursive call
8850              (cdr list))))                  ; next-step-expression
8851
8852     (print-elements-recursively animals)
8853
8854   The ‘print-elements-recursively’ function first tests whether there
8855is any content in the list; if there is, the function prints the first
8856element of the list, the CAR of the list.  Then the function invokes
8857itself, but gives itself as its argument, not the whole list, but the
8858second and subsequent elements of the list, the CDR of the list.
8859
8860   Put another way, if the list is not empty, the function invokes
8861another instance of code that is similar to the initial code, but is a
8862different thread of execution, with different arguments than the first
8863instance.
8864
8865   Put in yet another way, if the list is not empty, the first robot
8866assembles a second robot and tells it what to do; the second robot is a
8867different individual from the first, but is the same model.
8868
8869   When the second evaluation occurs, the ‘when’ expression is evaluated
8870and if true, prints the first element of the list it receives as its
8871argument (which is the second element of the original list).  Then the
8872function calls itself with the CDR of the list it is invoked with, which
8873(the second time around) is the CDR of the CDR of the original list.
8874
8875   Note that although we say that the function “calls itself”, what we
8876mean is that the Lisp interpreter assembles and instructs a new instance
8877of the program.  The new instance is a clone of the first, but is a
8878separate individual.
8879
8880   Each time the function invokes itself, it does so on a shorter
8881version of the original list.  It creates a new instance that works on a
8882shorter list.
8883
8884   Eventually, the function invokes itself on an empty list.  It creates
8885a new instance whose argument is ‘nil’.  The conditional expression
8886tests the value of ‘list’.  Since the value of ‘list’ is ‘nil’, the
8887‘when’ expression tests false so the then-part is not evaluated.  The
8888function as a whole then returns ‘nil’.
8889
8890   When you evaluate the expression ‘(print-elements-recursively
8891animals)’ in the ‘*scratch*’ buffer, you see this result:
8892
8893     gazelle
8894
8895     giraffe
8896
8897     lion
8898
8899     tiger
8900     nil
8901
8902
8903File: eintr.info,  Node: Recursive triangle function,  Next: Recursion with cond,  Prev: Recursion with list,  Up: Recursion
8904
890511.3.4 Recursion in Place of a Counter
8906--------------------------------------
8907
8908The ‘triangle’ function described in a previous section can also be
8909written recursively.  It looks like this:
8910
8911     (defun triangle-recursively (number)
8912       "Return the sum of the numbers 1 through NUMBER inclusive.
8913     Uses recursion."
8914       (if (= number 1)                    ; do-again-test
8915           1                               ; then-part
8916         (+ number                         ; else-part
8917            (triangle-recursively          ; recursive call
8918             (1- number)))))               ; next-step-expression
8919
8920     (triangle-recursively 7)
8921
8922You can install this function by evaluating it and then try it by
8923evaluating ‘(triangle-recursively 7)’.  (Remember to put your cursor
8924immediately after the last parenthesis of the function definition,
8925before the comment.)  The function evaluates to 28.
8926
8927   To understand how this function works, let’s consider what happens in
8928the various cases when the function is passed 1, 2, 3, or 4 as the value
8929of its argument.
8930
8931* Menu:
8932
8933* Recursive Example arg of 1 or 2::
8934* Recursive Example arg of 3 or 4::
8935
8936
8937File: eintr.info,  Node: Recursive Example arg of 1 or 2,  Next: Recursive Example arg of 3 or 4,  Up: Recursive triangle function
8938
8939An argument of 1 or 2
8940.....................
8941
8942First, what happens if the value of the argument is 1?
8943
8944   The function has an ‘if’ expression after the documentation string.
8945It tests whether the value of ‘number’ is equal to 1; if so, Emacs
8946evaluates the then-part of the ‘if’ expression, which returns the number
89471 as the value of the function.  (A triangle with one row has one pebble
8948in it.)
8949
8950   Suppose, however, that the value of the argument is 2.  In this case,
8951Emacs evaluates the else-part of the ‘if’ expression.
8952
8953   The else-part consists of an addition, the recursive call to
8954‘triangle-recursively’ and a decrementing action; and it looks like
8955this:
8956
8957     (+ number (triangle-recursively (1- number)))
8958
8959   When Emacs evaluates this expression, the innermost expression is
8960evaluated first; then the other parts in sequence.  Here are the steps
8961in detail:
8962
8963Step 1    Evaluate the innermost expression.
8964
8965     The innermost expression is ‘(1- number)’ so Emacs decrements the
8966     value of ‘number’ from 2 to 1.
8967
8968Step 2    Evaluate the ‘triangle-recursively’ function.
8969
8970     The Lisp interpreter creates an individual instance of
8971     ‘triangle-recursively’.  It does not matter that this function is
8972     contained within itself.  Emacs passes the result Step 1 as the
8973     argument used by this instance of the ‘triangle-recursively’
8974     function
8975
8976     In this case, Emacs evaluates ‘triangle-recursively’ with an
8977     argument of 1.  This means that this evaluation of
8978     ‘triangle-recursively’ returns 1.
8979
8980Step 3    Evaluate the value of ‘number’.
8981
8982     The variable ‘number’ is the second element of the list that starts
8983     with ‘+’; its value is 2.
8984
8985Step 4    Evaluate the ‘+’ expression.
8986
8987     The ‘+’ expression receives two arguments, the first from the
8988     evaluation of ‘number’ (Step 3) and the second from the evaluation
8989     of ‘triangle-recursively’ (Step 2).
8990
8991     The result of the addition is the sum of 2 plus 1, and the number 3
8992     is returned, which is correct.  A triangle with two rows has three
8993     pebbles in it.
8994
8995
8996File: eintr.info,  Node: Recursive Example arg of 3 or 4,  Prev: Recursive Example arg of 1 or 2,  Up: Recursive triangle function
8997
8998An argument of 3 or 4
8999.....................
9000
9001Suppose that ‘triangle-recursively’ is called with an argument of 3.
9002
9003Step 1    Evaluate the do-again-test.
9004
9005     The ‘if’ expression is evaluated first.  This is the do-again test
9006     and returns false, so the else-part of the ‘if’ expression is
9007     evaluated.  (Note that in this example, the do-again-test causes
9008     the function to call itself when it tests false, not when it tests
9009     true.)
9010
9011Step 2    Evaluate the innermost expression of the else-part.
9012
9013     The innermost expression of the else-part is evaluated, which
9014     decrements 3 to 2.  This is the next-step-expression.
9015
9016Step 3    Evaluate the ‘triangle-recursively’ function.
9017
9018     The number 2 is passed to the ‘triangle-recursively’ function.
9019
9020     We already know what happens when Emacs evaluates
9021     ‘triangle-recursively’ with an argument of 2.  After going through
9022     the sequence of actions described earlier, it returns a value of 3.
9023     So that is what will happen here.
9024
9025Step 4    Evaluate the addition.
9026
9027     3 will be passed as an argument to the addition and will be added
9028     to the number with which the function was called, which is 3.
9029
9030The value returned by the function as a whole will be 6.
9031
9032   Now that we know what will happen when ‘triangle-recursively’ is
9033called with an argument of 3, it is evident what will happen if it is
9034called with an argument of 4:
9035
9036     In the recursive call, the evaluation of
9037
9038          (triangle-recursively (1- 4))
9039
9040     will return the value of evaluating
9041
9042          (triangle-recursively 3)
9043
9044     which is 6 and this value will be added to 4 by the addition in the
9045     third line.
9046
9047The value returned by the function as a whole will be 10.
9048
9049   Each time ‘triangle-recursively’ is evaluated, it evaluates a version
9050of itself—a different instance of itself—with a smaller argument, until
9051the argument is small enough so that it does not evaluate itself.
9052
9053   Note that this particular design for a recursive function requires
9054that operations be deferred.
9055
9056   Before ‘(triangle-recursively 7)’ can calculate its answer, it must
9057call ‘(triangle-recursively 6)’; and before ‘(triangle-recursively 6)’
9058can calculate its answer, it must call ‘(triangle-recursively 5)’; and
9059so on.  That is to say, the calculation that ‘(triangle-recursively 7)’
9060makes must be deferred until ‘(triangle-recursively 6)’ makes its
9061calculation; and ‘(triangle-recursively 6)’ must defer until
9062‘(triangle-recursively 5)’ completes; and so on.
9063
9064   If each of these instances of ‘triangle-recursively’ are thought of
9065as different robots, the first robot must wait for the second to
9066complete its job, which must wait until the third completes, and so on.
9067
9068   There is a way around this kind of waiting, which we will discuss in
9069*note Recursion without Deferments: No Deferment.
9070
9071
9072File: eintr.info,  Node: Recursion with cond,  Next: Recursive Patterns,  Prev: Recursive triangle function,  Up: Recursion
9073
907411.3.5 Recursion Example Using ‘cond’
9075-------------------------------------
9076
9077The version of ‘triangle-recursively’ described earlier is written with
9078the ‘if’ special form.  It can also be written using another special
9079form called ‘cond’.  The name of the special form ‘cond’ is an
9080abbreviation of the word ‘conditional’.
9081
9082   Although the ‘cond’ special form is not used as often in the Emacs
9083Lisp sources as ‘if’, it is used often enough to justify explaining it.
9084
9085   The template for a ‘cond’ expression looks like this:
9086
9087     (cond
9088      BODY...)
9089
9090where the BODY is a series of lists.
9091
9092   Written out more fully, the template looks like this:
9093
9094     (cond
9095      (FIRST-TRUE-OR-FALSE-TEST FIRST-CONSEQUENT)
9096      (SECOND-TRUE-OR-FALSE-TEST SECOND-CONSEQUENT)
9097      (THIRD-TRUE-OR-FALSE-TEST THIRD-CONSEQUENT)
9098       ...)
9099
9100   When the Lisp interpreter evaluates the ‘cond’ expression, it
9101evaluates the first element (the CAR or true-or-false-test) of the first
9102expression in a series of expressions within the body of the ‘cond’.
9103
9104   If the true-or-false-test returns ‘nil’ the rest of that expression,
9105the consequent, is skipped and the true-or-false-test of the next
9106expression is evaluated.  When an expression is found whose
9107true-or-false-test returns a value that is not ‘nil’, the consequent of
9108that expression is evaluated.  The consequent can be one or more
9109expressions.  If the consequent consists of more than one expression,
9110the expressions are evaluated in sequence and the value of the last one
9111is returned.  If the expression does not have a consequent, the value of
9112the true-or-false-test is returned.
9113
9114   If none of the true-or-false-tests test true, the ‘cond’ expression
9115returns ‘nil’.
9116
9117   Written using ‘cond’, the ‘triangle’ function looks like this:
9118
9119     (defun triangle-using-cond (number)
9120       (cond ((<= number 0) 0)
9121             ((= number 1) 1)
9122             ((> number 1)
9123              (+ number (triangle-using-cond (1- number))))))
9124
9125In this example, the ‘cond’ returns 0 if the number is less than or
9126equal to 0, it returns 1 if the number is 1 and it evaluates ‘(+ number
9127(triangle-using-cond (1- number)))’ if the number is greater than 1.
9128
9129
9130File: eintr.info,  Node: Recursive Patterns,  Next: No Deferment,  Prev: Recursion with cond,  Up: Recursion
9131
913211.3.6 Recursive Patterns
9133-------------------------
9134
9135Here are three common recursive patterns.  Each involves a list.
9136Recursion does not need to involve lists, but Lisp is designed for lists
9137and this provides a sense of its primal capabilities.
9138
9139* Menu:
9140
9141* Every::
9142* Accumulate::
9143* Keep::
9144
9145
9146File: eintr.info,  Node: Every,  Next: Accumulate,  Up: Recursive Patterns
9147
9148Recursive Pattern: _every_
9149..........................
9150
9151In the ‘every’ recursive pattern, an action is performed on every
9152element of a list.
9153
9154   The basic pattern is:
9155
9156   • If a list be empty, return ‘nil’.
9157   • Else, act on the beginning of the list (the CAR of the list)
9158        − through a recursive call by the function on the rest (the CDR)
9159          of the list,
9160        − and, optionally, combine the acted-on element, using ‘cons’,
9161          with the results of acting on the rest.
9162
9163   Here is an example:
9164
9165     (defun square-each (numbers-list)
9166       "Square each of a NUMBERS LIST, recursively."
9167       (if (not numbers-list)                ; do-again-test
9168           nil
9169         (cons
9170          (* (car numbers-list) (car numbers-list))
9171          (square-each (cdr numbers-list))))) ; next-step-expression
9172
9173     (square-each '(1 2 3))
9174         ⇒ (1 4 9)
9175
9176If ‘numbers-list’ is empty, do nothing.  But if it has content,
9177construct a list combining the square of the first number in the list
9178with the result of the recursive call.
9179
9180   (The example follows the pattern exactly: ‘nil’ is returned if the
9181numbers’ list is empty.  In practice, you would write the conditional so
9182it carries out the action when the numbers’ list is not empty.)
9183
9184   The ‘print-elements-recursively’ function (*note Recursion with a
9185List: Recursion with list.) is another example of an ‘every’ pattern,
9186except in this case, rather than bring the results together using
9187‘cons’, we print each element of output.
9188
9189   The ‘print-elements-recursively’ function looks like this:
9190
9191     (setq animals '(gazelle giraffe lion tiger))
9192
9193     (defun print-elements-recursively (list)
9194       "Print each element of LIST on a line of its own.
9195     Uses recursion."
9196       (when list                            ; do-again-test
9197             (print (car list))              ; body
9198             (print-elements-recursively     ; recursive call
9199              (cdr list))))                  ; next-step-expression
9200
9201     (print-elements-recursively animals)
9202
9203   The pattern for ‘print-elements-recursively’ is:
9204
9205   • When the list is empty, do nothing.
9206   • But when the list has at least one element,
9207        − act on the beginning of the list (the CAR of the list),
9208        − and make a recursive call on the rest (the CDR) of the list.
9209
9210
9211File: eintr.info,  Node: Accumulate,  Next: Keep,  Prev: Every,  Up: Recursive Patterns
9212
9213Recursive Pattern: _accumulate_
9214...............................
9215
9216Another recursive pattern is called the ‘accumulate’ pattern.  In the
9217‘accumulate’ recursive pattern, an action is performed on every element
9218of a list and the result of that action is accumulated with the results
9219of performing the action on the other elements.
9220
9221   This is very like the ‘every’ pattern using ‘cons’, except that
9222‘cons’ is not used, but some other combiner.
9223
9224   The pattern is:
9225
9226   • If a list be empty, return zero or some other constant.
9227   • Else, act on the beginning of the list (the CAR of the list),
9228        − and combine that acted-on element, using ‘+’ or some other
9229          combining function, with
9230        − a recursive call by the function on the rest (the CDR) of the
9231          list.
9232
9233   Here is an example:
9234
9235     (defun add-elements (numbers-list)
9236       "Add the elements of NUMBERS-LIST together."
9237       (if (not numbers-list)
9238           0
9239         (+ (car numbers-list) (add-elements (cdr numbers-list)))))
9240
9241     (add-elements '(1 2 3 4))
9242         ⇒ 10
9243
9244   *Note Making a List of Files: Files List, for an example of the
9245accumulate pattern.
9246
9247
9248File: eintr.info,  Node: Keep,  Prev: Accumulate,  Up: Recursive Patterns
9249
9250Recursive Pattern: _keep_
9251.........................
9252
9253A third recursive pattern is called the ‘keep’ pattern.  In the ‘keep’
9254recursive pattern, each element of a list is tested; the element is
9255acted on and the results are kept only if the element meets a criterion.
9256
9257   Again, this is very like the ‘every’ pattern, except the element is
9258skipped unless it meets a criterion.
9259
9260   The pattern has three parts:
9261
9262   • If a list be empty, return ‘nil’.
9263   • Else, if the beginning of the list (the CAR of the list) passes a
9264     test
9265        − act on that element and combine it, using ‘cons’ with
9266        − a recursive call by the function on the rest (the CDR) of the
9267          list.
9268   • Otherwise, if the beginning of the list (the CAR of the list) fails
9269     the test
9270        − skip on that element,
9271        − and, recursively call the function on the rest (the CDR) of
9272          the list.
9273
9274   Here is an example that uses ‘cond’:
9275
9276     (defun keep-three-letter-words (word-list)
9277       "Keep three letter words in WORD-LIST."
9278       (cond
9279        ;; First do-again-test: stop-condition
9280        ((not word-list) nil)
9281
9282        ;; Second do-again-test: when to act
9283        ((eq 3 (length (symbol-name (car word-list))))
9284         ;; combine acted-on element with recursive call on shorter list
9285         (cons (car word-list) (keep-three-letter-words (cdr word-list))))
9286
9287        ;; Third do-again-test: when to skip element;
9288        ;;   recursively call shorter list with next-step expression
9289        (t (keep-three-letter-words (cdr word-list)))))
9290
9291     (keep-three-letter-words '(one two three four five six))
9292         ⇒ (one two six)
9293
9294   It goes without saying that you need not use ‘nil’ as the test for
9295when to stop; and you can, of course, combine these patterns.
9296
9297
9298File: eintr.info,  Node: No Deferment,  Next: No deferment solution,  Prev: Recursive Patterns,  Up: Recursion
9299
930011.3.7 Recursion without Deferments
9301-----------------------------------
9302
9303Let’s consider again what happens with the ‘triangle-recursively’
9304function.  We will find that the intermediate calculations are deferred
9305until all can be done.
9306
9307   Here is the function definition:
9308
9309     (defun triangle-recursively (number)
9310       "Return the sum of the numbers 1 through NUMBER inclusive.
9311     Uses recursion."
9312       (if (= number 1)                    ; do-again-test
9313           1                               ; then-part
9314         (+ number                         ; else-part
9315            (triangle-recursively          ; recursive call
9316             (1- number)))))               ; next-step-expression
9317
9318   What happens when we call this function with an argument of 7?
9319
9320   The first instance of the ‘triangle-recursively’ function adds the
9321number 7 to the value returned by a second instance of
9322‘triangle-recursively’, an instance that has been passed an argument of
93236.  That is to say, the first calculation is:
9324
9325     (+ 7 (triangle-recursively 6))
9326
9327The first instance of ‘triangle-recursively’—you may want to think of it
9328as a little robot—cannot complete its job.  It must hand off the
9329calculation for ‘(triangle-recursively 6)’ to a second instance of the
9330program, to a second robot.  This second individual is completely
9331different from the first one; it is, in the jargon, a “different
9332instantiation”.  Or, put another way, it is a different robot.  It is
9333the same model as the first; it calculates triangle numbers recursively;
9334but it has a different serial number.
9335
9336   And what does ‘(triangle-recursively 6)’ return?  It returns the
9337number 6 added to the value returned by evaluating
9338‘triangle-recursively’ with an argument of 5.  Using the robot metaphor,
9339it asks yet another robot to help it.
9340
9341   Now the total is:
9342
9343     (+ 7 6 (triangle-recursively 5))
9344
9345   And what happens next?
9346
9347     (+ 7 6 5 (triangle-recursively 4))
9348
9349   Each time ‘triangle-recursively’ is called, except for the last time,
9350it creates another instance of the program—another robot—and asks it to
9351make a calculation.
9352
9353   Eventually, the full addition is set up and performed:
9354
9355     (+ 7 6 5 4 3 2 1)
9356
9357   This design for the function defers the calculation of the first step
9358until the second can be done, and defers that until the third can be
9359done, and so on.  Each deferment means the computer must remember what
9360is being waited on.  This is not a problem when there are only a few
9361steps, as in this example.  But it can be a problem when there are more
9362steps.
9363
9364
9365File: eintr.info,  Node: No deferment solution,  Prev: No Deferment,  Up: Recursion
9366
936711.3.8 No Deferment Solution
9368----------------------------
9369
9370The solution to the problem of deferred operations is to write in a
9371manner that does not defer operations(1).  This requires writing to a
9372different pattern, often one that involves writing two function
9373definitions, an initialization function and a helper function.
9374
9375   The initialization function sets up the job; the helper function does
9376the work.
9377
9378   Here are the two function definitions for adding up numbers.  They
9379are so simple, I find them hard to understand.
9380
9381     (defun triangle-initialization (number)
9382       "Return the sum of the numbers 1 through NUMBER inclusive.
9383     This is the initialization component of a two function
9384     duo that uses recursion."
9385       (triangle-recursive-helper 0 0 number))
9386
9387     (defun triangle-recursive-helper (sum counter number)
9388       "Return SUM, using COUNTER, through NUMBER inclusive.
9389     This is the helper component of a two function duo
9390     that uses recursion."
9391       (if (> counter number)
9392           sum
9393         (triangle-recursive-helper (+ sum counter)  ; sum
9394                                    (1+ counter)     ; counter
9395                                    number)))        ; number
9396
9397   Install both function definitions by evaluating them, then call
9398‘triangle-initialization’ with 2 rows:
9399
9400     (triangle-initialization 2)
9401         ⇒ 3
9402
9403   The initialization function calls the first instance of the helper
9404function with three arguments: zero, zero, and a number which is the
9405number of rows in the triangle.
9406
9407   The first two arguments passed to the helper function are
9408initialization values.  These values are changed when
9409‘triangle-recursive-helper’ invokes new instances.(2)
9410
9411   Let’s see what happens when we have a triangle that has one row.
9412(This triangle will have one pebble in it!)
9413
9414   ‘triangle-initialization’ will call its helper with the arguments
9415‘0 0 1’.  That function will run the conditional test whether ‘(>
9416counter number)’:
9417
9418     (> 0 1)
9419
9420and find that the result is false, so it will invoke the else-part of
9421the ‘if’ clause:
9422
9423         (triangle-recursive-helper
9424          (+ sum counter)  ; sum plus counter ⇒ sum
9425          (1+ counter)     ; increment counter ⇒ counter
9426          number)          ; number stays the same
9427
9428which will first compute:
9429
9430     (triangle-recursive-helper (+ 0 0)  ; sum
9431                                (1+ 0)   ; counter
9432                                1)       ; number
9433which is:
9434
9435     (triangle-recursive-helper 0 1 1)
9436
9437   Again, ‘(> counter number)’ will be false, so again, the Lisp
9438interpreter will evaluate ‘triangle-recursive-helper’, creating a new
9439instance with new arguments.
9440
9441   This new instance will be;
9442
9443         (triangle-recursive-helper
9444          (+ sum counter)  ; sum plus counter ⇒ sum
9445          (1+ counter)     ; increment counter ⇒ counter
9446          number)          ; number stays the same
9447
9448which is:
9449
9450     (triangle-recursive-helper 1 2 1)
9451
9452   In this case, the ‘(> counter number)’ test will be true!  So the
9453instance will return the value of the sum, which will be 1, as expected.
9454
9455   Now, let’s pass ‘triangle-initialization’ an argument of 2, to find
9456out how many pebbles there are in a triangle with two rows.
9457
9458   That function calls ‘(triangle-recursive-helper 0 0 2)’.
9459
9460   In stages, the instances called will be:
9461
9462                               sum counter number
9463     (triangle-recursive-helper 0    1       2)
9464
9465     (triangle-recursive-helper 1    2       2)
9466
9467     (triangle-recursive-helper 3    3       2)
9468
9469   When the last instance is called, the ‘(> counter number)’ test will
9470be true, so the instance will return the value of ‘sum’, which will be
94713.
9472
9473   This kind of pattern helps when you are writing functions that can
9474use many resources in a computer.
9475
9476   ---------- Footnotes ----------
9477
9478   (1) The phrase “tail recursive” is used to describe such a process,
9479one that uses constant space.
9480
9481   (2) The jargon is mildly confusing: ‘triangle-recursive-helper’ uses
9482a process that is iterative in a procedure that is recursive.  The
9483process is called iterative because the computer need only record the
9484three values, ‘sum’, ‘counter’, and ‘number’; the procedure is recursive
9485because the function calls itself.  On the other hand, both the process
9486and the procedure used by ‘triangle-recursively’ are called recursive.
9487The word “recursive” has different meanings in the two contexts.
9488
9489
9490File: eintr.info,  Node: Looping exercise,  Prev: Recursion,  Up: Loops & Recursion
9491
949211.4 Looping Exercise
9493=====================
9494
9495   • Write a function similar to ‘triangle’ in which each row has a
9496     value which is the square of the row number.  Use a ‘while’ loop.
9497
9498   • Write a function similar to ‘triangle’ that multiplies instead of
9499     adds the values.
9500
9501   • Rewrite these two functions recursively.  Rewrite these functions
9502     using ‘cond’.
9503
9504   • Write a function for Texinfo mode that creates an index entry at
9505     the beginning of a paragraph for every ‘@dfn’ within the paragraph.
9506     (In a Texinfo file, ‘@dfn’ marks a definition.  This book is
9507     written in Texinfo.)
9508
9509     Many of the functions you will need are described in two of the
9510     previous chapters, *note Cutting and Storing Text: Cutting &
9511     Storing Text, and *note Yanking Text Back: Yanking.  If you use
9512     ‘forward-paragraph’ to put the index entry at the beginning of the
9513     paragraph, you will have to use ‘C-h f’ (‘describe-function’) to
9514     find out how to make the command go backwards.
9515
9516     For more information, see *note Indicating Definitions:
9517     (texinfo)Indicating.
9518
9519
9520File: eintr.info,  Node: Regexp Search,  Next: Counting Words,  Prev: Loops & Recursion,  Up: Top
9521
952212 Regular Expression Searches
9523******************************
9524
9525Regular expression searches are used extensively in GNU Emacs.  The two
9526functions, ‘forward-sentence’ and ‘forward-paragraph’, illustrate these
9527searches well.  They use regular expressions to find where to move
9528point.  The phrase “regular expression” is often written as “regexp”.
9529
9530   Regular expression searches are described in *note Regular Expression
9531Search: (emacs)Regexp Search, as well as in *note (elisp)Regular
9532Expressions::.  In writing this chapter, I am presuming that you have at
9533least a mild acquaintance with them.  The major point to remember is
9534that regular expressions permit you to search for patterns as well as
9535for literal strings of characters.  For example, the code in
9536‘forward-sentence’ searches for the pattern of possible characters that
9537could mark the end of a sentence, and moves point to that spot.
9538
9539   Before looking at the code for the ‘forward-sentence’ function, it is
9540worth considering what the pattern that marks the end of a sentence must
9541be.  The pattern is discussed in the next section; following that is a
9542description of the regular expression search function,
9543‘re-search-forward’.  The ‘forward-sentence’ function is described in
9544the section following.  Finally, the ‘forward-paragraph’ function is
9545described in the last section of this chapter.  ‘forward-paragraph’ is a
9546complex function that introduces several new features.
9547
9548* Menu:
9549
9550* sentence-end::                The regular expression for ‘sentence-end’.
9551* re-search-forward::           Very similar to ‘search-forward’.
9552* forward-sentence::            A straightforward example of regexp search.
9553* forward-paragraph::           A somewhat complex example.
9554* Regexp Review::
9555* re-search Exercises::
9556
9557
9558File: eintr.info,  Node: sentence-end,  Next: re-search-forward,  Up: Regexp Search
9559
956012.1 The Regular Expression for ‘sentence-end’
9561==============================================
9562
9563The symbol ‘sentence-end’ is bound to the pattern that marks the end of
9564a sentence.  What should this regular expression be?
9565
9566   Clearly, a sentence may be ended by a period, a question mark, or an
9567exclamation mark.  Indeed, in English, only clauses that end with one of
9568those three characters should be considered the end of a sentence.  This
9569means that the pattern should include the character set:
9570
9571     [.?!]
9572
9573   However, we do not want ‘forward-sentence’ merely to jump to a
9574period, a question mark, or an exclamation mark, because such a
9575character might be used in the middle of a sentence.  A period, for
9576example, is used after abbreviations.  So other information is needed.
9577
9578   According to convention, you type two spaces after every sentence,
9579but only one space after a period, a question mark, or an exclamation
9580mark in the body of a sentence.  So a period, a question mark, or an
9581exclamation mark followed by two spaces is a good indicator of an end of
9582sentence.  However, in a file, the two spaces may instead be a tab or
9583the end of a line.  This means that the regular expression should
9584include these three items as alternatives.
9585
9586   This group of alternatives will look like this:
9587
9588     \\($\\| \\|  \\)
9589            ^   ^^
9590           TAB  SPC
9591
9592Here, ‘$’ indicates the end of the line, and I have pointed out where
9593the tab and two spaces are inserted in the expression.  Both are
9594inserted by putting the actual characters into the expression.
9595
9596   Two backslashes, ‘\\’, are required before the parentheses and
9597vertical bars: the first backslash quotes the following backslash in
9598Emacs; and the second indicates that the following character, the
9599parenthesis or the vertical bar, is special.
9600
9601   Also, a sentence may be followed by one or more carriage returns,
9602like this:
9603
9604     [
9605     ]*
9606
9607Like tabs and spaces, a carriage return is inserted into a regular
9608expression by inserting it literally.  The asterisk indicates that the
9609<RET> is repeated zero or more times.
9610
9611   But a sentence end does not consist only of a period, a question mark
9612or an exclamation mark followed by appropriate space: a closing
9613quotation mark or a closing brace of some kind may precede the space.
9614Indeed more than one such mark or brace may precede the space.  These
9615require a expression that looks like this:
9616
9617     []\"')}]*
9618
9619   In this expression, the first ‘]’ is the first character in the
9620expression; the second character is ‘"’, which is preceded by a ‘\’ to
9621tell Emacs the ‘"’ is _not_ special.  The last three characters are ‘'’,
9622‘)’, and ‘}’.
9623
9624   All this suggests what the regular expression pattern for matching
9625the end of a sentence should be; and, indeed, if we evaluate
9626‘sentence-end’ we find that it returns the following value:
9627
9628     sentence-end
9629          ⇒ "[.?!][]\"')}]*\\($\\|     \\|  \\)[
9630     ]*"
9631
9632(Well, not in GNU Emacs 22; that is because of an effort to make the
9633process simpler and to handle more glyphs and languages.  When the value
9634of ‘sentence-end’ is ‘nil’, then use the value defined by the function
9635‘sentence-end’.  (Here is a use of the difference between a value and a
9636function in Emacs Lisp.)  The function returns a value constructed from
9637the variables ‘sentence-end-base’, ‘sentence-end-double-space’,
9638‘sentence-end-without-period’, and ‘sentence-end-without-space’.  The
9639critical variable is ‘sentence-end-base’; its global value is similar to
9640the one described above but it also contains two additional quotation
9641marks.  These have differing degrees of curliness.  The
9642‘sentence-end-without-period’ variable, when true, tells Emacs that a
9643sentence may end without a period, such as text in Thai.)
9644
9645
9646File: eintr.info,  Node: re-search-forward,  Next: forward-sentence,  Prev: sentence-end,  Up: Regexp Search
9647
964812.2 The ‘re-search-forward’ Function
9649=====================================
9650
9651The ‘re-search-forward’ function is very like the ‘search-forward’
9652function.  (*Note The ‘search-forward’ Function: search-forward.)
9653
9654   ‘re-search-forward’ searches for a regular expression.  If the search
9655is successful, it leaves point immediately after the last character in
9656the target.  If the search is backwards, it leaves point just before the
9657first character in the target.  You may tell ‘re-search-forward’ to
9658return ‘t’ for true.  (Moving point is therefore a side effect.)
9659
9660   Like ‘search-forward’, the ‘re-search-forward’ function takes four
9661arguments:
9662
9663  1. The first argument is the regular expression that the function
9664     searches for.  The regular expression will be a string between
9665     quotation marks.
9666
9667  2. The optional second argument limits how far the function will
9668     search; it is a bound, which is specified as a position in the
9669     buffer.
9670
9671  3. The optional third argument specifies how the function responds to
9672     failure: ‘nil’ as the third argument causes the function to signal
9673     an error (and print a message) when the search fails; any other
9674     value causes it to return ‘nil’ if the search fails and ‘t’ if the
9675     search succeeds.
9676
9677  4. The optional fourth argument is the repeat count.  A negative
9678     repeat count causes ‘re-search-forward’ to search backwards.
9679
9680   The template for ‘re-search-forward’ looks like this:
9681
9682     (re-search-forward "REGULAR-EXPRESSION"
9683                     LIMIT-OF-SEARCH
9684                     WHAT-TO-DO-IF-SEARCH-FAILS
9685                     REPEAT-COUNT)
9686
9687   The second, third, and fourth arguments are optional.  However, if
9688you want to pass a value to either or both of the last two arguments,
9689you must also pass a value to all the preceding arguments.  Otherwise,
9690the Lisp interpreter will mistake which argument you are passing the
9691value to.
9692
9693   In the ‘forward-sentence’ function, the regular expression will be
9694the value of the variable ‘sentence-end’.  In simple form, that is:
9695
9696     "[.?!][]\"')}]*\\($\\|  \\|  \\)[
9697     ]*"
9698
9699The limit of the search will be the end of the paragraph (since a
9700sentence cannot go beyond a paragraph).  If the search fails, the
9701function will return ‘nil’; and the repeat count will be provided by the
9702argument to the ‘forward-sentence’ function.
9703
9704
9705File: eintr.info,  Node: forward-sentence,  Next: forward-paragraph,  Prev: re-search-forward,  Up: Regexp Search
9706
970712.3 ‘forward-sentence’
9708=======================
9709
9710The command to move the cursor forward a sentence is a straightforward
9711illustration of how to use regular expression searches in Emacs Lisp.
9712Indeed, the function looks longer and more complicated than it is; this
9713is because the function is designed to go backwards as well as forwards;
9714and, optionally, over more than one sentence.  The function is usually
9715bound to the key command ‘M-e’.
9716
9717* Menu:
9718
9719* Complete forward-sentence::
9720* fwd-sentence while loops::    Two ‘while’ loops.
9721* fwd-sentence re-search::      A regular expression search.
9722
9723
9724File: eintr.info,  Node: Complete forward-sentence,  Next: fwd-sentence while loops,  Up: forward-sentence
9725
9726Complete ‘forward-sentence’ function definition
9727-----------------------------------------------
9728
9729Here is the code for ‘forward-sentence’:
9730
9731     (defun forward-sentence (&optional arg)
9732       "Move forward to next end of sentence.  With argument, repeat.
9733     With negative argument, move backward repeatedly to start of sentence.
9734
9735     The variable `sentence-end' is a regular expression that matches ends of
9736     sentences.  Also, every paragraph boundary terminates sentences as well."
9737       (interactive "p")
9738       (or arg (setq arg 1))
9739       (let ((opoint (point))
9740             (sentence-end (sentence-end)))
9741         (while (< arg 0)
9742           (let ((pos (point))
9743                 (par-beg (save-excursion (start-of-paragraph-text) (point))))
9744            (if (and (re-search-backward sentence-end par-beg t)
9745                     (or (< (match-end 0) pos)
9746                         (re-search-backward sentence-end par-beg t)))
9747                (goto-char (match-end 0))
9748              (goto-char par-beg)))
9749           (setq arg (1+ arg)))
9750         (while (> arg 0)
9751           (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
9752            (if (re-search-forward sentence-end par-end t)
9753                (skip-chars-backward " \t\n")
9754              (goto-char par-end)))
9755           (setq arg (1- arg)))
9756         (constrain-to-field nil opoint t)))
9757
9758   The function looks long at first sight and it is best to look at its
9759skeleton first, and then its muscle.  The way to see the skeleton is to
9760look at the expressions that start in the left-most columns:
9761
9762     (defun forward-sentence (&optional arg)
9763       "DOCUMENTATION..."
9764       (interactive "p")
9765       (or arg (setq arg 1))
9766       (let ((opoint (point)) (sentence-end (sentence-end)))
9767         (while (< arg 0)
9768           (let ((pos (point))
9769                 (par-beg (save-excursion (start-of-paragraph-text) (point))))
9770            REST-OF-BODY-OF-WHILE-LOOP-WHEN-GOING-BACKWARDS
9771         (while (> arg 0)
9772           (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
9773            REST-OF-BODY-OF-WHILE-LOOP-WHEN-GOING-FORWARDS
9774         HANDLE-FORMS-AND-EQUIVALENT
9775
9776   This looks much simpler!  The function definition consists of
9777documentation, an ‘interactive’ expression, an ‘or’ expression, a ‘let’
9778expression, and ‘while’ loops.
9779
9780   Let’s look at each of these parts in turn.
9781
9782   We note that the documentation is thorough and understandable.
9783
9784   The function has an ‘interactive "p"’ declaration.  This means that
9785the processed prefix argument, if any, is passed to the function as its
9786argument.  (This will be a number.)  If the function is not passed an
9787argument (it is optional) then the argument ‘arg’ will be bound to 1.
9788
9789   When ‘forward-sentence’ is called non-interactively without an
9790argument, ‘arg’ is bound to ‘nil’.  The ‘or’ expression handles this.
9791What it does is either leave the value of ‘arg’ as it is, but only if
9792‘arg’ is bound to a value; or it sets the value of ‘arg’ to 1, in the
9793case when ‘arg’ is bound to ‘nil’.
9794
9795   Next is a ‘let’.  That specifies the values of two local variables,
9796‘opoint’ and ‘sentence-end’.  The local value of point, from before the
9797search, is used in the ‘constrain-to-field’ function which handles forms
9798and equivalents.  The ‘sentence-end’ variable is set by the
9799‘sentence-end’ function.
9800
9801
9802File: eintr.info,  Node: fwd-sentence while loops,  Next: fwd-sentence re-search,  Prev: Complete forward-sentence,  Up: forward-sentence
9803
9804The ‘while’ loops
9805-----------------
9806
9807Two ‘while’ loops follow.  The first ‘while’ has a true-or-false-test
9808that tests true if the prefix argument for ‘forward-sentence’ is a
9809negative number.  This is for going backwards.  The body of this loop is
9810similar to the body of the second ‘while’ clause, but it is not exactly
9811the same.  We will skip this ‘while’ loop and concentrate on the second
9812‘while’ loop.
9813
9814   The second ‘while’ loop is for moving point forward.  Its skeleton
9815looks like this:
9816
9817     (while (> arg 0)            ; true-or-false-test
9818       (let VARLIST
9819         (if (TRUE-OR-FALSE-TEST)
9820             THEN-PART
9821           ELSE-PART
9822       (setq arg (1- arg))))     ; while loop decrementer
9823
9824   The ‘while’ loop is of the decrementing kind.  (*Note A Loop with a
9825Decrementing Counter: Decrementing Loop.)  It has a true-or-false-test
9826that tests true so long as the counter (in this case, the variable
9827‘arg’) is greater than zero; and it has a decrementer that subtracts 1
9828from the value of the counter every time the loop repeats.
9829
9830   If no prefix argument is given to ‘forward-sentence’, which is the
9831most common way the command is used, this ‘while’ loop will run once,
9832since the value of ‘arg’ will be 1.
9833
9834   The body of the ‘while’ loop consists of a ‘let’ expression, which
9835creates and binds a local variable, and has, as its body, an ‘if’
9836expression.
9837
9838   The body of the ‘while’ loop looks like this:
9839
9840     (let ((par-end
9841            (save-excursion (end-of-paragraph-text) (point))))
9842       (if (re-search-forward sentence-end par-end t)
9843           (skip-chars-backward " \t\n")
9844         (goto-char par-end)))
9845
9846   The ‘let’ expression creates and binds the local variable ‘par-end’.
9847As we shall see, this local variable is designed to provide a bound or
9848limit to the regular expression search.  If the search fails to find a
9849proper sentence ending in the paragraph, it will stop on reaching the
9850end of the paragraph.
9851
9852   But first, let us examine how ‘par-end’ is bound to the value of the
9853end of the paragraph.  What happens is that the ‘let’ sets the value of
9854‘par-end’ to the value returned when the Lisp interpreter evaluates the
9855expression
9856
9857     (save-excursion (end-of-paragraph-text) (point))
9858
9859In this expression, ‘(end-of-paragraph-text)’ moves point to the end of
9860the paragraph, ‘(point)’ returns the value of point, and then
9861‘save-excursion’ restores point to its original position.  Thus, the
9862‘let’ binds ‘par-end’ to the value returned by the ‘save-excursion’
9863expression, which is the position of the end of the paragraph.  (The
9864‘end-of-paragraph-text’ function uses ‘forward-paragraph’, which we will
9865discuss shortly.)
9866
9867   Emacs next evaluates the body of the ‘let’, which is an ‘if’
9868expression that looks like this:
9869
9870     (if (re-search-forward sentence-end par-end t) ; if-part
9871         (skip-chars-backward " \t\n")              ; then-part
9872       (goto-char par-end)))                        ; else-part
9873
9874   The ‘if’ tests whether its first argument is true and if so,
9875evaluates its then-part; otherwise, the Emacs Lisp interpreter evaluates
9876the else-part.  The true-or-false-test of the ‘if’ expression is the
9877regular expression search.
9878
9879   It may seem odd to have what looks like the real work of the
9880‘forward-sentence’ function buried here, but this is a common way this
9881kind of operation is carried out in Lisp.
9882
9883
9884File: eintr.info,  Node: fwd-sentence re-search,  Prev: fwd-sentence while loops,  Up: forward-sentence
9885
9886The regular expression search
9887-----------------------------
9888
9889The ‘re-search-forward’ function searches for the end of the sentence,
9890that is, for the pattern defined by the ‘sentence-end’ regular
9891expression.  If the pattern is found—if the end of the sentence is
9892found—then the ‘re-search-forward’ function does two things:
9893
9894  1. The ‘re-search-forward’ function carries out a side effect, which
9895     is to move point to the end of the occurrence found.
9896
9897  2. The ‘re-search-forward’ function returns a value of true.  This is
9898     the value received by the ‘if’, and means that the search was
9899     successful.
9900
9901The side effect, the movement of point, is completed before the ‘if’
9902function is handed the value returned by the successful conclusion of
9903the search.
9904
9905   When the ‘if’ function receives the value of true from a successful
9906call to ‘re-search-forward’, the ‘if’ evaluates the then-part, which is
9907the expression ‘(skip-chars-backward " \t\n")’.  This expression moves
9908backwards over any blank spaces, tabs or carriage returns until a
9909printed character is found and then leaves point after the character.
9910Since point has already been moved to the end of the pattern that marks
9911the end of the sentence, this action leaves point right after the
9912closing printed character of the sentence, which is usually a period.
9913
9914   On the other hand, if the ‘re-search-forward’ function fails to find
9915a pattern marking the end of the sentence, the function returns false.
9916The false then causes the ‘if’ to evaluate its third argument, which is
9917‘(goto-char par-end)’: it moves point to the end of the paragraph.
9918
9919   (And if the text is in a form or equivalent, and point may not move
9920fully, then the ‘constrain-to-field’ function comes into play.)
9921
9922   Regular expression searches are exceptionally useful and the pattern
9923illustrated by ‘re-search-forward’, in which the search is the test of
9924an ‘if’ expression, is handy.  You will see or write code incorporating
9925this pattern often.
9926
9927
9928File: eintr.info,  Node: forward-paragraph,  Next: Regexp Review,  Prev: forward-sentence,  Up: Regexp Search
9929
993012.4 ‘forward-paragraph’: a Goldmine of Functions
9931=================================================
9932
9933The ‘forward-paragraph’ function moves point forward to the end of the
9934paragraph.  It is usually bound to ‘M-}’ and makes use of a number of
9935functions that are important in themselves, including ‘let*’,
9936‘match-beginning’, and ‘looking-at’.
9937
9938   The function definition for ‘forward-paragraph’ is considerably
9939longer than the function definition for ‘forward-sentence’ because it
9940works with a paragraph, each line of which may begin with a fill prefix.
9941
9942   A fill prefix consists of a string of characters that are repeated at
9943the beginning of each line.  For example, in Lisp code, it is a
9944convention to start each line of a paragraph-long comment with ‘;;; ’.
9945In Text mode, four blank spaces make up another common fill prefix,
9946creating an indented paragraph.  (*Note (emacs)Fill Prefix::, for more
9947information about fill prefixes.)
9948
9949   The existence of a fill prefix means that in addition to being able
9950to find the end of a paragraph whose lines begin on the left-most
9951column, the ‘forward-paragraph’ function must be able to find the end of
9952a paragraph when all or many of the lines in the buffer begin with the
9953fill prefix.
9954
9955   Moreover, it is sometimes practical to ignore a fill prefix that
9956exists, especially when blank lines separate paragraphs.  This is an
9957added complication.
9958
9959* Menu:
9960
9961* forward-paragraph in brief::  Key parts of the function definition.
9962* fwd-para let::                The ‘let*’ expression.
9963* fwd-para while::              The forward motion ‘while’ loop.
9964
9965
9966File: eintr.info,  Node: forward-paragraph in brief,  Next: fwd-para let,  Up: forward-paragraph
9967
9968Shortened ‘forward-paragraph’ function definition
9969-------------------------------------------------
9970
9971Rather than print all of the ‘forward-paragraph’ function, we will only
9972print parts of it.  Read without preparation, the function can be
9973daunting!
9974
9975   In outline, the function looks like this:
9976
9977     (defun forward-paragraph (&optional arg)
9978       "DOCUMENTATION..."
9979       (interactive "p")
9980       (or arg (setq arg 1))
9981       (let*
9982           VARLIST
9983         (while (and (< arg 0) (not (bobp)))     ; backward-moving-code
9984           ...
9985         (while (and (> arg 0) (not (eobp)))     ; forward-moving-code
9986           ...
9987
9988   The first parts of the function are routine: the function’s argument
9989list consists of one optional argument.  Documentation follows.
9990
9991   The lower case ‘p’ in the ‘interactive’ declaration means that the
9992processed prefix argument, if any, is passed to the function.  This will
9993be a number, and is the repeat count of how many paragraphs point will
9994move.  The ‘or’ expression in the next line handles the common case when
9995no argument is passed to the function, which occurs if the function is
9996called from other code rather than interactively.  This case was
9997described earlier.  (*Note The ‘forward-sentence’ function:
9998forward-sentence.)  Now we reach the end of the familiar part of this
9999function.
10000
10001
10002File: eintr.info,  Node: fwd-para let,  Next: fwd-para while,  Prev: forward-paragraph in brief,  Up: forward-paragraph
10003
10004The ‘let*’ expression
10005---------------------
10006
10007The next line of the ‘forward-paragraph’ function begins a ‘let*’
10008expression.  This is different from ‘let’.  The symbol is ‘let*’ not
10009‘let’.
10010
10011   The ‘let*’ special form is like ‘let’ except that Emacs sets each
10012variable in sequence, one after another, and variables in the latter
10013part of the varlist can make use of the values to which Emacs set
10014variables in the earlier part of the varlist.
10015
10016   (*note ‘save-excursion’ in ‘append-to-buffer’: append
10017save-excursion.)
10018
10019   In the ‘let*’ expression in this function, Emacs binds a total of
10020seven variables: ‘opoint’, ‘fill-prefix-regexp’, ‘parstart’, ‘parsep’,
10021‘sp-parstart’, ‘start’, and ‘found-start’.
10022
10023   The variable ‘parsep’ appears twice, first, to remove instances of
10024‘^’, and second, to handle fill prefixes.
10025
10026   The variable ‘opoint’ is just the value of ‘point’.  As you can
10027guess, it is used in a ‘constrain-to-field’ expression, just as in
10028‘forward-sentence’.
10029
10030   The variable ‘fill-prefix-regexp’ is set to the value returned by
10031evaluating the following list:
10032
10033     (and fill-prefix
10034          (not (equal fill-prefix ""))
10035          (not paragraph-ignore-fill-prefix)
10036          (regexp-quote fill-prefix))
10037
10038This is an expression whose first element is the ‘and’ special form.
10039
10040   As we learned earlier (*note The ‘kill-new’ function: kill-new
10041function.), the ‘and’ special form evaluates each of its arguments until
10042one of the arguments returns a value of ‘nil’, in which case the ‘and’
10043expression returns ‘nil’; however, if none of the arguments returns a
10044value of ‘nil’, the value resulting from evaluating the last argument is
10045returned.  (Since such a value is not ‘nil’, it is considered true in
10046Lisp.)  In other words, an ‘and’ expression returns a true value only if
10047all its arguments are true.
10048
10049   In this case, the variable ‘fill-prefix-regexp’ is bound to a
10050non-‘nil’ value only if the following four expressions produce a true
10051(i.e., a non-‘nil’) value when they are evaluated; otherwise,
10052‘fill-prefix-regexp’ is bound to ‘nil’.
10053
10054‘fill-prefix’
10055     When this variable is evaluated, the value of the fill prefix, if
10056     any, is returned.  If there is no fill prefix, this variable
10057     returns ‘nil’.
10058
10059‘(not (equal fill-prefix "")’
10060     This expression checks whether an existing fill prefix is an empty
10061     string, that is, a string with no characters in it.  An empty
10062     string is not a useful fill prefix.
10063
10064‘(not paragraph-ignore-fill-prefix)’
10065     This expression returns ‘nil’ if the variable
10066     ‘paragraph-ignore-fill-prefix’ has been turned on by being set to a
10067     true value such as ‘t’.
10068
10069‘(regexp-quote fill-prefix)’
10070     This is the last argument to the ‘and’ special form.  If all the
10071     arguments to the ‘and’ are true, the value resulting from
10072     evaluating this expression will be returned by the ‘and’ expression
10073     and bound to the variable ‘fill-prefix-regexp’,
10074
10075The result of evaluating this ‘and’ expression successfully is that
10076‘fill-prefix-regexp’ will be bound to the value of ‘fill-prefix’ as
10077modified by the ‘regexp-quote’ function.  What ‘regexp-quote’ does is
10078read a string and return a regular expression that will exactly match
10079the string and match nothing else.  This means that ‘fill-prefix-regexp’
10080will be set to a value that will exactly match the fill prefix if the
10081fill prefix exists.  Otherwise, the variable will be set to ‘nil’.
10082
10083   The next two local variables in the ‘let*’ expression are designed to
10084remove instances of ‘^’ from ‘parstart’ and ‘parsep’, the local
10085variables which indicate the paragraph start and the paragraph
10086separator.  The next expression sets ‘parsep’ again.  That is to handle
10087fill prefixes.
10088
10089   This is the setting that requires the definition call ‘let*’ rather
10090than ‘let’.  The true-or-false-test for the ‘if’ depends on whether the
10091variable ‘fill-prefix-regexp’ evaluates to ‘nil’ or some other value.
10092
10093   If ‘fill-prefix-regexp’ does not have a value, Emacs evaluates the
10094else-part of the ‘if’ expression and binds ‘parsep’ to its local value.
10095(‘parsep’ is a regular expression that matches what separates
10096paragraphs.)
10097
10098   But if ‘fill-prefix-regexp’ does have a value, Emacs evaluates the
10099then-part of the ‘if’ expression and binds ‘parsep’ to a regular
10100expression that includes the ‘fill-prefix-regexp’ as part of the
10101pattern.
10102
10103   Specifically, ‘parsep’ is set to the original value of the paragraph
10104separate regular expression concatenated with an alternative expression
10105that consists of the ‘fill-prefix-regexp’ followed by optional
10106whitespace to the end of the line.  The whitespace is defined by
10107‘"[ \t]*$"’.)  The ‘\\|’ defines this portion of the regexp as an
10108alternative to ‘parsep’.
10109
10110   According to a comment in the code, the next local variable,
10111‘sp-parstart’, is used for searching, and then the final two, ‘start’
10112and ‘found-start’, are set to ‘nil’.
10113
10114   Now we get into the body of the ‘let*’.  The first part of the body
10115of the ‘let*’ deals with the case when the function is given a negative
10116argument and is therefore moving backwards.  We will skip this section.
10117
10118
10119File: eintr.info,  Node: fwd-para while,  Prev: fwd-para let,  Up: forward-paragraph
10120
10121The forward motion ‘while’ loop
10122-------------------------------
10123
10124The second part of the body of the ‘let*’ deals with forward motion.  It
10125is a ‘while’ loop that repeats itself so long as the value of ‘arg’ is
10126greater than zero.  In the most common use of the function, the value of
10127the argument is 1, so the body of the ‘while’ loop is evaluated exactly
10128once, and the cursor moves forward one paragraph.
10129
10130   This part handles three situations: when point is between paragraphs,
10131when there is a fill prefix and when there is no fill prefix.
10132
10133   The ‘while’ loop looks like this:
10134
10135     ;; going forwards and not at the end of the buffer
10136     (while (and (> arg 0) (not (eobp)))
10137
10138       ;; between paragraphs
10139       ;; Move forward over separator lines...
10140       (while (and (not (eobp))
10141                   (progn (move-to-left-margin) (not (eobp)))
10142                   (looking-at parsep))
10143         (forward-line 1))
10144       ;;  This decrements the loop
10145       (unless (eobp) (setq arg (1- arg)))
10146       ;; ... and one more line.
10147       (forward-line 1)
10148
10149       (if fill-prefix-regexp
10150           ;; There is a fill prefix; it overrides parstart;
10151           ;; we go forward line by line
10152           (while (and (not (eobp))
10153                       (progn (move-to-left-margin) (not (eobp)))
10154                       (not (looking-at parsep))
10155                       (looking-at fill-prefix-regexp))
10156             (forward-line 1))
10157
10158         ;; There is no fill prefix;
10159         ;; we go forward character by character
10160         (while (and (re-search-forward sp-parstart nil 1)
10161                     (progn (setq start (match-beginning 0))
10162                            (goto-char start)
10163                            (not (eobp)))
10164                     (progn (move-to-left-margin)
10165                            (not (looking-at parsep)))
10166                     (or (not (looking-at parstart))
10167                         (and use-hard-newlines
10168                              (not (get-text-property (1- start) 'hard)))))
10169           (forward-char 1))
10170
10171         ;; and if there is no fill prefix and if we are not at the end,
10172         ;;     go to whatever was found in the regular expression search
10173         ;;     for sp-parstart
10174         (if (< (point) (point-max))
10175             (goto-char start))))
10176
10177   We can see that this is a decrementing counter ‘while’ loop, using
10178the expression ‘(setq arg (1- arg))’ as the decrementer.  That
10179expression is not far from the ‘while’, but is hidden in another Lisp
10180macro, an ‘unless’ macro.  Unless we are at the end of the buffer—that
10181is what the ‘eobp’ function determines; it is an abbreviation of ‘End Of
10182Buffer P’—we decrease the value of ‘arg’ by one.
10183
10184   (If we are at the end of the buffer, we cannot go forward any more
10185and the next loop of the ‘while’ expression will test false since the
10186test is an ‘and’ with ‘(not (eobp))’.  The ‘not’ function means exactly
10187as you expect; it is another name for ‘null’, a function that returns
10188true when its argument is false.)
10189
10190   Interestingly, the loop count is not decremented until we leave the
10191space between paragraphs, unless we come to the end of buffer or stop
10192seeing the local value of the paragraph separator.
10193
10194   That second ‘while’ also has a ‘(move-to-left-margin)’ expression.
10195The function is self-explanatory.  It is inside a ‘progn’ expression and
10196not the last element of its body, so it is only invoked for its side
10197effect, which is to move point to the left margin of the current line.
10198
10199   The ‘looking-at’ function is also self-explanatory; it returns true
10200if the text after point matches the regular expression given as its
10201argument.
10202
10203   The rest of the body of the loop looks difficult at first, but makes
10204sense as you come to understand it.
10205
10206   First consider what happens if there is a fill prefix:
10207
10208       (if fill-prefix-regexp
10209           ;; There is a fill prefix; it overrides parstart;
10210           ;; we go forward line by line
10211           (while (and (not (eobp))
10212                       (progn (move-to-left-margin) (not (eobp)))
10213                       (not (looking-at parsep))
10214                       (looking-at fill-prefix-regexp))
10215             (forward-line 1))
10216
10217This expression moves point forward line by line so long as four
10218conditions are true:
10219
10220  1. Point is not at the end of the buffer.
10221
10222  2. We can move to the left margin of the text and are not at the end
10223     of the buffer.
10224
10225  3. The text following point does not separate paragraphs.
10226
10227  4. The pattern following point is the fill prefix regular expression.
10228
10229   The last condition may be puzzling, until you remember that point was
10230moved to the beginning of the line early in the ‘forward-paragraph’
10231function.  This means that if the text has a fill prefix, the
10232‘looking-at’ function will see it.
10233
10234   Consider what happens when there is no fill prefix.
10235
10236         (while (and (re-search-forward sp-parstart nil 1)
10237                     (progn (setq start (match-beginning 0))
10238                            (goto-char start)
10239                            (not (eobp)))
10240                     (progn (move-to-left-margin)
10241                            (not (looking-at parsep)))
10242                     (or (not (looking-at parstart))
10243                         (and use-hard-newlines
10244                              (not (get-text-property (1- start) 'hard)))))
10245           (forward-char 1))
10246
10247This ‘while’ loop has us searching forward for ‘sp-parstart’, which is
10248the combination of possible whitespace with the local value of the start
10249of a paragraph or of a paragraph separator.  (The latter two are within
10250an expression starting ‘\(?:’ so that they are not referenced by the
10251‘match-beginning’ function.)
10252
10253   The two expressions,
10254
10255     (setq start (match-beginning 0))
10256     (goto-char start)
10257
10258mean go to the start of the text matched by the regular expression
10259search.
10260
10261   The ‘(match-beginning 0)’ expression is new.  It returns a number
10262specifying the location of the start of the text that was matched by the
10263last search.
10264
10265   The ‘match-beginning’ function is used here because of a
10266characteristic of a forward search: a successful forward search,
10267regardless of whether it is a plain search or a regular expression
10268search, moves point to the end of the text that is found.  In this case,
10269a successful search moves point to the end of the pattern for
10270‘sp-parstart’.
10271
10272   However, we want to put point at the end of the current paragraph,
10273not somewhere else.  Indeed, since the search possibly includes the
10274paragraph separator, point may end up at the beginning of the next one
10275unless we use an expression that includes ‘match-beginning’.
10276
10277   When given an argument of 0, ‘match-beginning’ returns the position
10278that is the start of the text matched by the most recent search.  In
10279this case, the most recent search looks for ‘sp-parstart’.  The
10280‘(match-beginning 0)’ expression returns the beginning position of that
10281pattern, rather than the end position of that pattern.
10282
10283   (Incidentally, when passed a positive number as an argument, the
10284‘match-beginning’ function returns the location of point at that
10285parenthesized expression in the last search unless that parenthesized
10286expression begins with ‘\(?:’.  I don’t know why ‘\(?:’ appears here
10287since the argument is 0.)
10288
10289   The last expression when there is no fill prefix is
10290
10291     (if (< (point) (point-max))
10292         (goto-char start))))
10293
10294This says that if there is no fill prefix and if we are not at the end,
10295point should move to the beginning of whatever was found by the regular
10296expression search for ‘sp-parstart’.
10297
10298   The full definition for the ‘forward-paragraph’ function not only
10299includes code for going forwards, but also code for going backwards.
10300
10301   If you are reading this inside of GNU Emacs and you want to see the
10302whole function, you can type ‘C-h f’ (‘describe-function’) and the name
10303of the function.  This gives you the function documentation and the name
10304of the library containing the function’s source.  Place point over the
10305name of the library and press the <RET> key; you will be taken directly
10306to the source.  (Be sure to install your sources!  Without them, you are
10307like a person who tries to drive a car with his eyes shut!)
10308
10309
10310File: eintr.info,  Node: Regexp Review,  Next: re-search Exercises,  Prev: forward-paragraph,  Up: Regexp Search
10311
1031212.5 Review
10313===========
10314
10315Here is a brief summary of some recently introduced functions.
10316
10317‘while’
10318     Repeatedly evaluate the body of the expression so long as the first
10319     element of the body tests true.  Then return ‘nil’.  (The
10320     expression is evaluated only for its side effects.)
10321
10322     For example:
10323
10324          (let ((foo 2))
10325            (while (> foo 0)
10326              (insert (format "foo is %d.\n" foo))
10327              (setq foo (1- foo))))
10328
10329               ⇒      foo is 2.
10330                       foo is 1.
10331                       nil
10332
10333     (The ‘insert’ function inserts its arguments at point; the ‘format’
10334     function returns a string formatted from its arguments the way
10335     ‘message’ formats its arguments; ‘\n’ produces a new line.)
10336
10337‘re-search-forward’
10338     Search for a pattern, and if the pattern is found, move point to
10339     rest just after it.
10340
10341     Takes four arguments, like ‘search-forward’:
10342
10343       1. A regular expression that specifies the pattern to search for.
10344          (Remember to put quotation marks around this argument!)
10345
10346       2. Optionally, the limit of the search.
10347
10348       3. Optionally, what to do if the search fails, return ‘nil’ or an
10349          error message.
10350
10351       4. Optionally, how many times to repeat the search; if negative,
10352          the search goes backwards.
10353
10354‘let*’
10355     Bind some variables locally to particular values, and then evaluate
10356     the remaining arguments, returning the value of the last one.
10357     While binding the local variables, use the local values of
10358     variables bound earlier, if any.
10359
10360     For example:
10361
10362          (let* ((foo 7)
10363                 (bar (* 3 foo)))
10364            (message "`bar' is %d." bar))
10365               ⇒ ‘bar’ is 21.
10366
10367‘match-beginning’
10368     Return the position of the start of the text found by the last
10369     regular expression search.
10370
10371‘looking-at’
10372     Return ‘t’ for true if the text after point matches the argument,
10373     which should be a regular expression.
10374
10375‘eobp’
10376     Return ‘t’ for true if point is at the end of the accessible part
10377     of a buffer.  The end of the accessible part is the end of the
10378     buffer if the buffer is not narrowed; it is the end of the narrowed
10379     part if the buffer is narrowed.
10380
10381
10382File: eintr.info,  Node: re-search Exercises,  Prev: Regexp Review,  Up: Regexp Search
10383
1038412.6 Exercises with ‘re-search-forward’
10385=======================================
10386
10387   • Write a function to search for a regular expression that matches
10388     two or more blank lines in sequence.
10389
10390   • Write a function to search for duplicated words, such as “the the”.
10391     *Note Syntax of Regular Expressions: (emacs)Regexps, for
10392     information on how to write a regexp (a regular expression) to
10393     match a string that is composed of two identical halves.  You can
10394     devise several regexps; some are better than others.  The function
10395     I use is described in an appendix, along with several regexps.
10396     *Note ‘the-the’ Duplicated Words Function: the-the.
10397
10398
10399File: eintr.info,  Node: Counting Words,  Next: Words in a defun,  Prev: Regexp Search,  Up: Top
10400
1040113 Counting via Repetition and Regexps
10402**************************************
10403
10404Repetition and regular expression searches are powerful tools that you
10405often use when you write code in Emacs Lisp.  This chapter illustrates
10406the use of regular expression searches through the construction of word
10407count commands using ‘while’ loops and recursion.
10408
10409* Menu:
10410
10411* Why Count Words::
10412* count-words-example::          Use a regexp, but find a problem.
10413* recursive-count-words::       Start with case of no words in region.
10414* Counting Exercise::
10415
10416
10417File: eintr.info,  Node: Why Count Words,  Next: count-words-example,  Up: Counting Words
10418
10419Counting words
10420==============
10421
10422The standard Emacs distribution contains functions for counting the
10423number of lines and words within a region.
10424
10425   Certain types of writing ask you to count words.  Thus, if you write
10426an essay, you may be limited to 800 words; if you write a novel, you may
10427discipline yourself to write 1000 words a day.  It seems odd, but for a
10428long time, Emacs lacked a word count command.  Perhaps people used Emacs
10429mostly for code or types of documentation that did not require word
10430counts; or perhaps they restricted themselves to the operating system
10431word count command, ‘wc’.  Alternatively, people may have followed the
10432publishers’ convention and computed a word count by dividing the number
10433of characters in a document by five.
10434
10435   There are many ways to implement a command to count words.  Here are
10436some examples, which you may wish to compare with the standard Emacs
10437command, ‘count-words-region’.
10438
10439
10440File: eintr.info,  Node: count-words-example,  Next: recursive-count-words,  Prev: Why Count Words,  Up: Counting Words
10441
1044213.1 The ‘count-words-example’ Function
10443=======================================
10444
10445A word count command could count words in a line, paragraph, region, or
10446buffer.  What should the command cover?  You could design the command to
10447count the number of words in a complete buffer.  However, the Emacs
10448tradition encourages flexibility—you may want to count words in just a
10449section, rather than all of a buffer.  So it makes more sense to design
10450the command to count the number of words in a region.  Once you have a
10451command to count words in a region, you can, if you wish, count words in
10452a whole buffer by marking it with ‘C-x h’ (‘mark-whole-buffer’).
10453
10454   Clearly, counting words is a repetitive act: starting from the
10455beginning of the region, you count the first word, then the second word,
10456then the third word, and so on, until you reach the end of the region.
10457This means that word counting is ideally suited to recursion or to a
10458‘while’ loop.
10459
10460* Menu:
10461
10462* Design count-words-example::  The definition using a ‘while’ loop.
10463* Whitespace Bug::              The Whitespace Bug in ‘count-words-example’.
10464
10465
10466File: eintr.info,  Node: Design count-words-example,  Next: Whitespace Bug,  Up: count-words-example
10467
10468Designing ‘count-words-example’
10469-------------------------------
10470
10471First, we will implement the word count command with a ‘while’ loop,
10472then with recursion.  The command will, of course, be interactive.
10473
10474   The template for an interactive function definition is, as always:
10475
10476     (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
10477       "DOCUMENTATION..."
10478       (INTERACTIVE-EXPRESSION...)
10479       BODY...)
10480
10481   What we need to do is fill in the slots.
10482
10483   The name of the function should be self-explanatory and similar to
10484the existing ‘count-lines-region’ name.  This makes the name easier to
10485remember.  ‘count-words-region’ is the obvious choice.  Since that name
10486is now used for the standard Emacs command to count words, we will name
10487our implementation ‘count-words-example’.
10488
10489   The function counts words within a region.  This means that the
10490argument list must contain symbols that are bound to the two positions,
10491the beginning and end of the region.  These two positions can be called
10492‘beginning’ and ‘end’ respectively.  The first line of the documentation
10493should be a single sentence, since that is all that is printed as
10494documentation by a command such as ‘apropos’.  The interactive
10495expression will be of the form ‘(interactive "r")’, since that will
10496cause Emacs to pass the beginning and end of the region to the
10497function’s argument list.  All this is routine.
10498
10499   The body of the function needs to be written to do three tasks:
10500first, to set up conditions under which the ‘while’ loop can count
10501words, second, to run the ‘while’ loop, and third, to send a message to
10502the user.
10503
10504   When a user calls ‘count-words-example’, point may be at the
10505beginning or the end of the region.  However, the counting process must
10506start at the beginning of the region.  This means we will want to put
10507point there if it is not already there.  Executing ‘(goto-char
10508beginning)’ ensures this.  Of course, we will want to return point to
10509its expected position when the function finishes its work.  For this
10510reason, the body must be enclosed in a ‘save-excursion’ expression.
10511
10512   The central part of the body of the function consists of a ‘while’
10513loop in which one expression jumps point forward word by word, and
10514another expression counts those jumps.  The true-or-false-test of the
10515‘while’ loop should test true so long as point should jump forward, and
10516false when point is at the end of the region.
10517
10518   We could use ‘(forward-word 1)’ as the expression for moving point
10519forward word by word, but it is easier to see what Emacs identifies as a
10520“word” if we use a regular expression search.
10521
10522   A regular expression search that finds the pattern for which it is
10523searching leaves point after the last character matched.  This means
10524that a succession of successful word searches will move point forward
10525word by word.
10526
10527   As a practical matter, we want the regular expression search to jump
10528over whitespace and punctuation between words as well as over the words
10529themselves.  A regexp that refuses to jump over interword whitespace
10530would never jump more than one word!  This means that the regexp should
10531include the whitespace and punctuation that follows a word, if any, as
10532well as the word itself.  (A word may end a buffer and not have any
10533following whitespace or punctuation, so that part of the regexp must be
10534optional.)
10535
10536   Thus, what we want for the regexp is a pattern defining one or more
10537word constituent characters followed, optionally, by one or more
10538characters that are not word constituents.  The regular expression for
10539this is:
10540
10541     \w+\W*
10542
10543The buffer’s syntax table determines which characters are and are not
10544word constituents.  For more information about syntax, *note Syntax
10545Tables: (elisp)Syntax Tables.
10546
10547   The search expression looks like this:
10548
10549     (re-search-forward "\\w+\\W*")
10550
10551(Note that paired backslashes precede the ‘w’ and ‘W’.  A single
10552backslash has special meaning to the Emacs Lisp interpreter.  It
10553indicates that the following character is interpreted differently than
10554usual.  For example, the two characters, ‘\n’, stand for ‘newline’,
10555rather than for a backslash followed by ‘n’.  Two backslashes in a row
10556stand for an ordinary, unspecial backslash, so Emacs Lisp interpreter
10557ends of seeing a single backslash followed by a letter.  So it discovers
10558the letter is special.)
10559
10560   We need a counter to count how many words there are; this variable
10561must first be set to 0 and then incremented each time Emacs goes around
10562the ‘while’ loop.  The incrementing expression is simply:
10563
10564     (setq count (1+ count))
10565
10566   Finally, we want to tell the user how many words there are in the
10567region.  The ‘message’ function is intended for presenting this kind of
10568information to the user.  The message has to be phrased so that it reads
10569properly regardless of how many words there are in the region: we don’t
10570want to say that “there are 1 words in the region”.  The conflict
10571between singular and plural is ungrammatical.  We can solve this problem
10572by using a conditional expression that evaluates different messages
10573depending on the number of words in the region.  There are three
10574possibilities: no words in the region, one word in the region, and more
10575than one word.  This means that the ‘cond’ special form is appropriate.
10576
10577   All this leads to the following function definition:
10578
10579     ;;; First version; has bugs!
10580     (defun count-words-example (beginning end)
10581       "Print number of words in the region.
10582     Words are defined as at least one word-constituent
10583     character followed by at least one character that
10584     is not a word-constituent.  The buffer's syntax
10585     table determines which characters these are."
10586       (interactive "r")
10587       (message "Counting words in region ... ")
10588
10589     ;;; 1. Set up appropriate conditions.
10590       (save-excursion
10591         (goto-char beginning)
10592         (let ((count 0))
10593
10594     ;;; 2. Run the while loop.
10595           (while (< (point) end)
10596             (re-search-forward "\\w+\\W*")
10597             (setq count (1+ count)))
10598
10599     ;;; 3. Send a message to the user.
10600           (cond ((zerop count)
10601                  (message
10602                   "The region does NOT have any words."))
10603                 ((= 1 count)
10604                  (message
10605                   "The region has 1 word."))
10606                 (t
10607                  (message
10608                   "The region has %d words." count))))))
10609
10610As written, the function works, but not in all circumstances.
10611
10612
10613File: eintr.info,  Node: Whitespace Bug,  Prev: Design count-words-example,  Up: count-words-example
10614
1061513.1.1 The Whitespace Bug in ‘count-words-example’
10616--------------------------------------------------
10617
10618The ‘count-words-example’ command described in the preceding section has
10619two bugs, or rather, one bug with two manifestations.  First, if you
10620mark a region containing only whitespace in the middle of some text, the
10621‘count-words-example’ command tells you that the region contains one
10622word!  Second, if you mark a region containing only whitespace at the
10623end of the buffer or the accessible portion of a narrowed buffer, the
10624command displays an error message that looks like this:
10625
10626     Search failed: "\\w+\\W*"
10627
10628   If you are reading this in Info in GNU Emacs, you can test for these
10629bugs yourself.
10630
10631   First, evaluate the function in the usual manner to install it.  Here
10632is a copy of the definition.  Place your cursor after the closing
10633parenthesis and type ‘C-x C-e’ to install it.
10634
10635     ;; First version; has bugs!
10636     (defun count-words-example (beginning end)
10637       "Print number of words in the region.
10638     Words are defined as at least one word-constituent character followed
10639     by at least one character that is not a word-constituent.  The buffer's
10640     syntax table determines which characters these are."
10641       (interactive "r")
10642       (message "Counting words in region ... ")
10643
10644     ;;; 1. Set up appropriate conditions.
10645       (save-excursion
10646         (goto-char beginning)
10647         (let ((count 0))
10648
10649     ;;; 2. Run the while loop.
10650           (while (< (point) end)
10651             (re-search-forward "\\w+\\W*")
10652             (setq count (1+ count)))
10653
10654     ;;; 3. Send a message to the user.
10655           (cond ((zerop count)
10656                  (message "The region does NOT have any words."))
10657                 ((= 1 count) (message "The region has 1 word."))
10658                 (t (message "The region has %d words." count))))))
10659
10660   If you wish, you can also install this keybinding by evaluating it:
10661
10662     (global-set-key "\C-c=" 'count-words-example)
10663
10664   To conduct the first test, set mark and point to the beginning and
10665end of the following line and then type ‘C-c =’ (or ‘M-x
10666count-words-example’ if you have not bound ‘C-c =’):
10667
10668         one   two  three
10669
10670Emacs will tell you, correctly, that the region has three words.
10671
10672   Repeat the test, but place mark at the beginning of the line and
10673place point just _before_ the word ‘one’.  Again type the command ‘C-c
10674=’ (or ‘M-x count-words-example’).  Emacs should tell you that the
10675region has no words, since it is composed only of the whitespace at the
10676beginning of the line.  But instead Emacs tells you that the region has
10677one word!
10678
10679   For the third test, copy the sample line to the end of the
10680‘*scratch*’ buffer and then type several spaces at the end of the line.
10681Place mark right after the word ‘three’ and point at the end of line.
10682(The end of the line will be the end of the buffer.)  Type ‘C-c =’ (or
10683‘M-x count-words-example’) as you did before.  Again, Emacs should tell
10684you that the region has no words, since it is composed only of the
10685whitespace at the end of the line.  Instead, Emacs displays an error
10686message saying ‘Search failed’.
10687
10688   The two bugs stem from the same problem.
10689
10690   Consider the first manifestation of the bug, in which the command
10691tells you that the whitespace at the beginning of the line contains one
10692word.  What happens is this: The ‘M-x count-words-example’ command moves
10693point to the beginning of the region.  The ‘while’ tests whether the
10694value of point is smaller than the value of ‘end’, which it is.
10695Consequently, the regular expression search looks for and finds the
10696first word.  It leaves point after the word.  ‘count’ is set to one.
10697The ‘while’ loop repeats; but this time the value of point is larger
10698than the value of ‘end’, the loop is exited; and the function displays a
10699message saying the number of words in the region is one.  In brief, the
10700regular expression search looks for and finds the word even though it is
10701outside the marked region.
10702
10703   In the second manifestation of the bug, the region is whitespace at
10704the end of the buffer.  Emacs says ‘Search failed’.  What happens is
10705that the true-or-false-test in the ‘while’ loop tests true, so the
10706search expression is executed.  But since there are no more words in the
10707buffer, the search fails.
10708
10709   In both manifestations of the bug, the search extends or attempts to
10710extend outside of the region.
10711
10712   The solution is to limit the search to the region—this is a fairly
10713simple action, but as you may have come to expect, it is not quite as
10714simple as you might think.
10715
10716   As we have seen, the ‘re-search-forward’ function takes a search
10717pattern as its first argument.  But in addition to this first, mandatory
10718argument, it accepts three optional arguments.  The optional second
10719argument bounds the search.  The optional third argument, if ‘t’, causes
10720the function to return ‘nil’ rather than signal an error if the search
10721fails.  The optional fourth argument is a repeat count.  (In Emacs, you
10722can see a function’s documentation by typing ‘C-h f’, the name of the
10723function, and then <RET>.)
10724
10725   In the ‘count-words-example’ definition, the value of the end of the
10726region is held by the variable ‘end’ which is passed as an argument to
10727the function.  Thus, we can add ‘end’ as an argument to the regular
10728expression search expression:
10729
10730     (re-search-forward "\\w+\\W*" end)
10731
10732   However, if you make only this change to the ‘count-words-example’
10733definition and then test the new version of the definition on a stretch
10734of whitespace, you will receive an error message saying ‘Search failed’.
10735
10736   What happens is this: the search is limited to the region, and fails
10737as you expect because there are no word-constituent characters in the
10738region.  Since it fails, we receive an error message.  But we do not
10739want to receive an error message in this case; we want to receive the
10740message “The region does NOT have any words.”
10741
10742   The solution to this problem is to provide ‘re-search-forward’ with a
10743third argument of ‘t’, which causes the function to return ‘nil’ rather
10744than signal an error if the search fails.
10745
10746   However, if you make this change and try it, you will see the message
10747“Counting words in region ...  ” and ... you will keep on seeing that
10748message ..., until you type ‘C-g’ (‘keyboard-quit’).
10749
10750   Here is what happens: the search is limited to the region, as before,
10751and it fails because there are no word-constituent characters in the
10752region, as expected.  Consequently, the ‘re-search-forward’ expression
10753returns ‘nil’.  It does nothing else.  In particular, it does not move
10754point, which it does as a side effect if it finds the search target.
10755After the ‘re-search-forward’ expression returns ‘nil’, the next
10756expression in the ‘while’ loop is evaluated.  This expression increments
10757the count.  Then the loop repeats.  The true-or-false-test tests true
10758because the value of point is still less than the value of end, since
10759the ‘re-search-forward’ expression did not move point.  ... and the
10760cycle repeats ...
10761
10762   The ‘count-words-example’ definition requires yet another
10763modification, to cause the true-or-false-test of the ‘while’ loop to
10764test false if the search fails.  Put another way, there are two
10765conditions that must be satisfied in the true-or-false-test before the
10766word count variable is incremented: point must still be within the
10767region and the search expression must have found a word to count.
10768
10769   Since both the first condition and the second condition must be true
10770together, the two expressions, the region test and the search
10771expression, can be joined with an ‘and’ special form and embedded in the
10772‘while’ loop as the true-or-false-test, like this:
10773
10774     (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
10775
10776(*Note The ‘kill-new’ function: kill-new function, for information about
10777‘and’.)
10778
10779   The ‘re-search-forward’ expression returns ‘t’ if the search succeeds
10780and as a side effect moves point.  Consequently, as words are found,
10781point is moved through the region.  When the search expression fails to
10782find another word, or when point reaches the end of the region, the
10783true-or-false-test tests false, the ‘while’ loop exits, and the
10784‘count-words-example’ function displays one or other of its messages.
10785
10786   After incorporating these final changes, the ‘count-words-example’
10787works without bugs (or at least, without bugs that I have found!).  Here
10788is what it looks like:
10789
10790     ;;; Final version: while
10791     (defun count-words-example (beginning end)
10792       "Print number of words in the region."
10793       (interactive "r")
10794       (message "Counting words in region ... ")
10795
10796     ;;; 1. Set up appropriate conditions.
10797       (save-excursion
10798         (let ((count 0))
10799           (goto-char beginning)
10800
10801     ;;; 2. Run the while loop.
10802           (while (and (< (point) end)
10803                       (re-search-forward "\\w+\\W*" end t))
10804             (setq count (1+ count)))
10805
10806     ;;; 3. Send a message to the user.
10807           (cond ((zerop count)
10808                  (message
10809                   "The region does NOT have any words."))
10810                 ((= 1 count)
10811                  (message
10812                   "The region has 1 word."))
10813                 (t
10814                  (message
10815                   "The region has %d words." count))))))
10816
10817
10818File: eintr.info,  Node: recursive-count-words,  Next: Counting Exercise,  Prev: count-words-example,  Up: Counting Words
10819
1082013.2 Count Words Recursively
10821============================
10822
10823You can write the function for counting words recursively as well as
10824with a ‘while’ loop.  Let’s see how this is done.
10825
10826   First, we need to recognize that the ‘count-words-example’ function
10827has three jobs: it sets up the appropriate conditions for counting to
10828occur; it counts the words in the region; and it sends a message to the
10829user telling how many words there are.
10830
10831   If we write a single recursive function to do everything, we will
10832receive a message for every recursive call.  If the region contains 13
10833words, we will receive thirteen messages, one right after the other.  We
10834don’t want this!  Instead, we must write two functions to do the job,
10835one of which (the recursive function) will be used inside of the other.
10836One function will set up the conditions and display the message; the
10837other will return the word count.
10838
10839   Let us start with the function that causes the message to be
10840displayed.  We can continue to call this ‘count-words-example’.
10841
10842   This is the function that the user will call.  It will be
10843interactive.  Indeed, it will be similar to our previous versions of
10844this function, except that it will call ‘recursive-count-words’ to
10845determine how many words are in the region.
10846
10847   We can readily construct a template for this function, based on our
10848previous versions:
10849
10850     ;; Recursive version; uses regular expression search
10851     (defun count-words-example (beginning end)
10852       "DOCUMENTATION..."
10853       (INTERACTIVE-EXPRESSION...)
10854
10855     ;;; 1. Set up appropriate conditions.
10856       (EXPLANATORY MESSAGE)
10857       (SET-UP FUNCTIONS...
10858
10859     ;;; 2. Count the words.
10860         RECURSIVE CALL
10861
10862     ;;; 3. Send a message to the user.
10863         MESSAGE PROVIDING WORD COUNT))
10864
10865   The definition looks straightforward, except that somehow the count
10866returned by the recursive call must be passed to the message displaying
10867the word count.  A little thought suggests that this can be done by
10868making use of a ‘let’ expression: we can bind a variable in the varlist
10869of a ‘let’ expression to the number of words in the region, as returned
10870by the recursive call; and then the ‘cond’ expression, using binding,
10871can display the value to the user.
10872
10873   Often, one thinks of the binding within a ‘let’ expression as somehow
10874secondary to the primary work of a function.  But in this case, what you
10875might consider the primary job of the function, counting words, is done
10876within the ‘let’ expression.
10877
10878   Using ‘let’, the function definition looks like this:
10879
10880     (defun count-words-example (beginning end)
10881       "Print number of words in the region."
10882       (interactive "r")
10883
10884     ;;; 1. Set up appropriate conditions.
10885       (message "Counting words in region ... ")
10886       (save-excursion
10887         (goto-char beginning)
10888
10889     ;;; 2. Count the words.
10890         (let ((count (recursive-count-words end)))
10891
10892     ;;; 3. Send a message to the user.
10893           (cond ((zerop count)
10894                  (message
10895                   "The region does NOT have any words."))
10896                 ((= 1 count)
10897                  (message
10898                   "The region has 1 word."))
10899                 (t
10900                  (message
10901                   "The region has %d words." count))))))
10902
10903   Next, we need to write the recursive counting function.
10904
10905   A recursive function has at least three parts: the do-again-test, the
10906next-step-expression, and the recursive call.
10907
10908   The do-again-test determines whether the function will or will not be
10909called again.  Since we are counting words in a region and can use a
10910function that moves point forward for every word, the do-again-test can
10911check whether point is still within the region.  The do-again-test
10912should find the value of point and determine whether point is before,
10913at, or after the value of the end of the region.  We can use the ‘point’
10914function to locate point.  Clearly, we must pass the value of the end of
10915the region to the recursive counting function as an argument.
10916
10917   In addition, the do-again-test should also test whether the search
10918finds a word.  If it does not, the function should not call itself
10919again.
10920
10921   The next-step-expression changes a value so that when the recursive
10922function is supposed to stop calling itself, it stops.  More precisely,
10923the next-step-expression changes a value so that at the right time, the
10924do-again-test stops the recursive function from calling itself again.
10925In this case, the next-step-expression can be the expression that moves
10926point forward, word by word.
10927
10928   The third part of a recursive function is the recursive call.
10929
10930   Somewhere, we also need a part that does the work of the function, a
10931part that does the counting.  A vital part!
10932
10933   But already, we have an outline of the recursive counting function:
10934
10935     (defun recursive-count-words (region-end)
10936       "DOCUMENTATION..."
10937        DO-AGAIN-TEST
10938        NEXT-STEP-EXPRESSION
10939        RECURSIVE CALL)
10940
10941   Now we need to fill in the slots.  Let’s start with the simplest
10942cases first: if point is at or beyond the end of the region, there
10943cannot be any words in the region, so the function should return zero.
10944Likewise, if the search fails, there are no words to count, so the
10945function should return zero.
10946
10947   On the other hand, if point is within the region and the search
10948succeeds, the function should call itself again.
10949
10950   Thus, the do-again-test should look like this:
10951
10952     (and (< (point) region-end)
10953          (re-search-forward "\\w+\\W*" region-end t))
10954
10955   Note that the search expression is part of the do-again-test—the
10956function returns ‘t’ if its search succeeds and ‘nil’ if it fails.
10957(*Note The Whitespace Bug in ‘count-words-example’: Whitespace Bug, for
10958an explanation of how ‘re-search-forward’ works.)
10959
10960   The do-again-test is the true-or-false test of an ‘if’ clause.
10961Clearly, if the do-again-test succeeds, the then-part of the ‘if’ clause
10962should call the function again; but if it fails, the else-part should
10963return zero since either point is outside the region or the search
10964failed because there were no words to find.
10965
10966   But before considering the recursive call, we need to consider the
10967next-step-expression.  What is it?  Interestingly, it is the search part
10968of the do-again-test.
10969
10970   In addition to returning ‘t’ or ‘nil’ for the do-again-test,
10971‘re-search-forward’ moves point forward as a side effect of a successful
10972search.  This is the action that changes the value of point so that the
10973recursive function stops calling itself when point completes its
10974movement through the region.  Consequently, the ‘re-search-forward’
10975expression is the next-step-expression.
10976
10977   In outline, then, the body of the ‘recursive-count-words’ function
10978looks like this:
10979
10980     (if DO-AGAIN-TEST-AND-NEXT-STEP-COMBINED
10981         ;; then
10982         RECURSIVE-CALL-RETURNING-COUNT
10983       ;; else
10984       RETURN-ZERO)
10985
10986   How to incorporate the mechanism that counts?
10987
10988   If you are not used to writing recursive functions, a question like
10989this can be troublesome.  But it can and should be approached
10990systematically.
10991
10992   We know that the counting mechanism should be associated in some way
10993with the recursive call.  Indeed, since the next-step-expression moves
10994point forward by one word, and since a recursive call is made for each
10995word, the counting mechanism must be an expression that adds one to the
10996value returned by a call to ‘recursive-count-words’.
10997
10998   Consider several cases:
10999
11000   • If there are two words in the region, the function should return a
11001     value resulting from adding one to the value returned when it
11002     counts the first word, plus the number returned when it counts the
11003     remaining words in the region, which in this case is one.
11004
11005   • If there is one word in the region, the function should return a
11006     value resulting from adding one to the value returned when it
11007     counts that word, plus the number returned when it counts the
11008     remaining words in the region, which in this case is zero.
11009
11010   • If there are no words in the region, the function should return
11011     zero.
11012
11013   From the sketch we can see that the else-part of the ‘if’ returns
11014zero for the case of no words.  This means that the then-part of the
11015‘if’ must return a value resulting from adding one to the value returned
11016from a count of the remaining words.
11017
11018   The expression will look like this, where ‘1+’ is a function that
11019adds one to its argument.
11020
11021     (1+ (recursive-count-words region-end))
11022
11023   The whole ‘recursive-count-words’ function will then look like this:
11024
11025     (defun recursive-count-words (region-end)
11026       "DOCUMENTATION..."
11027
11028     ;;; 1. do-again-test
11029       (if (and (< (point) region-end)
11030                (re-search-forward "\\w+\\W*" region-end t))
11031
11032     ;;; 2. then-part: the recursive call
11033           (1+ (recursive-count-words region-end))
11034
11035     ;;; 3. else-part
11036         0))
11037
11038   Let’s examine how this works:
11039
11040   If there are no words in the region, the else part of the ‘if’
11041expression is evaluated and consequently the function returns zero.
11042
11043   If there is one word in the region, the value of point is less than
11044the value of ‘region-end’ and the search succeeds.  In this case, the
11045true-or-false-test of the ‘if’ expression tests true, and the then-part
11046of the ‘if’ expression is evaluated.  The counting expression is
11047evaluated.  This expression returns a value (which will be the value
11048returned by the whole function) that is the sum of one added to the
11049value returned by a recursive call.
11050
11051   Meanwhile, the next-step-expression has caused point to jump over the
11052first (and in this case only) word in the region.  This means that when
11053‘(recursive-count-words region-end)’ is evaluated a second time, as a
11054result of the recursive call, the value of point will be equal to or
11055greater than the value of region end.  So this time,
11056‘recursive-count-words’ will return zero.  The zero will be added to
11057one, and the original evaluation of ‘recursive-count-words’ will return
11058one plus zero, which is one, which is the correct amount.
11059
11060   Clearly, if there are two words in the region, the first call to
11061‘recursive-count-words’ returns one added to the value returned by
11062calling ‘recursive-count-words’ on a region containing the remaining
11063word—that is, it adds one to one, producing two, which is the correct
11064amount.
11065
11066   Similarly, if there are three words in the region, the first call to
11067‘recursive-count-words’ returns one added to the value returned by
11068calling ‘recursive-count-words’ on a region containing the remaining two
11069words—and so on and so on.
11070
11071With full documentation the two functions look like this:
11072
11073The recursive function:
11074
11075     (defun recursive-count-words (region-end)
11076       "Number of words between point and REGION-END."
11077
11078     ;;; 1. do-again-test
11079       (if (and (< (point) region-end)
11080                (re-search-forward "\\w+\\W*" region-end t))
11081
11082     ;;; 2. then-part: the recursive call
11083           (1+ (recursive-count-words region-end))
11084
11085     ;;; 3. else-part
11086         0))
11087
11088The wrapper:
11089
11090     ;;; Recursive version
11091     (defun count-words-example (beginning end)
11092       "Print number of words in the region.
11093
11094     Words are defined as at least one word-constituent
11095     character followed by at least one character that is
11096     not a word-constituent.  The buffer's syntax table
11097     determines which characters these are."
11098       (interactive "r")
11099       (message "Counting words in region ... ")
11100       (save-excursion
11101         (goto-char beginning)
11102         (let ((count (recursive-count-words end)))
11103           (cond ((zerop count)
11104                  (message
11105                   "The region does NOT have any words."))
11106                 ((= 1 count)
11107                  (message "The region has 1 word."))
11108                 (t
11109                  (message
11110                   "The region has %d words." count))))))
11111
11112
11113File: eintr.info,  Node: Counting Exercise,  Prev: recursive-count-words,  Up: Counting Words
11114
1111513.3 Exercise: Counting Punctuation
11116===================================
11117
11118Using a ‘while’ loop, write a function to count the number of
11119punctuation marks in a region—period, comma, semicolon, colon,
11120exclamation mark, and question mark.  Do the same using recursion.
11121
11122
11123File: eintr.info,  Node: Words in a defun,  Next: Readying a Graph,  Prev: Counting Words,  Up: Top
11124
1112514 Counting Words in a ‘defun’
11126******************************
11127
11128Our next project is to count the number of words in a function
11129definition.  Clearly, this can be done using some variant of
11130‘count-words-example’.  *Note Counting via Repetition and Regexps:
11131Counting Words.  If we are just going to count the words in one
11132definition, it is easy enough to mark the definition with the ‘C-M-h’
11133(‘mark-defun’) command, and then call ‘count-words-example’.
11134
11135   However, I am more ambitious: I want to count the words and symbols
11136in every definition in the Emacs sources and then print a graph that
11137shows how many functions there are of each length: how many contain 40
11138to 49 words or symbols, how many contain 50 to 59 words or symbols, and
11139so on.  I have often been curious how long a typical function is, and
11140this will tell.
11141
11142* Menu:
11143
11144* Divide and Conquer::
11145* Words and Symbols::           What to count?
11146* Syntax::                      What constitutes a word or symbol?
11147* count-words-in-defun::        Very like ‘count-words-example’.
11148* Several defuns::              Counting several defuns in a file.
11149* Find a File::                 Do you want to look at a file?
11150* lengths-list-file::           A list of the lengths of many definitions.
11151* Several files::               Counting in definitions in different files.
11152* Several files recursively::   Recursively counting in different files.
11153* Prepare the data::            Prepare the data for display in a graph.
11154
11155
11156File: eintr.info,  Node: Divide and Conquer,  Next: Words and Symbols,  Up: Words in a defun
11157
11158Divide and Conquer
11159==================
11160
11161Described in one phrase, the histogram project is daunting; but divided
11162into numerous small steps, each of which we can take one at a time, the
11163project becomes less fearsome.  Let us consider what the steps must be:
11164
11165   • First, write a function to count the words in one definition.  This
11166     includes the problem of handling symbols as well as words.
11167
11168   • Second, write a function to list the number of words in each
11169     function in a file.  This function can use the
11170     ‘count-words-in-defun’ function.
11171
11172   • Third, write a function to list the number of words in each
11173     function in each of several files.  This entails automatically
11174     finding the various files, switching to them, and counting the
11175     words in the definitions within them.
11176
11177   • Fourth, write a function to convert the list of numbers that we
11178     created in step three to a form that will be suitable for printing
11179     as a graph.
11180
11181   • Fifth, write a function to print the results as a graph.
11182
11183   This is quite a project!  But if we take each step slowly, it will
11184not be difficult.
11185
11186
11187File: eintr.info,  Node: Words and Symbols,  Next: Syntax,  Prev: Divide and Conquer,  Up: Words in a defun
11188
1118914.1 What to Count?
11190===================
11191
11192When we first start thinking about how to count the words in a function
11193definition, the first question is (or ought to be) what are we going to
11194count?  When we speak of “words” with respect to a Lisp function
11195definition, we are actually speaking, in large part, of symbols.  For
11196example, the following ‘multiply-by-seven’ function contains the five
11197symbols ‘defun’, ‘multiply-by-seven’, ‘number’, ‘*’, and ‘7’.  In
11198addition, in the documentation string, it contains the four words
11199‘Multiply’, ‘NUMBER’, ‘by’, and ‘seven’.  The symbol ‘number’ is
11200repeated, so the definition contains a total of ten words and symbols.
11201
11202     (defun multiply-by-seven (number)
11203       "Multiply NUMBER by seven."
11204       (* 7 number))
11205
11206However, if we mark the ‘multiply-by-seven’ definition with ‘C-M-h’
11207(‘mark-defun’), and then call ‘count-words-example’ on it, we will find
11208that ‘count-words-example’ claims the definition has eleven words, not
11209ten!  Something is wrong!
11210
11211   The problem is twofold: ‘count-words-example’ does not count the ‘*’
11212as a word, and it counts the single symbol, ‘multiply-by-seven’, as
11213containing three words.  The hyphens are treated as if they were
11214interword spaces rather than intraword connectors: ‘multiply-by-seven’
11215is counted as if it were written ‘multiply by seven’.
11216
11217   The cause of this confusion is the regular expression search within
11218the ‘count-words-example’ definition that moves point forward word by
11219word.  In the canonical version of ‘count-words-example’, the regexp is:
11220
11221     "\\w+\\W*"
11222
11223This regular expression is a pattern defining one or more word
11224constituent characters possibly followed by one or more characters that
11225are not word constituents.  What is meant by “word constituent
11226characters” brings us to the issue of syntax, which is worth a section
11227of its own.
11228
11229
11230File: eintr.info,  Node: Syntax,  Next: count-words-in-defun,  Prev: Words and Symbols,  Up: Words in a defun
11231
1123214.2 What Constitutes a Word or Symbol?
11233=======================================
11234
11235Emacs treats different characters as belonging to different “syntax
11236categories”.  For example, the regular expression, ‘\\w+’, is a pattern
11237specifying one or more _word constituent_ characters.  Word constituent
11238characters are members of one syntax category.  Other syntax categories
11239include the class of punctuation characters, such as the period and the
11240comma, and the class of whitespace characters, such as the blank space
11241and the tab character.  (For more information, *note Syntax Tables:
11242(elisp)Syntax Tables.)
11243
11244   Syntax tables specify which characters belong to which categories.
11245Usually, a hyphen is not specified as a word constituent character.
11246Instead, it is specified as being in the class of characters that are
11247part of symbol names but not words.  This means that the
11248‘count-words-example’ function treats it in the same way it treats an
11249interword white space, which is why ‘count-words-example’ counts
11250‘multiply-by-seven’ as three words.
11251
11252   There are two ways to cause Emacs to count ‘multiply-by-seven’ as one
11253symbol: modify the syntax table or modify the regular expression.
11254
11255   We could redefine a hyphen as a word constituent character by
11256modifying the syntax table that Emacs keeps for each mode.  This action
11257would serve our purpose, except that a hyphen is merely the most common
11258character within symbols that is not typically a word constituent
11259character; there are others, too.
11260
11261   Alternatively, we can redefine the regexp used in the
11262‘count-words-example’ definition so as to include symbols.  This
11263procedure has the merit of clarity, but the task is a little tricky.
11264
11265   The first part is simple enough: the pattern must match at least one
11266character that is a word or symbol constituent.  Thus:
11267
11268     "\\(\\w\\|\\s_\\)+"
11269
11270The ‘\\(’ is the first part of the grouping construct that includes the
11271‘\\w’ and the ‘\\s_’ as alternatives, separated by the ‘\\|’.  The ‘\\w’
11272matches any word-constituent character and the ‘\\s_’ matches any
11273character that is part of a symbol name but not a word-constituent
11274character.  The ‘+’ following the group indicates that the word or
11275symbol constituent characters must be matched at least once.
11276
11277   However, the second part of the regexp is more difficult to design.
11278What we want is to follow the first part with optionally one or more
11279characters that are not constituents of a word or symbol.  At first, I
11280thought I could define this with the following:
11281
11282     "\\(\\W\\|\\S_\\)*"
11283
11284The upper case ‘W’ and ‘S’ match characters that are _not_ word or
11285symbol constituents.  Unfortunately, this expression matches any
11286character that is either not a word constituent or not a symbol
11287constituent.  This matches any character!
11288
11289   I then noticed that every word or symbol in my test region was
11290followed by white space (blank space, tab, or newline).  So I tried
11291placing a pattern to match one or more blank spaces after the pattern
11292for one or more word or symbol constituents.  This failed, too.  Words
11293and symbols are often separated by whitespace, but in actual code
11294parentheses may follow symbols and punctuation may follow words.  So
11295finally, I designed a pattern in which the word or symbol constituents
11296are followed optionally by characters that are not white space and then
11297followed optionally by white space.
11298
11299   Here is the full regular expression:
11300
11301     "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
11302
11303
11304File: eintr.info,  Node: count-words-in-defun,  Next: Several defuns,  Prev: Syntax,  Up: Words in a defun
11305
1130614.3 The ‘count-words-in-defun’ Function
11307========================================
11308
11309We have seen that there are several ways to write a ‘count-words-region’
11310function.  To write a ‘count-words-in-defun’, we need merely adapt one
11311of these versions.
11312
11313   The version that uses a ‘while’ loop is easy to understand, so I am
11314going to adapt that.  Because ‘count-words-in-defun’ will be part of a
11315more complex program, it need not be interactive and it need not display
11316a message but just return the count.  These considerations simplify the
11317definition a little.
11318
11319   On the other hand, ‘count-words-in-defun’ will be used within a
11320buffer that contains function definitions.  Consequently, it is
11321reasonable to ask that the function determine whether it is called when
11322point is within a function definition, and if it is, to return the count
11323for that definition.  This adds complexity to the definition, but saves
11324us from needing to pass arguments to the function.
11325
11326   These considerations lead us to prepare the following template:
11327
11328     (defun count-words-in-defun ()
11329       "DOCUMENTATION..."
11330       (SET UP...
11331          (WHILE LOOP...)
11332        RETURN COUNT)
11333
11334As usual, our job is to fill in the slots.
11335
11336   First, the set up.
11337
11338   We are presuming that this function will be called within a buffer
11339containing function definitions.  Point will either be within a function
11340definition or not.  For ‘count-words-in-defun’ to work, point must move
11341to the beginning of the definition, a counter must start at zero, and
11342the counting loop must stop when point reaches the end of the
11343definition.
11344
11345   The ‘beginning-of-defun’ function searches backwards for an opening
11346delimiter such as a ‘(’ at the beginning of a line, and moves point to
11347that position, or else to the limit of the search.  In practice, this
11348means that ‘beginning-of-defun’ moves point to the beginning of an
11349enclosing or preceding function definition, or else to the beginning of
11350the buffer.  We can use ‘beginning-of-defun’ to place point where we
11351wish to start.
11352
11353   The ‘while’ loop requires a counter to keep track of the words or
11354symbols being counted.  A ‘let’ expression can be used to create a local
11355variable for this purpose, and bind it to an initial value of zero.
11356
11357   The ‘end-of-defun’ function works like ‘beginning-of-defun’ except
11358that it moves point to the end of the definition.  ‘end-of-defun’ can be
11359used as part of an expression that determines the position of the end of
11360the definition.
11361
11362   The set up for ‘count-words-in-defun’ takes shape rapidly: first we
11363move point to the beginning of the definition, then we create a local
11364variable to hold the count, and finally, we record the position of the
11365end of the definition so the ‘while’ loop will know when to stop
11366looping.
11367
11368   The code looks like this:
11369
11370     (beginning-of-defun)
11371     (let ((count 0)
11372           (end (save-excursion (end-of-defun) (point))))
11373
11374The code is simple.  The only slight complication is likely to concern
11375‘end’: it is bound to the position of the end of the definition by a
11376‘save-excursion’ expression that returns the value of point after
11377‘end-of-defun’ temporarily moves it to the end of the definition.
11378
11379   The second part of the ‘count-words-in-defun’, after the set up, is
11380the ‘while’ loop.
11381
11382   The loop must contain an expression that jumps point forward word by
11383word and symbol by symbol, and another expression that counts the jumps.
11384The true-or-false-test for the ‘while’ loop should test true so long as
11385point should jump forward, and false when point is at the end of the
11386definition.  We have already redefined the regular expression for this,
11387so the loop is straightforward:
11388
11389     (while (and (< (point) end)
11390                 (re-search-forward
11391                  "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t))
11392       (setq count (1+ count)))
11393
11394   The third part of the function definition returns the count of words
11395and symbols.  This part is the last expression within the body of the
11396‘let’ expression, and can be, very simply, the local variable ‘count’,
11397which when evaluated returns the count.
11398
11399   Put together, the ‘count-words-in-defun’ definition looks like this:
11400
11401     (defun count-words-in-defun ()
11402       "Return the number of words and symbols in a defun."
11403       (beginning-of-defun)
11404       (let ((count 0)
11405             (end (save-excursion (end-of-defun) (point))))
11406         (while
11407             (and (< (point) end)
11408                  (re-search-forward
11409                   "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
11410                   end t))
11411           (setq count (1+ count)))
11412         count))
11413
11414   How to test this?  The function is not interactive, but it is easy to
11415put a wrapper around the function to make it interactive; we can use
11416almost the same code as for the recursive version of
11417‘count-words-example’:
11418
11419     ;;; Interactive version.
11420     (defun count-words-defun ()
11421       "Number of words and symbols in a function definition."
11422       (interactive)
11423       (message
11424        "Counting words and symbols in function definition ... ")
11425       (let ((count (count-words-in-defun)))
11426         (cond
11427          ((zerop count)
11428           (message
11429            "The definition does NOT have any words or symbols."))
11430          ((= 1 count)
11431           (message
11432            "The definition has 1 word or symbol."))
11433          (t
11434           (message
11435            "The definition has %d words or symbols." count)))))
11436
11437Let’s re-use ‘C-c =’ as a convenient keybinding:
11438
11439     (global-set-key "\C-c=" 'count-words-defun)
11440
11441   Now we can try out ‘count-words-defun’: install both
11442‘count-words-in-defun’ and ‘count-words-defun’, and set the keybinding,
11443and then place the cursor within the following definition:
11444
11445     (defun multiply-by-seven (number)
11446       "Multiply NUMBER by seven."
11447       (* 7 number))
11448          ⇒ 10
11449
11450Success!  The definition has 10 words and symbols.
11451
11452   The next problem is to count the numbers of words and symbols in
11453several definitions within a single file.
11454
11455
11456File: eintr.info,  Node: Several defuns,  Next: Find a File,  Prev: count-words-in-defun,  Up: Words in a defun
11457
1145814.4 Count Several ‘defuns’ Within a File
11459=========================================
11460
11461A file such as ‘simple.el’ may have a hundred or more function
11462definitions within it.  Our long term goal is to collect statistics on
11463many files, but as a first step, our immediate goal is to collect
11464statistics on one file.
11465
11466   The information will be a series of numbers, each number being the
11467length of a function definition.  We can store the numbers in a list.
11468
11469   We know that we will want to incorporate the information regarding
11470one file with information about many other files; this means that the
11471function for counting definition lengths within one file need only
11472return the list of lengths.  It need not and should not display any
11473messages.
11474
11475   The word count commands contain one expression to jump point forward
11476word by word and another expression to count the jumps.  The function to
11477return the lengths of definitions can be designed to work the same way,
11478with one expression to jump point forward definition by definition and
11479another expression to construct the lengths’ list.
11480
11481   This statement of the problem makes it elementary to write the
11482function definition.  Clearly, we will start the count at the beginning
11483of the file, so the first command will be ‘(goto-char (point-min))’.
11484Next, we start the ‘while’ loop; and the true-or-false test of the loop
11485can be a regular expression search for the next function definition—so
11486long as the search succeeds, point is moved forward and then the body of
11487the loop is evaluated.  The body needs an expression that constructs the
11488lengths’ list.  ‘cons’, the list construction command, can be used to
11489create the list.  That is almost all there is to it.
11490
11491   Here is what this fragment of code looks like:
11492
11493     (goto-char (point-min))
11494     (while (re-search-forward "^(defun" nil t)
11495       (setq lengths-list
11496             (cons (count-words-in-defun) lengths-list)))
11497
11498   What we have left out is the mechanism for finding the file that
11499contains the function definitions.
11500
11501   In previous examples, we either used this, the Info file, or we
11502switched back and forth to some other buffer, such as the ‘*scratch*’
11503buffer.
11504
11505   Finding a file is a new process that we have not yet discussed.
11506
11507
11508File: eintr.info,  Node: Find a File,  Next: lengths-list-file,  Prev: Several defuns,  Up: Words in a defun
11509
1151014.5 Find a File
11511================
11512
11513To find a file in Emacs, you use the ‘C-x C-f’ (‘find-file’) command.
11514This command is almost, but not quite right for the lengths problem.
11515
11516   Let’s look at the source for ‘find-file’:
11517
11518     (defun find-file (filename)
11519       "Edit file FILENAME.
11520     Switch to a buffer visiting file FILENAME,
11521     creating one if none already exists."
11522       (interactive "FFind file: ")
11523       (switch-to-buffer (find-file-noselect filename)))
11524
11525(The most recent version of the ‘find-file’ function definition permits
11526you to specify optional wildcards to visit multiple files; that makes
11527the definition more complex and we will not discuss it here, since it is
11528not relevant.  You can see its source using either ‘M-.’
11529(‘xref-find-definitions’) or ‘C-h f’ (‘describe-function’).)
11530
11531   The definition I am showing possesses short but complete
11532documentation and an interactive specification that prompts you for a
11533file name when you use the command interactively.  The body of the
11534definition contains two functions, ‘find-file-noselect’ and
11535‘switch-to-buffer’.
11536
11537   According to its documentation as shown by ‘C-h f’ (the
11538‘describe-function’ command), the ‘find-file-noselect’ function reads
11539the named file into a buffer and returns the buffer.  (Its most recent
11540version includes an optional WILDCARDS argument, too, as well as another
11541to read a file literally and another to suppress warning messages.
11542These optional arguments are irrelevant.)
11543
11544   However, the ‘find-file-noselect’ function does not select the buffer
11545in which it puts the file.  Emacs does not switch its attention (or
11546yours if you are using ‘find-file-noselect’) to the selected buffer.
11547That is what ‘switch-to-buffer’ does: it switches the buffer to which
11548Emacs attention is directed; and it switches the buffer displayed in the
11549window to the new buffer.  We have discussed buffer switching elsewhere.
11550(*Note Switching Buffers::.)
11551
11552   In this histogram project, we do not need to display each file on the
11553screen as the program determines the length of each definition within
11554it.  Instead of employing ‘switch-to-buffer’, we can work with
11555‘set-buffer’, which redirects the attention of the computer program to a
11556different buffer but does not redisplay it on the screen.  So instead of
11557calling on ‘find-file’ to do the job, we must write our own expression.
11558
11559   The task is easy: use ‘find-file-noselect’ and ‘set-buffer’.
11560
11561
11562File: eintr.info,  Node: lengths-list-file,  Next: Several files,  Prev: Find a File,  Up: Words in a defun
11563
1156414.6 ‘lengths-list-file’ in Detail
11565==================================
11566
11567The core of the ‘lengths-list-file’ function is a ‘while’ loop
11568containing a function to move point forward defun by defun, and a
11569function to count the number of words and symbols in each defun.  This
11570core must be surrounded by functions that do various other tasks,
11571including finding the file, and ensuring that point starts out at the
11572beginning of the file.  The function definition looks like this:
11573
11574     (defun lengths-list-file (filename)
11575       "Return list of definitions' lengths within FILE.
11576     The returned list is a list of numbers.
11577     Each number is the number of words or
11578     symbols in one function definition."
11579       (message "Working on `%s' ... " filename)
11580       (save-excursion
11581         (let ((buffer (find-file-noselect filename))
11582               (lengths-list))
11583           (set-buffer buffer)
11584           (setq buffer-read-only t)
11585           (widen)
11586           (goto-char (point-min))
11587           (while (re-search-forward "^(defun" nil t)
11588             (setq lengths-list
11589                   (cons (count-words-in-defun) lengths-list)))
11590           (kill-buffer buffer)
11591           lengths-list)))
11592
11593The function is passed one argument, the name of the file on which it
11594will work.  It has four lines of documentation, but no interactive
11595specification.  Since people worry that a computer is broken if they
11596don’t see anything going on, the first line of the body is a message.
11597
11598   The next line contains a ‘save-excursion’ that returns Emacs’s
11599attention to the current buffer when the function completes.  This is
11600useful in case you embed this function in another function that presumes
11601point is restored to the original buffer.
11602
11603   In the varlist of the ‘let’ expression, Emacs finds the file and
11604binds the local variable ‘buffer’ to the buffer containing the file.  At
11605the same time, Emacs creates ‘lengths-list’ as a local variable.
11606
11607   Next, Emacs switches its attention to the buffer.
11608
11609   In the following line, Emacs makes the buffer read-only.  Ideally,
11610this line is not necessary.  None of the functions for counting words
11611and symbols in a function definition should change the buffer.  Besides,
11612the buffer is not going to be saved, even if it were changed.  This line
11613is entirely the consequence of great, perhaps excessive, caution.  The
11614reason for the caution is that this function and those it calls work on
11615the sources for Emacs and it is inconvenient if they are inadvertently
11616modified.  It goes without saying that I did not realize a need for this
11617line until an experiment went awry and started to modify my Emacs source
11618files ...
11619
11620   Next comes a call to widen the buffer if it is narrowed.  This
11621function is usually not needed—Emacs creates a fresh buffer if none
11622already exists; but if a buffer visiting the file already exists Emacs
11623returns that one.  In this case, the buffer may be narrowed and must be
11624widened.  If we wanted to be fully user-friendly, we would arrange to
11625save the restriction and the location of point, but we won’t.
11626
11627   The ‘(goto-char (point-min))’ expression moves point to the beginning
11628of the buffer.
11629
11630   Then comes a ‘while’ loop in which the work of the function is
11631carried out.  In the loop, Emacs determines the length of each
11632definition and constructs a lengths’ list containing the information.
11633
11634   Emacs kills the buffer after working through it.  This is to save
11635space inside of Emacs.  My version of GNU Emacs 19 contained over 300
11636source files of interest; GNU Emacs 22 contains over a thousand source
11637files.  Another function will apply ‘lengths-list-file’ to each of the
11638files.
11639
11640   Finally, the last expression within the ‘let’ expression is the
11641‘lengths-list’ variable; its value is returned as the value of the whole
11642function.
11643
11644   You can try this function by installing it in the usual fashion.
11645Then place your cursor after the following expression and type ‘C-x C-e’
11646(‘eval-last-sexp’).
11647
11648     (lengths-list-file
11649      "/usr/local/share/emacs/22.1/lisp/emacs-lisp/debug.el")
11650
11651You may need to change the pathname of the file; the one here is for GNU
11652Emacs version 22.1.  To change the expression, copy it to the
11653‘*scratch*’ buffer and edit it.
11654
11655Also, to see the full length of the list, rather than a truncated
11656version, you may have to evaluate the following:
11657
11658     (custom-set-variables '(eval-expression-print-length nil))
11659
11660(*Note Specifying Variables using ‘defcustom’: defcustom.  Then evaluate
11661the ‘lengths-list-file’ expression.)
11662
11663   The lengths’ list for ‘debug.el’ takes less than a second to produce
11664and looks like this in GNU Emacs 22:
11665
11666     (83 113 105 144 289 22 30 97 48 89 25 52 52 88 28 29 77 49 43 290 232 587)
11667
11668   (Using my old machine, the version 19 lengths’ list for ‘debug.el11669took seven seconds to produce and looked like this:
11670
11671     (75 41 80 62 20 45 44 68 45 12 34 235)
11672
11673The newer version of ‘debug.el’ contains more defuns than the earlier
11674one; and my new machine is much faster than the old one.)
11675
11676   Note that the length of the last definition in the file is first in
11677the list.
11678
11679
11680File: eintr.info,  Node: Several files,  Next: Several files recursively,  Prev: lengths-list-file,  Up: Words in a defun
11681
1168214.7 Count Words in ‘defuns’ in Different Files
11683===============================================
11684
11685In the previous section, we created a function that returns a list of
11686the lengths of each definition in a file.  Now, we want to define a
11687function to return a master list of the lengths of the definitions in a
11688list of files.
11689
11690   Working on each of a list of files is a repetitious act, so we can
11691use either a ‘while’ loop or recursion.
11692
11693* Menu:
11694
11695* lengths-list-many-files::     Return a list of the lengths of defuns.
11696* append::                      Attach one list to another.
11697
11698
11699File: eintr.info,  Node: lengths-list-many-files,  Next: append,  Up: Several files
11700
11701Determine the lengths of ‘defuns’
11702---------------------------------
11703
11704The design using a ‘while’ loop is routine.  The argument passed to the
11705function is a list of files.  As we saw earlier (*note Loop Example::),
11706you can write a ‘while’ loop so that the body of the loop is evaluated
11707if such a list contains elements, but to exit the loop if the list is
11708empty.  For this design to work, the body of the loop must contain an
11709expression that shortens the list each time the body is evaluated, so
11710that eventually the list is empty.  The usual technique is to set the
11711value of the list to the value of the CDR of the list each time the body
11712is evaluated.
11713
11714   The template looks like this:
11715
11716     (while TEST-WHETHER-LIST-IS-EMPTY
11717       BODY...
11718       SET-LIST-TO-CDR-OF-LIST)
11719
11720   Also, we remember that a ‘while’ loop returns ‘nil’ (the result of
11721evaluating the true-or-false-test), not the result of any evaluation
11722within its body.  (The evaluations within the body of the loop are done
11723for their side effects.)  However, the expression that sets the lengths’
11724list is part of the body—and that is the value that we want returned by
11725the function as a whole.  To do this, we enclose the ‘while’ loop within
11726a ‘let’ expression, and arrange that the last element of the ‘let’
11727expression contains the value of the lengths’ list.  (*Note Loop Example
11728with an Incrementing Counter: Incrementing Example.)
11729
11730   These considerations lead us directly to the function itself:
11731
11732     ;;; Use ‘while’ loop.
11733     (defun lengths-list-many-files (list-of-files)
11734       "Return list of lengths of defuns in LIST-OF-FILES."
11735       (let (lengths-list)
11736
11737     ;;; true-or-false-test
11738         (while list-of-files
11739           (setq lengths-list
11740                 (append
11741                  lengths-list
11742
11743     ;;; Generate a lengths’ list.
11744                  (lengths-list-file
11745                   (expand-file-name (car list-of-files)))))
11746
11747     ;;; Make files’ list shorter.
11748           (setq list-of-files (cdr list-of-files)))
11749
11750     ;;; Return final value of lengths’ list.
11751         lengths-list))
11752
11753   ‘expand-file-name’ is a built-in function that converts a file name
11754to the absolute, long, path name form.  The function employs the name of
11755the directory in which the function is called.
11756
11757   Thus, if ‘expand-file-name’ is called on ‘debug.el’ when Emacs is
11758visiting the ‘/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/’ directory,
11759
11760     debug.el
11761
11762becomes
11763
11764     /usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el
11765
11766   The only other new element of this function definition is the as yet
11767unstudied function ‘append’, which merits a short section for itself.
11768
11769
11770File: eintr.info,  Node: append,  Prev: lengths-list-many-files,  Up: Several files
11771
1177214.7.1 The ‘append’ Function
11773----------------------------
11774
11775The ‘append’ function attaches one list to another.  Thus,
11776
11777     (append '(1 2 3 4) '(5 6 7 8))
11778
11779produces the list
11780
11781     (1 2 3 4 5 6 7 8)
11782
11783   This is exactly how we want to attach two lengths’ lists produced by
11784‘lengths-list-file’ to each other.  The results contrast with ‘cons’,
11785
11786     (cons '(1 2 3 4) '(5 6 7 8))
11787
11788which constructs a new list in which the first argument to ‘cons’
11789becomes the first element of the new list:
11790
11791     ((1 2 3 4) 5 6 7 8)
11792
11793
11794File: eintr.info,  Node: Several files recursively,  Next: Prepare the data,  Prev: Several files,  Up: Words in a defun
11795
1179614.8 Recursively Count Words in Different Files
11797===============================================
11798
11799Besides a ‘while’ loop, you can work on each of a list of files with
11800recursion.  A recursive version of ‘lengths-list-many-files’ is short
11801and simple.
11802
11803   The recursive function has the usual parts: the do-again-test, the
11804next-step-expression, and the recursive call.  The do-again-test
11805determines whether the function should call itself again, which it will
11806do if the ‘list-of-files’ contains any remaining elements; the
11807next-step-expression resets the ‘list-of-files’ to the CDR of itself, so
11808eventually the list will be empty; and the recursive call calls itself
11809on the shorter list.  The complete function is shorter than this
11810description!
11811
11812     (defun recursive-lengths-list-many-files (list-of-files)
11813       "Return list of lengths of each defun in LIST-OF-FILES."
11814       (if list-of-files                     ; do-again-test
11815           (append
11816            (lengths-list-file
11817             (expand-file-name (car list-of-files)))
11818            (recursive-lengths-list-many-files
11819             (cdr list-of-files)))))
11820
11821In a sentence, the function returns the lengths’ list for the first of
11822the ‘list-of-files’ appended to the result of calling itself on the rest
11823of the ‘list-of-files’.
11824
11825   Here is a test of ‘recursive-lengths-list-many-files’, along with the
11826results of running ‘lengths-list-file’ on each of the files
11827individually.
11828
11829   Install ‘recursive-lengths-list-many-files’ and ‘lengths-list-file’,
11830if necessary, and then evaluate the following expressions.  You may need
11831to change the files’ pathnames; those here work when this Info file and
11832the Emacs sources are located in their customary places.  To change the
11833expressions, copy them to the ‘*scratch*’ buffer, edit them, and then
11834evaluate them.
11835
11836   The results are shown after the ‘⇒’.  (These results are for files
11837from Emacs version 22.1.1; files from other versions of Emacs may
11838produce different results.)
11839
11840     (cd "/usr/local/share/emacs/22.1.1/")
11841
11842     (lengths-list-file "./lisp/macros.el")
11843          ⇒ (283 263 480 90)
11844
11845     (lengths-list-file "./lisp/mail/mailalias.el")
11846          ⇒ (38 32 29 95 178 180 321 218 324)
11847
11848     (lengths-list-file "./lisp/makesum.el")
11849          ⇒ (85 181)
11850
11851       (recursive-lengths-list-many-files
11852        '("./lisp/macros.el"
11853          "./lisp/mail/mailalias.el"
11854          "./lisp/makesum.el"))
11855            ⇒ (283 263 480 90 38 32 29 95 178 180 321 218 324 85 181)
11856
11857   The ‘recursive-lengths-list-many-files’ function produces the output
11858we want.
11859
11860   The next step is to prepare the data in the list for display in a
11861graph.
11862
11863
11864File: eintr.info,  Node: Prepare the data,  Prev: Several files recursively,  Up: Words in a defun
11865
1186614.9 Prepare the Data for Display in a Graph
11867============================================
11868
11869The ‘recursive-lengths-list-many-files’ function returns a list of
11870numbers.  Each number records the length of a function definition.  What
11871we need to do now is transform this data into a list of numbers suitable
11872for generating a graph.  The new list will tell how many functions
11873definitions contain less than 10 words and symbols, how many contain
11874between 10 and 19 words and symbols, how many contain between 20 and 29
11875words and symbols, and so on.
11876
11877   In brief, we need to go through the lengths’ list produced by the
11878‘recursive-lengths-list-many-files’ function and count the number of
11879defuns within each range of lengths, and produce a list of those
11880numbers.
11881
11882* Menu:
11883
11884* Data for Display in Detail::
11885* Sorting::                     Sorting lists.
11886* Files List::                  Making a list of files.
11887* Counting function definitions::
11888
11889
11890File: eintr.info,  Node: Data for Display in Detail,  Next: Sorting,  Up: Prepare the data
11891
11892The Data for Display in Detail
11893------------------------------
11894
11895Based on what we have done before, we can readily foresee that it should
11896not be too hard to write a function that CDRs down the lengths’ list,
11897looks at each element, determines which length range it is in, and
11898increments a counter for that range.
11899
11900   However, before beginning to write such a function, we should
11901consider the advantages of sorting the lengths’ list first, so the
11902numbers are ordered from smallest to largest.  First, sorting will make
11903it easier to count the numbers in each range, since two adjacent numbers
11904will either be in the same length range or in adjacent ranges.  Second,
11905by inspecting a sorted list, we can discover the highest and lowest
11906number, and thereby determine the largest and smallest length range that
11907we will need.
11908
11909
11910File: eintr.info,  Node: Sorting,  Next: Files List,  Prev: Data for Display in Detail,  Up: Prepare the data
11911
1191214.9.1 Sorting Lists
11913--------------------
11914
11915Emacs contains a function to sort lists, called (as you might guess)
11916‘sort’.  The ‘sort’ function takes two arguments, the list to be sorted,
11917and a predicate that determines whether the first of two list elements
11918is less than the second.
11919
11920   As we saw earlier (*note Using the Wrong Type Object as an Argument:
11921Wrong Type of Argument.), a predicate is a function that determines
11922whether some property is true or false.  The ‘sort’ function will
11923reorder a list according to whatever property the predicate uses; this
11924means that ‘sort’ can be used to sort non-numeric lists by non-numeric
11925criteria—it can, for example, alphabetize a list.
11926
11927   The ‘<’ function is used when sorting a numeric list.  For example,
11928
11929     (sort '(4 8 21 17 33 7 21 7) '<)
11930
11931produces this:
11932
11933     (4 7 7 8 17 21 21 33)
11934
11935(Note that in this example, both the arguments are quoted so that the
11936symbols are not evaluated before being passed to ‘sort’ as arguments.)
11937
11938   Sorting the list returned by the ‘recursive-lengths-list-many-files’
11939function is straightforward; it uses the ‘<’ function:
11940
11941     (sort
11942      (recursive-lengths-list-many-files
11943       '("./lisp/macros.el"
11944         "./lisp/mailalias.el"
11945         "./lisp/makesum.el"))
11946      '<)
11947
11948which produces:
11949
11950     (29 32 38 85 90 95 178 180 181 218 263 283 321 324 480)
11951
11952(Note that in this example, the first argument to ‘sort’ is not quoted,
11953since the expression must be evaluated so as to produce the list that is
11954passed to ‘sort’.)
11955
11956
11957File: eintr.info,  Node: Files List,  Next: Counting function definitions,  Prev: Sorting,  Up: Prepare the data
11958
1195914.9.2 Making a List of Files
11960-----------------------------
11961
11962The ‘recursive-lengths-list-many-files’ function requires a list of
11963files as its argument.  For our test examples, we constructed such a
11964list by hand; but the Emacs Lisp source directory is too large for us to
11965do for that.  Instead, we will write a function to do the job for us.
11966In this function, we will use both a ‘while’ loop and a recursive call.
11967
11968   We did not have to write a function like this for older versions of
11969GNU Emacs, since they placed all the ‘.el’ files in one directory.
11970Instead, we were able to use the ‘directory-files’ function, which lists
11971the names of files that match a specified pattern within a single
11972directory.
11973
11974   However, recent versions of Emacs place Emacs Lisp files in
11975sub-directories of the top level ‘lisp’ directory.  This re-arrangement
11976eases navigation.  For example, all the mail related files are in a
11977‘lisp’ sub-directory called ‘mail’.  But at the same time, this
11978arrangement forces us to create a file listing function that descends
11979into the sub-directories.
11980
11981   We can create this function, called ‘files-in-below-directory’, using
11982familiar functions such as ‘car’, ‘nthcdr’, and ‘substring’ in
11983conjunction with an existing function called
11984‘directory-files-and-attributes’.  This latter function not only lists
11985all the filenames in a directory, including the names of
11986sub-directories, but also their attributes.
11987
11988   To restate our goal: to create a function that will enable us to feed
11989filenames to ‘recursive-lengths-list-many-files’ as a list that looks
11990like this (but with more elements):
11991
11992     ("./lisp/macros.el"
11993      "./lisp/mail/rmail.el"
11994      "./lisp/makesum.el")
11995
11996   The ‘directory-files-and-attributes’ function returns a list of
11997lists.  Each of the lists within the main list consists of 13 elements.
11998The first element is a string that contains the name of the file—which,
11999in GNU/Linux, may be a “directory file”, that is to say, a file with the
12000special attributes of a directory.  The second element of the list is
12001‘t’ for a directory, a string for symbolic link (the string is the name
12002linked to), or ‘nil’.
12003
12004   For example, the first ‘.el’ file in the ‘lisp/’ directory is
12005abbrev.el’.  Its name is ‘/usr/local/share/emacs/22.1.1/lisp/abbrev.el12006and it is not a directory or a symbolic link.
12007
12008   This is how ‘directory-files-and-attributes’ lists that file and its
12009attributes:
12010
12011     ("abbrev.el"
12012     nil
12013     1
12014     1000
12015     100
12016     (20615 27034 579989 697000)
12017     (17905 55681 0 0)
12018     (20615 26327 734791 805000)
12019     13188
12020     "-rw-r--r--"
12021     t
12022     2971624
12023     773)
12024
12025   On the other hand, ‘mail/’ is a directory within the ‘lisp/’
12026directory.  The beginning of its listing looks like this:
12027
12028     ("mail"
12029     t
12030     ...
12031     )
12032
12033   (To learn about the different attributes, look at the documentation
12034of ‘file-attributes’.  Bear in mind that the ‘file-attributes’ function
12035does not list the filename, so its first element is
12036‘directory-files-and-attributes’’s second element.)
12037
12038   We will want our new function, ‘files-in-below-directory’, to list
12039the ‘.el’ files in the directory it is told to check, and in any
12040directories below that directory.
12041
12042   This gives us a hint on how to construct ‘files-in-below-directory’:
12043within a directory, the function should add ‘.el’ filenames to a list;
12044and if, within a directory, the function comes upon a sub-directory, it
12045should go into that sub-directory and repeat its actions.
12046
12047   However, we should note that every directory contains a name that
12048refers to itself, called ‘.’ (“dot”), and a name that refers to its
12049parent directory, called ‘..’ (“dot dot”).  (In ‘/’, the root directory,
12050‘..’ refers to itself, since ‘/’ has no parent.)  Clearly, we do not
12051want our ‘files-in-below-directory’ function to enter those directories,
12052since they always lead us, directly or indirectly, to the current
12053directory.
12054
12055   Consequently, our ‘files-in-below-directory’ function must do several
12056tasks:
12057
12058   • Check to see whether it is looking at a filename that ends in
12059     ‘.el’; and if so, add its name to a list.
12060
12061   • Check to see whether it is looking at a filename that is the name
12062     of a directory; and if so,
12063
12064        − Check to see whether it is looking at ‘.’ or ‘..’; and if so
12065          skip it.
12066
12067        − Or else, go into that directory and repeat the process.
12068
12069   Let’s write a function definition to do these tasks.  We will use a
12070‘while’ loop to move from one filename to another within a directory,
12071checking what needs to be done; and we will use a recursive call to
12072repeat the actions on each sub-directory.  The recursive pattern is
12073Accumulate (*note Accumulate::), using ‘append’ as the combiner.
12074
12075   Here is the function:
12076
12077     (defun files-in-below-directory (directory)
12078       "List the .el files in DIRECTORY and in its sub-directories."
12079       ;; Although the function will be used non-interactively,
12080       ;; it will be easier to test if we make it interactive.
12081       ;; The directory will have a name such as
12082       ;;  "/usr/local/share/emacs/22.1.1/lisp/"
12083       (interactive "DDirectory name: ")
12084       (let (el-files-list
12085             (current-directory-list
12086              (directory-files-and-attributes directory t)))
12087         ;; while we are in the current directory
12088         (while current-directory-list
12089           (cond
12090            ;; check to see whether filename ends in '.el'
12091            ;; and if so, add its name to a list.
12092            ((equal ".el" (substring (car (car current-directory-list)) -3))
12093             (setq el-files-list
12094                   (cons (car (car current-directory-list)) el-files-list)))
12095            ;; check whether filename is that of a directory
12096            ((eq t (car (cdr (car current-directory-list))))
12097             ;; decide whether to skip or recurse
12098             (if
12099                 (equal "."
12100                        (substring (car (car current-directory-list)) -1))
12101                 ;; then do nothing since filename is that of
12102                 ;;   current directory or parent, "." or ".."
12103                 ()
12104               ;; else descend into the directory and repeat the process
12105               (setq el-files-list
12106                     (append
12107                      (files-in-below-directory
12108                       (car (car current-directory-list)))
12109                      el-files-list)))))
12110           ;; move to the next filename in the list; this also
12111           ;; shortens the list so the while loop eventually comes to an end
12112           (setq current-directory-list (cdr current-directory-list)))
12113         ;; return the filenames
12114         el-files-list))
12115
12116   The ‘files-in-below-directory’ ‘directory-files’ function takes one
12117argument, the name of a directory.
12118
12119   Thus, on my system,
12120
12121     (length
12122      (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/"))
12123
12124tells me that in and below my Lisp sources directory are 1031 ‘.el’
12125files.
12126
12127   ‘files-in-below-directory’ returns a list in reverse alphabetical
12128order.  An expression to sort the list in alphabetical order looks like
12129this:
12130
12131     (sort
12132      (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
12133      'string-lessp)
12134
12135
12136File: eintr.info,  Node: Counting function definitions,  Prev: Files List,  Up: Prepare the data
12137
1213814.9.3 Counting function definitions
12139------------------------------------
12140
12141Our immediate goal is to generate a list that tells us how many function
12142definitions contain fewer than 10 words and symbols, how many contain
12143between 10 and 19 words and symbols, how many contain between 20 and 29
12144words and symbols, and so on.
12145
12146   With a sorted list of numbers, this is easy: count how many elements
12147of the list are smaller than 10, then, after moving past the numbers
12148just counted, count how many are smaller than 20, then, after moving
12149past the numbers just counted, count how many are smaller than 30, and
12150so on.  Each of the numbers, 10, 20, 30, 40, and the like, is one larger
12151than the top of that range.  We can call the list of such numbers the
12152‘top-of-ranges’ list.
12153
12154   If we wished, we could generate this list automatically, but it is
12155simpler to write a list manually.  Here it is:
12156
12157     (defvar top-of-ranges
12158      '(10  20  30  40  50
12159        60  70  80  90 100
12160       110 120 130 140 150
12161       160 170 180 190 200
12162       210 220 230 240 250
12163       260 270 280 290 300)
12164      "List specifying ranges for `defuns-per-range'.")
12165
12166   To change the ranges, we edit this list.
12167
12168   Next, we need to write the function that creates the list of the
12169number of definitions within each range.  Clearly, this function must
12170take the ‘sorted-lengths’ and the ‘top-of-ranges’ lists as arguments.
12171
12172   The ‘defuns-per-range’ function must do two things again and again:
12173it must count the number of definitions within a range specified by the
12174current top-of-range value; and it must shift to the next higher value
12175in the ‘top-of-ranges’ list after counting the number of definitions in
12176the current range.  Since each of these actions is repetitive, we can
12177use ‘while’ loops for the job.  One loop counts the number of
12178definitions in the range defined by the current top-of-range value, and
12179the other loop selects each of the top-of-range values in turn.
12180
12181   Several entries of the ‘sorted-lengths’ list are counted for each
12182range; this means that the loop for the ‘sorted-lengths’ list will be
12183inside the loop for the ‘top-of-ranges’ list, like a small gear inside a
12184big gear.
12185
12186   The inner loop counts the number of definitions within the range.  It
12187is a simple counting loop of the type we have seen before.  (*Note A
12188loop with an incrementing counter: Incrementing Loop.)  The
12189true-or-false test of the loop tests whether the value from the
12190‘sorted-lengths’ list is smaller than the current value of the top of
12191the range.  If it is, the function increments the counter and tests the
12192next value from the ‘sorted-lengths’ list.
12193
12194   The inner loop looks like this:
12195
12196     (while LENGTH-ELEMENT-SMALLER-THAN-TOP-OF-RANGE
12197       (setq number-within-range (1+ number-within-range))
12198       (setq sorted-lengths (cdr sorted-lengths)))
12199
12200   The outer loop must start with the lowest value of the
12201‘top-of-ranges’ list, and then be set to each of the succeeding higher
12202values in turn.  This can be done with a loop like this:
12203
12204     (while top-of-ranges
12205       BODY-OF-LOOP...
12206       (setq top-of-ranges (cdr top-of-ranges)))
12207
12208   Put together, the two loops look like this:
12209
12210     (while top-of-ranges
12211
12212       ;; Count the number of elements within the current range.
12213       (while LENGTH-ELEMENT-SMALLER-THAN-TOP-OF-RANGE
12214         (setq number-within-range (1+ number-within-range))
12215         (setq sorted-lengths (cdr sorted-lengths)))
12216
12217       ;; Move to next range.
12218       (setq top-of-ranges (cdr top-of-ranges)))
12219
12220   In addition, in each circuit of the outer loop, Emacs should record
12221the number of definitions within that range (the value of
12222‘number-within-range’) in a list.  We can use ‘cons’ for this purpose.
12223(*Note ‘cons’: cons.)
12224
12225   The ‘cons’ function works fine, except that the list it constructs
12226will contain the number of definitions for the highest range at its
12227beginning and the number of definitions for the lowest range at its end.
12228This is because ‘cons’ attaches new elements of the list to the
12229beginning of the list, and since the two loops are working their way
12230through the lengths’ list from the lower end first, the
12231‘defuns-per-range-list’ will end up largest number first.  But we will
12232want to print our graph with smallest values first and the larger later.
12233The solution is to reverse the order of the ‘defuns-per-range-list’.  We
12234can do this using the ‘nreverse’ function, which reverses the order of a
12235list.
12236
12237   For example,
12238
12239     (nreverse '(1 2 3 4))
12240
12241produces:
12242
12243     (4 3 2 1)
12244
12245   Note that the ‘nreverse’ function is destructive—that is, it changes
12246the list to which it is applied; this contrasts with the ‘car’ and ‘cdr’
12247functions, which are non-destructive.  In this case, we do not want the
12248original ‘defuns-per-range-list’, so it does not matter that it is
12249destroyed.  (The ‘reverse’ function provides a reversed copy of a list,
12250leaving the original list as is.)
12251
12252   Put all together, the ‘defuns-per-range’ looks like this:
12253
12254     (defun defuns-per-range (sorted-lengths top-of-ranges)
12255       "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
12256       (let ((top-of-range (car top-of-ranges))
12257             (number-within-range 0)
12258             defuns-per-range-list)
12259
12260         ;; Outer loop.
12261         (while top-of-ranges
12262
12263           ;; Inner loop.
12264           (while (and
12265                   ;; Need number for numeric test.
12266                   (car sorted-lengths)
12267                   (< (car sorted-lengths) top-of-range))
12268
12269             ;; Count number of definitions within current range.
12270             (setq number-within-range (1+ number-within-range))
12271             (setq sorted-lengths (cdr sorted-lengths)))
12272
12273           ;; Exit inner loop but remain within outer loop.
12274
12275           (setq defuns-per-range-list
12276                 (cons number-within-range defuns-per-range-list))
12277           (setq number-within-range 0)      ; Reset count to zero.
12278
12279           ;; Move to next range.
12280           (setq top-of-ranges (cdr top-of-ranges))
12281           ;; Specify next top of range value.
12282           (setq top-of-range (car top-of-ranges)))
12283
12284         ;; Exit outer loop and count the number of defuns larger than
12285         ;;   the largest top-of-range value.
12286         (setq defuns-per-range-list
12287               (cons
12288                (length sorted-lengths)
12289                defuns-per-range-list))
12290
12291         ;; Return a list of the number of definitions within each range,
12292         ;;   smallest to largest.
12293         (nreverse defuns-per-range-list)))
12294
12295The function is straightforward except for one subtle feature.  The
12296true-or-false test of the inner loop looks like this:
12297
12298     (and (car sorted-lengths)
12299          (< (car sorted-lengths) top-of-range))
12300
12301instead of like this:
12302
12303     (< (car sorted-lengths) top-of-range)
12304
12305   The purpose of the test is to determine whether the first item in the
12306‘sorted-lengths’ list is less than the value of the top of the range.
12307
12308   The simple version of the test works fine unless the ‘sorted-lengths’
12309list has a ‘nil’ value.  In that case, the ‘(car sorted-lengths)’
12310expression function returns ‘nil’.  The ‘<’ function cannot compare a
12311number to ‘nil’, which is an empty list, so Emacs signals an error and
12312stops the function from attempting to continue to execute.
12313
12314   The ‘sorted-lengths’ list always becomes ‘nil’ when the counter
12315reaches the end of the list.  This means that any attempt to use the
12316‘defuns-per-range’ function with the simple version of the test will
12317fail.
12318
12319   We solve the problem by using the ‘(car sorted-lengths)’ expression
12320in conjunction with the ‘and’ expression.  The ‘(car sorted-lengths)’
12321expression returns a non-‘nil’ value so long as the list has at least
12322one number within it, but returns ‘nil’ if the list is empty.  The ‘and’
12323expression first evaluates the ‘(car sorted-lengths)’ expression, and if
12324it is ‘nil’, returns false _without_ evaluating the ‘<’ expression.  But
12325if the ‘(car sorted-lengths)’ expression returns a non-‘nil’ value, the
12326‘and’ expression evaluates the ‘<’ expression, and returns that value as
12327the value of the ‘and’ expression.
12328
12329   This way, we avoid an error.  (*Note The ‘kill-new’ function:
12330kill-new function, for information about ‘and’.)
12331
12332   Here is a short test of the ‘defuns-per-range’ function.  First,
12333evaluate the expression that binds (a shortened) ‘top-of-ranges’ list to
12334the list of values, then evaluate the expression for binding the
12335‘sorted-lengths’ list, and then evaluate the ‘defuns-per-range’
12336function.
12337
12338     ;; (Shorter list than we will use later.)
12339     (setq top-of-ranges
12340      '(110 120 130 140 150
12341        160 170 180 190 200))
12342
12343     (setq sorted-lengths
12344           '(85 86 110 116 122 129 154 176 179 200 265 300 300))
12345
12346     (defuns-per-range sorted-lengths top-of-ranges)
12347
12348The list returned looks like this:
12349
12350     (2 2 2 0 0 1 0 2 0 0 4)
12351
12352Indeed, there are two elements of the ‘sorted-lengths’ list smaller than
12353110, two elements between 110 and 119, two elements between 120 and 129,
12354and so on.  There are four elements with a value of 200 or larger.
12355
12356
12357File: eintr.info,  Node: Readying a Graph,  Next: Emacs Initialization,  Prev: Words in a defun,  Up: Top
12358
1235915 Readying a Graph
12360*******************
12361
12362Our goal is to construct a graph showing the numbers of function
12363definitions of various lengths in the Emacs lisp sources.
12364
12365   As a practical matter, if you were creating a graph, you would
12366probably use a program such as ‘gnuplot’ to do the job.  (‘gnuplot’ is
12367nicely integrated into GNU Emacs.)  In this case, however, we create one
12368from scratch, and in the process we will re-acquaint ourselves with some
12369of what we learned before and learn more.
12370
12371   In this chapter, we will first write a simple graph printing
12372function.  This first definition will be a “prototype”, a rapidly
12373written function that enables us to reconnoiter this unknown
12374graph-making territory.  We will discover dragons, or find that they are
12375myth.  After scouting the terrain, we will feel more confident and
12376enhance the function to label the axes automatically.
12377
12378* Menu:
12379
12380* Columns of a graph::
12381* graph-body-print::            How to print the body of a graph.
12382* recursive-graph-body-print::
12383* Printed Axes::
12384* Line Graph Exercise::
12385
12386
12387File: eintr.info,  Node: Columns of a graph,  Next: graph-body-print,  Up: Readying a Graph
12388
12389Printing the Columns of a Graph
12390===============================
12391
12392Since Emacs is designed to be flexible and work with all kinds of
12393terminals, including character-only terminals, the graph will need to be
12394made from one of the typewriter symbols.  An asterisk will do; as we
12395enhance the graph-printing function, we can make the choice of symbol a
12396user option.
12397
12398   We can call this function ‘graph-body-print’; it will take a
12399‘numbers-list’ as its only argument.  At this stage, we will not label
12400the graph, but only print its body.
12401
12402   The ‘graph-body-print’ function inserts a vertical column of
12403asterisks for each element in the ‘numbers-list’.  The height of each
12404line is determined by the value of that element of the ‘numbers-list’.
12405
12406   Inserting columns is a repetitive act; that means that this function
12407can be written either with a ‘while’ loop or recursively.
12408
12409   Our first challenge is to discover how to print a column of
12410asterisks.  Usually, in Emacs, we print characters onto a screen
12411horizontally, line by line, by typing.  We have two routes we can
12412follow: write our own column-insertion function or discover whether one
12413exists in Emacs.
12414
12415   To see whether there is one in Emacs, we can use the ‘M-x apropos’
12416command.  This command is like the ‘C-h a’ (‘command-apropos’) command,
12417except that the latter finds only those functions that are commands.
12418The ‘M-x apropos’ command lists all symbols that match a regular
12419expression, including functions that are not interactive.
12420
12421   What we want to look for is some command that prints or inserts
12422columns.  Very likely, the name of the function will contain either the
12423word “print” or the word “insert” or the word “column”.  Therefore, we
12424can simply type ‘M-x apropos <RET> print\|insert\|column <RET>’ and look
12425at the result.  On my system, this command once took quite some time,
12426and then produced a list of 79 functions and variables.  Now it does not
12427take much time at all and produces a list of 211 functions and
12428variables.  Scanning down the list, the only function that looks as if
12429it might do the job is ‘insert-rectangle’.
12430
12431   Indeed, this is the function we want; its documentation says:
12432
12433     insert-rectangle:
12434     Insert text of RECTANGLE with upper left corner at point.
12435     RECTANGLE's first line is inserted at point,
12436     its second line is inserted at a point vertically under point, etc.
12437     RECTANGLE should be a list of strings.
12438     After this command, the mark is at the upper left corner
12439     and point is at the lower right corner.
12440
12441   We can run a quick test, to make sure it does what we expect of it.
12442
12443   Here is the result of placing the cursor after the ‘insert-rectangle’
12444expression and typing ‘C-u C-x C-e’ (‘eval-last-sexp’).  The function
12445inserts the strings ‘"first"’, ‘"second"’, and ‘"third"’ at and below
12446point.  Also the function returns ‘nil’.
12447
12448     (insert-rectangle '("first" "second" "third"))first
12449                                                   second
12450                                                   thirdnil
12451
12452Of course, we won’t be inserting the text of the ‘insert-rectangle’
12453expression itself into the buffer in which we are making the graph, but
12454will call the function from our program.  We shall, however, have to
12455make sure that point is in the buffer at the place where the
12456‘insert-rectangle’ function will insert its column of strings.
12457
12458   If you are reading this in Info, you can see how this works by
12459switching to another buffer, such as the ‘*scratch*’ buffer, placing
12460point somewhere in the buffer, typing ‘M-:’, typing the
12461‘insert-rectangle’ expression into the minibuffer at the prompt, and
12462then typing <RET>.  This causes Emacs to evaluate the expression in the
12463minibuffer, but to use as the value of point the position of point in
12464the ‘*scratch*’ buffer.  (‘M-:’ is the keybinding for ‘eval-expression’.
12465Also, ‘nil’ does not appear in the ‘*scratch*’ buffer since the
12466expression is evaluated in the minibuffer.)
12467
12468   We find when we do this that point ends up at the end of the last
12469inserted line—that is to say, this function moves point as a
12470side-effect.  If we were to repeat the command, with point at this
12471position, the next insertion would be below and to the right of the
12472previous insertion.  We don’t want this!  If we are going to make a bar
12473graph, the columns need to be beside each other.
12474
12475   So we discover that each cycle of the column-inserting ‘while’ loop
12476must reposition point to the place we want it, and that place will be at
12477the top, not the bottom, of the column.  Moreover, we remember that when
12478we print a graph, we do not expect all the columns to be the same
12479height.  This means that the top of each column may be at a different
12480height from the previous one.  We cannot simply reposition point to the
12481same line each time, but moved over to the right—or perhaps we can...
12482
12483   We are planning to make the columns of the bar graph out of
12484asterisks.  The number of asterisks in the column is the number
12485specified by the current element of the ‘numbers-list’.  We need to
12486construct a list of asterisks of the right length for each call to
12487‘insert-rectangle’.  If this list consists solely of the requisite
12488number of asterisks, then we will have to position point the right
12489number of lines above the base for the graph to print correctly.  This
12490could be difficult.
12491
12492   Alternatively, if we can figure out some way to pass
12493‘insert-rectangle’ a list of the same length each time, then we can
12494place point on the same line each time, but move it over one column to
12495the right for each new column.  If we do this, however, some of the
12496entries in the list passed to ‘insert-rectangle’ must be blanks rather
12497than asterisks.  For example, if the maximum height of the graph is 5,
12498but the height of the column is 3, then ‘insert-rectangle’ requires an
12499argument that looks like this:
12500
12501     (" " " " "*" "*" "*")
12502
12503   This last proposal is not so difficult, so long as we can determine
12504the column height.  There are two ways for us to specify the column
12505height: we can arbitrarily state what it will be, which would work fine
12506for graphs of that height; or we can search through the list of numbers
12507and use the maximum height of the list as the maximum height of the
12508graph.  If the latter operation were difficult, then the former
12509procedure would be easiest, but there is a function built into Emacs
12510that determines the maximum of its arguments.  We can use that function.
12511The function is called ‘max’ and it returns the largest of all its
12512arguments, which must be numbers.  Thus, for example,
12513
12514     (max  3 4 6 5 7 3)
12515
12516returns 7.  (A corresponding function called ‘min’ returns the smallest
12517of all its arguments.)
12518
12519   However, we cannot simply call ‘max’ on the ‘numbers-list’; the ‘max’
12520function expects numbers as its argument, not a list of numbers.  Thus,
12521the following expression,
12522
12523     (max  '(3 4 6 5 7 3))
12524
12525produces the following error message;
12526
12527     Wrong type of argument:  number-or-marker-p, (3 4 6 5 7 3)
12528
12529   We need a function that passes a list of arguments to a function.
12530This function is ‘apply’.  This function applies its first argument (a
12531function) to its remaining arguments, the last of which may be a list.
12532
12533   For example,
12534
12535     (apply 'max 3 4 7 3 '(4 8 5))
12536
12537returns 8.
12538
12539   (Incidentally, I don’t know how you would learn of this function
12540without a book such as this.  It is possible to discover other
12541functions, like ‘search-forward’ or ‘insert-rectangle’, by guessing at a
12542part of their names and then using ‘apropos’.  Even though its base in
12543metaphor is clear—apply its first argument to the rest—I doubt a novice
12544would come up with that particular word when using ‘apropos’ or other
12545aid.  Of course, I could be wrong; after all, the function was first
12546named by someone who had to invent it.)
12547
12548   The second and subsequent arguments to ‘apply’ are optional, so we
12549can use ‘apply’ to call a function and pass the elements of a list to
12550it, like this, which also returns 8:
12551
12552     (apply 'max '(4 8 5))
12553
12554   This latter way is how we will use ‘apply’.  The
12555‘recursive-lengths-list-many-files’ function returns a numbers’ list to
12556which we can apply ‘max’ (we could also apply ‘max’ to the sorted
12557numbers’ list; it does not matter whether the list is sorted or not.)
12558
12559   Hence, the operation for finding the maximum height of the graph is
12560this:
12561
12562     (setq max-graph-height (apply 'max numbers-list))
12563
12564   Now we can return to the question of how to create a list of strings
12565for a column of the graph.  Told the maximum height of the graph and the
12566number of asterisks that should appear in the column, the function
12567should return a list of strings for the ‘insert-rectangle’ command to
12568insert.
12569
12570   Each column is made up of asterisks or blanks.  Since the function is
12571passed the value of the height of the column and the number of asterisks
12572in the column, the number of blanks can be found by subtracting the
12573number of asterisks from the height of the column.  Given the number of
12574blanks and the number of asterisks, two ‘while’ loops can be used to
12575construct the list:
12576
12577     ;;; First version.
12578     (defun column-of-graph (max-graph-height actual-height)
12579       "Return list of strings that is one column of a graph."
12580       (let ((insert-list nil)
12581             (number-of-top-blanks
12582              (- max-graph-height actual-height)))
12583
12584         ;; Fill in asterisks.
12585         (while (> actual-height 0)
12586           (setq insert-list (cons "*" insert-list))
12587           (setq actual-height (1- actual-height)))
12588
12589         ;; Fill in blanks.
12590         (while (> number-of-top-blanks 0)
12591           (setq insert-list (cons " " insert-list))
12592           (setq number-of-top-blanks
12593                 (1- number-of-top-blanks)))
12594
12595         ;; Return whole list.
12596         insert-list))
12597
12598   If you install this function and then evaluate the following
12599expression you will see that it returns the list as desired:
12600
12601     (column-of-graph 5 3)
12602
12603returns
12604
12605     (" " " " "*" "*" "*")
12606
12607   As written, ‘column-of-graph’ contains a major flaw: the symbols used
12608for the blank and for the marked entries in the column are hard-coded as
12609a space and asterisk.  This is fine for a prototype, but you, or another
12610user, may wish to use other symbols.  For example, in testing the graph
12611function, you may want to use a period in place of the space, to make
12612sure the point is being repositioned properly each time the
12613‘insert-rectangle’ function is called; or you might want to substitute a
12614‘+’ sign or other symbol for the asterisk.  You might even want to make
12615a graph-column that is more than one display column wide.  The program
12616should be more flexible.  The way to do that is to replace the blank and
12617the asterisk with two variables that we can call ‘graph-blank’ and
12618‘graph-symbol’ and define those variables separately.
12619
12620   Also, the documentation is not well written.  These considerations
12621lead us to the second version of the function:
12622
12623     (defvar graph-symbol "*"
12624       "String used as symbol in graph, usually an asterisk.")
12625
12626     (defvar graph-blank " "
12627       "String used as blank in graph, usually a blank space.
12628     graph-blank must be the same number of columns wide
12629     as graph-symbol.")
12630
12631(For an explanation of ‘defvar’, see *note Initializing a Variable with
12632‘defvar’: defvar.)
12633
12634     ;;; Second version.
12635     (defun column-of-graph (max-graph-height actual-height)
12636       "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
12637
12638     The graph-symbols are contiguous entries at the end
12639     of the list.
12640     The list will be inserted as one column of a graph.
12641     The strings are either graph-blank or graph-symbol."
12642
12643       (let ((insert-list nil)
12644             (number-of-top-blanks
12645              (- max-graph-height actual-height)))
12646
12647         ;; Fill in ‘graph-symbols’.
12648         (while (> actual-height 0)
12649           (setq insert-list (cons graph-symbol insert-list))
12650           (setq actual-height (1- actual-height)))
12651
12652         ;; Fill in ‘graph-blanks’.
12653         (while (> number-of-top-blanks 0)
12654           (setq insert-list (cons graph-blank insert-list))
12655           (setq number-of-top-blanks
12656                 (1- number-of-top-blanks)))
12657
12658         ;; Return whole list.
12659         insert-list))
12660
12661   If we wished, we could rewrite ‘column-of-graph’ a third time to
12662provide optionally for a line graph as well as for a bar graph.  This
12663would not be hard to do.  One way to think of a line graph is that it is
12664no more than a bar graph in which the part of each bar that is below the
12665top is blank.  To construct a column for a line graph, the function
12666first constructs a list of blanks that is one shorter than the value,
12667then it uses ‘cons’ to attach a graph symbol to the list; then it uses
12668‘cons’ again to attach the top blanks to the list.
12669
12670   It is easy to see how to write such a function, but since we don’t
12671need it, we will not do it.  But the job could be done, and if it were
12672done, it would be done with ‘column-of-graph’.  Even more important, it
12673is worth noting that few changes would have to be made anywhere else.
12674The enhancement, if we ever wish to make it, is simple.
12675
12676   Now, finally, we come to our first actual graph printing function.
12677This prints the body of a graph, not the labels for the vertical and
12678horizontal axes, so we can call this ‘graph-body-print’.
12679
12680
12681File: eintr.info,  Node: graph-body-print,  Next: recursive-graph-body-print,  Prev: Columns of a graph,  Up: Readying a Graph
12682
1268315.1 The ‘graph-body-print’ Function
12684====================================
12685
12686After our preparation in the preceding section, the ‘graph-body-print’
12687function is straightforward.  The function will print column after
12688column of asterisks and blanks, using the elements of a numbers’ list to
12689specify the number of asterisks in each column.  This is a repetitive
12690act, which means we can use a decrementing ‘while’ loop or recursive
12691function for the job.  In this section, we will write the definition
12692using a ‘while’ loop.
12693
12694   The ‘column-of-graph’ function requires the height of the graph as an
12695argument, so we should determine and record that as a local variable.
12696
12697   This leads us to the following template for the ‘while’ loop version
12698of this function:
12699
12700     (defun graph-body-print (numbers-list)
12701       "DOCUMENTATION..."
12702       (let ((height  ...
12703              ...))
12704
12705         (while numbers-list
12706           INSERT-COLUMNS-AND-REPOSITION-POINT
12707           (setq numbers-list (cdr numbers-list)))))
12708
12709We need to fill in the slots of the template.
12710
12711   Clearly, we can use the ‘(apply 'max numbers-list)’ expression to
12712determine the height of the graph.
12713
12714   The ‘while’ loop will cycle through the ‘numbers-list’ one element at
12715a time.  As it is shortened by the ‘(setq numbers-list (cdr
12716numbers-list))’ expression, the CAR of each instance of the list is the
12717value of the argument for ‘column-of-graph’.
12718
12719   At each cycle of the ‘while’ loop, the ‘insert-rectangle’ function
12720inserts the list returned by ‘column-of-graph’.  Since the
12721‘insert-rectangle’ function moves point to the lower right of the
12722inserted rectangle, we need to save the location of point at the time
12723the rectangle is inserted, move back to that position after the
12724rectangle is inserted, and then move horizontally to the next place from
12725which ‘insert-rectangle’ is called.
12726
12727   If the inserted columns are one character wide, as they will be if
12728single blanks and asterisks are used, the repositioning command is
12729simply ‘(forward-char 1)’; however, the width of a column may be greater
12730than one.  This means that the repositioning command should be written
12731‘(forward-char symbol-width)’.  The ‘symbol-width’ itself is the length
12732of a ‘graph-blank’ and can be found using the expression ‘(length
12733graph-blank)’.  The best place to bind the ‘symbol-width’ variable to
12734the value of the width of graph column is in the varlist of the ‘let’
12735expression.
12736
12737   These considerations lead to the following function definition:
12738
12739     (defun graph-body-print (numbers-list)
12740       "Print a bar graph of the NUMBERS-LIST.
12741     The numbers-list consists of the Y-axis values."
12742
12743       (let ((height (apply 'max numbers-list))
12744             (symbol-width (length graph-blank))
12745             from-position)
12746
12747         (while numbers-list
12748           (setq from-position (point))
12749           (insert-rectangle
12750            (column-of-graph height (car numbers-list)))
12751           (goto-char from-position)
12752           (forward-char symbol-width)
12753           ;; Draw graph column by column.
12754           (sit-for 0)
12755           (setq numbers-list (cdr numbers-list)))
12756         ;; Place point for X axis labels.
12757         (forward-line height)
12758         (insert "\n")
12759     ))
12760
12761The one unexpected expression in this function is the ‘(sit-for 0)’
12762expression in the ‘while’ loop.  This expression makes the graph
12763printing operation more interesting to watch than it would be otherwise.
12764The expression causes Emacs to “sit” or do nothing for a zero length of
12765time and then redraw the screen.  Placed here, it causes Emacs to redraw
12766the screen column by column.  Without it, Emacs would not redraw the
12767screen until the function exits.
12768
12769   We can test ‘graph-body-print’ with a short list of numbers.
12770
12771  1. Install ‘graph-symbol’, ‘graph-blank’, ‘column-of-graph’, which are
12772     in *note Columns of a graph::, and ‘graph-body-print’.
12773
12774  2. Copy the following expression:
12775
12776          (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
12777
12778  3. Switch to the ‘*scratch*’ buffer and place the cursor where you
12779     want the graph to start.
12780
12781  4. Type ‘M-:’ (‘eval-expression’).
12782
12783  5. Yank the ‘graph-body-print’ expression into the minibuffer with
12784     ‘C-y’ (‘yank)’.
12785
12786  6. Press <RET> to evaluate the ‘graph-body-print’ expression.
12787
12788   Emacs will print a graph like this:
12789
12790                         *
12791                     *   **
12792                     *  ****
12793                    *** ****
12794                   ********* *
12795                  ************
12796                 *************
12797
12798
12799File: eintr.info,  Node: recursive-graph-body-print,  Next: Printed Axes,  Prev: graph-body-print,  Up: Readying a Graph
12800
1280115.2 The ‘recursive-graph-body-print’ Function
12802==============================================
12803
12804The ‘graph-body-print’ function may also be written recursively.  The
12805recursive solution is divided into two parts: an outside wrapper that
12806uses a ‘let’ expression to determine the values of several variables
12807that need only be found once, such as the maximum height of the graph,
12808and an inside function that is called recursively to print the graph.
12809
12810   The wrapper is uncomplicated:
12811
12812     (defun recursive-graph-body-print (numbers-list)
12813       "Print a bar graph of the NUMBERS-LIST.
12814     The numbers-list consists of the Y-axis values."
12815       (let ((height (apply 'max numbers-list))
12816             (symbol-width (length graph-blank))
12817             from-position)
12818         (recursive-graph-body-print-internal
12819          numbers-list
12820          height
12821          symbol-width)))
12822
12823   The recursive function is a little more difficult.  It has four
12824parts: the do-again-test, the printing code, the recursive call, and the
12825next-step-expression.  The do-again-test is a ‘when’ expression that
12826determines whether the ‘numbers-list’ contains any remaining elements;
12827if it does, the function prints one column of the graph using the
12828printing code and calls itself again.  The function calls itself again
12829according to the value produced by the next-step-expression which causes
12830the call to act on a shorter version of the ‘numbers-list’.
12831
12832     (defun recursive-graph-body-print-internal
12833       (numbers-list height symbol-width)
12834       "Print a bar graph.
12835     Used within recursive-graph-body-print function."
12836
12837       (when numbers-list
12838             (setq from-position (point))
12839             (insert-rectangle
12840              (column-of-graph height (car numbers-list)))
12841             (goto-char from-position)
12842             (forward-char symbol-width)
12843             (sit-for 0)     ; Draw graph column by column.
12844             (recursive-graph-body-print-internal
12845              (cdr numbers-list) height symbol-width)))
12846
12847   After installation, this expression can be tested; here is a sample:
12848
12849     (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
12850
12851   Here is what ‘recursive-graph-body-print’ produces:
12852
12853                     *
12854                    **   *
12855                   ****  *
12856                   **** ***
12857                 * *********
12858                 ************
12859                 *************
12860
12861   Either of these two functions, ‘graph-body-print’ or
12862‘recursive-graph-body-print’, create the body of a graph.
12863
12864
12865File: eintr.info,  Node: Printed Axes,  Next: Line Graph Exercise,  Prev: recursive-graph-body-print,  Up: Readying a Graph
12866
1286715.3 Need for Printed Axes
12868==========================
12869
12870A graph needs printed axes, so you can orient yourself.  For a do-once
12871project, it may be reasonable to draw the axes by hand using Emacs’s
12872Picture mode; but a graph drawing function may be used more than once.
12873
12874   For this reason, I have written enhancements to the basic
12875‘print-graph-body’ function that automatically print labels for the
12876horizontal and vertical axes.  Since the label printing functions do not
12877contain much new material, I have placed their description in an
12878appendix.  *Note A Graph with Labeled Axes: Full Graph.
12879
12880
12881File: eintr.info,  Node: Line Graph Exercise,  Prev: Printed Axes,  Up: Readying a Graph
12882
1288315.4 Exercise
12884=============
12885
12886Write a line graph version of the graph printing functions.
12887
12888
12889File: eintr.info,  Node: Emacs Initialization,  Next: Debugging,  Prev: Readying a Graph,  Up: Top
12890
1289116 Your ‘.emacs’ File
12892*********************
12893
12894“You don’t have to like Emacs to like it”—this seemingly paradoxical
12895statement is the secret of GNU Emacs.  The plain, out-of-the-box Emacs
12896is a generic tool.  Most people who use it customize it to suit
12897themselves.
12898
12899   GNU Emacs is mostly written in Emacs Lisp; this means that by writing
12900expressions in Emacs Lisp you can change or extend Emacs.
12901
12902* Menu:
12903
12904* Default Configuration::
12905* Site-wide Init::              You can write site-wide init files.
12906* defcustom::                   Emacs will write code for you.
12907* Beginning init File::         How to write a ‘.emacs’ init file.
12908* Text and Auto-fill::          Automatically wrap lines.
12909* Mail Aliases::                Use abbreviations for email addresses.
12910* Indent Tabs Mode::            Don’t use tabs with TeX
12911* Keybindings::                 Create some personal keybindings.
12912* Keymaps::                     More about key binding.
12913* Loading Files::               Load (i.e., evaluate) files automatically.
12914* Autoload::                    Make functions available.
12915* Simple Extension::            Define a function; bind it to a key.
12916* X11 Colors::                  Colors in X.
12917* Miscellaneous::
12918* Mode Line::                   How to customize your mode line.
12919
12920
12921File: eintr.info,  Node: Default Configuration,  Next: Site-wide Init,  Up: Emacs Initialization
12922
12923Emacs’s Default Configuration
12924=============================
12925
12926There are those who appreciate Emacs’s default configuration.  After
12927all, Emacs starts you in C mode when you edit a C file, starts you in
12928Fortran mode when you edit a Fortran file, and starts you in Fundamental
12929mode when you edit an unadorned file.  This all makes sense, if you do
12930not know who is going to use Emacs.  Who knows what a person hopes to do
12931with an unadorned file?  Fundamental mode is the right default for such
12932a file, just as C mode is the right default for editing C code.  (Enough
12933programming languages have syntaxes that enable them to share or nearly
12934share features, so C mode is now provided by CC mode, the C Collection.)
12935
12936   But when you do know who is going to use Emacs—you, yourself—then it
12937makes sense to customize Emacs.
12938
12939   For example, I seldom want Fundamental mode when I edit an otherwise
12940undistinguished file; I want Text mode.  This is why I customize Emacs:
12941so it suits me.
12942
12943   You can customize and extend Emacs by writing or adapting a
12944‘~/.emacs’ file.  This is your personal initialization file; its
12945contents, written in Emacs Lisp, tell Emacs what to do.(1)
12946
12947   A ‘~/.emacs’ file contains Emacs Lisp code.  You can write this code
12948yourself; or you can use Emacs’s ‘customize’ feature to write the code
12949for you.  You can combine your own expressions and auto-written
12950Customize expressions in your ‘.emacs’ file.
12951
12952   (I myself prefer to write my own expressions, except for those,
12953particularly fonts, that I find easier to manipulate using the
12954‘customize’ command.  I combine the two methods.)
12955
12956   Most of this chapter is about writing expressions yourself.  It
12957describes a simple ‘.emacs’ file; for more information, see *note The
12958Init File: (emacs)Init File, and *note The Init File: (elisp)Init File.
12959
12960   ---------- Footnotes ----------
12961
12962   (1) You may also add ‘.el’ to ‘~/.emacs’ and call it a ‘~/.emacs.el12963file.  In the past, you were forbidden to type the extra keystrokes that
12964the name ‘~/.emacs.el’ requires, but now you may.  The new format is
12965consistent with the Emacs Lisp file naming conventions; the old format
12966saves typing.
12967
12968
12969File: eintr.info,  Node: Site-wide Init,  Next: defcustom,  Prev: Default Configuration,  Up: Emacs Initialization
12970
1297116.1 Site-wide Initialization Files
12972===================================
12973
12974In addition to your personal initialization file, Emacs automatically
12975loads various site-wide initialization files, if they exist.  These have
12976the same form as your ‘.emacs’ file, but are loaded by everyone.
12977
12978   Two site-wide initialization files, ‘site-load.el’ and
12979site-init.el’, are loaded into Emacs and then dumped if a dumped
12980version of Emacs is created, as is most common.  (Dumped copies of Emacs
12981load more quickly.  However, once a file is loaded and dumped, a change
12982to it does not lead to a change in Emacs unless you load it yourself or
12983re-dump Emacs.  *Note Building Emacs: (elisp)Building Emacs, and the
12984‘INSTALL’ file.)
12985
12986   Three other site-wide initialization files are loaded automatically
12987each time you start Emacs, if they exist.  These are ‘site-start.el’,
12988which is loaded _before_ your ‘.emacs’ file, and ‘default.el’, and the
12989terminal type file, which are both loaded _after_ your ‘.emacs’ file.
12990
12991   Settings and definitions in your ‘.emacs’ file will overwrite
12992conflicting settings and definitions in a ‘site-start.el’ file, if it
12993exists; but the settings and definitions in a ‘default.el’ or terminal
12994type file will overwrite those in your ‘.emacs’ file.  (You can prevent
12995interference from a terminal type file by setting ‘term-file-prefix’ to
12996‘nil’.  *Note A Simple Extension: Simple Extension.)
12997
12998   The ‘INSTALL’ file that comes in the distribution contains
12999descriptions of the ‘site-init.el’ and ‘site-load.el’ files.
13000
13001   The ‘loadup.el’, ‘startup.el’, and ‘loaddefs.el’ files control
13002loading.  These files are in the ‘lisp’ directory of the Emacs
13003distribution and are worth perusing.
13004
13005   The ‘loaddefs.el’ file contains a good many suggestions as to what to
13006put into your own ‘.emacs’ file, or into a site-wide initialization
13007file.
13008
13009
13010File: eintr.info,  Node: defcustom,  Next: Beginning init File,  Prev: Site-wide Init,  Up: Emacs Initialization
13011
1301216.2 Specifying Variables using ‘defcustom’
13013===========================================
13014
13015You can specify variables using ‘defcustom’ so that you and others can
13016then use Emacs’s ‘customize’ feature to set their values.  (You cannot
13017use ‘customize’ to write function definitions; but you can write
13018‘defuns’ in your ‘.emacs’ file.  Indeed, you can write any Lisp
13019expression in your ‘.emacs’ file.)
13020
13021   The ‘customize’ feature depends on the ‘defcustom’ macro.  Although
13022you can use ‘defvar’ or ‘setq’ for variables that users set, the
13023‘defcustom’ macro is designed for the job.
13024
13025   You can use your knowledge of ‘defvar’ for writing the first three
13026arguments for ‘defcustom’.  The first argument to ‘defcustom’ is the
13027name of the variable.  The second argument is the variable’s initial
13028value, if any; and this value is set only if the value has not already
13029been set.  The third argument is the documentation.
13030
13031   The fourth and subsequent arguments to ‘defcustom’ specify types and
13032options; these are not featured in ‘defvar’.  (These arguments are
13033optional.)
13034
13035   Each of these arguments consists of a keyword followed by a value.
13036Each keyword starts with the colon character ‘:’.
13037
13038   For example, the customizable user option variable ‘text-mode-hook’
13039looks like this:
13040
13041     (defcustom text-mode-hook nil
13042       "Normal hook run when entering Text mode and many related modes."
13043       :type 'hook
13044       :options '(turn-on-auto-fill flyspell-mode)
13045       :group 'wp)
13046
13047The name of the variable is ‘text-mode-hook’; it has no default value;
13048and its documentation string tells you what it does.
13049
13050   The ‘:type’ keyword tells Emacs the kind of data to which
13051‘text-mode-hook’ should be set and how to display the value in a
13052Customization buffer.
13053
13054   The ‘:options’ keyword specifies a suggested list of values for the
13055variable.  Usually, ‘:options’ applies to a hook.  The list is only a
13056suggestion; it is not exclusive; a person who sets the variable may set
13057it to other values; the list shown following the ‘:options’ keyword is
13058intended to offer convenient choices to a user.
13059
13060   Finally, the ‘:group’ keyword tells the Emacs Customization command
13061in which group the variable is located.  This tells where to find it.
13062
13063   The ‘defcustom’ macro recognizes more than a dozen keywords.  For
13064more information, see *note Writing Customization Definitions:
13065(elisp)Customization.
13066
13067   Consider ‘text-mode-hook’ as an example.
13068
13069   There are two ways to customize this variable.  You can use the
13070customization command or write the appropriate expressions yourself.
13071
13072   Using the customization command, you can type:
13073
13074     M-x customize
13075
13076and find that the group for editing files of text is called “Text”.
13077Enter that group.  Text Mode Hook is the first member.  You can click on
13078its various options, such as ‘turn-on-auto-fill’, to set the values.
13079After you click on the button to
13080
13081     Save for Future Sessions
13082
13083Emacs will write an expression into your ‘.emacs’ file.  It will look
13084like this:
13085
13086     (custom-set-variables
13087       ;; custom-set-variables was added by Custom.
13088       ;; If you edit it by hand, you could mess it up, so be careful.
13089       ;; Your init file should contain only one such instance.
13090       ;; If there is more than one, they won't work right.
13091      '(text-mode-hook '(turn-on-auto-fill text-mode-hook-identify)))
13092
13093(The ‘text-mode-hook-identify’ function tells
13094‘toggle-text-mode-auto-fill’ which buffers are in Text mode.  It comes
13095on automatically.)
13096
13097   The ‘custom-set-variables’ function works somewhat differently than a
13098‘setq’.  While I have never learned the differences, I modify the
13099‘custom-set-variables’ expressions in my ‘.emacs’ file by hand: I make
13100the changes in what appears to me to be a reasonable manner and have not
13101had any problems.  Others prefer to use the Customization command and
13102let Emacs do the work for them.
13103
13104   Another ‘custom-set-...’ function is ‘custom-set-faces’.  This
13105function sets the various font faces.  Over time, I have set a
13106considerable number of faces.  Some of the time, I re-set them using
13107‘customize’; other times, I simply edit the ‘custom-set-faces’
13108expression in my ‘.emacs’ file itself.
13109
13110   The second way to customize your ‘text-mode-hook’ is to set it
13111yourself in your ‘.emacs’ file using code that has nothing to do with
13112the ‘custom-set-...’ functions.
13113
13114   When you do this, and later use ‘customize’, you will see a message
13115that says
13116
13117     CHANGED outside Customize; operating on it here may be unreliable.
13118
13119   This message is only a warning.  If you click on the button to
13120
13121     Save for Future Sessions
13122
13123Emacs will write a ‘custom-set-...’ expression near the end of your
13124‘.emacs’ file that will be evaluated after your hand-written expression.
13125It will, therefore, overrule your hand-written expression.  No harm will
13126be done.  When you do this, however, be careful to remember which
13127expression is active; if you forget, you may confuse yourself.
13128
13129   So long as you remember where the values are set, you will have no
13130trouble.  In any event, the values are always set in your initialization
13131file, which is usually called ‘.emacs’.
13132
13133   I myself use ‘customize’ for hardly anything.  Mostly, I write
13134expressions myself.
13135
13136   Incidentally, to be more complete concerning defines: ‘defsubst’
13137defines an inline function.  The syntax is just like that of ‘defun’.
13138‘defconst’ defines a symbol as a constant.  The intent is that neither
13139programs nor users should ever change a value set by ‘defconst’.  (You
13140can change it; the value set is a variable; but please do not.)
13141
13142
13143File: eintr.info,  Node: Beginning init File,  Next: Text and Auto-fill,  Prev: defcustom,  Up: Emacs Initialization
13144
1314516.3 Beginning a ‘.emacs’ File
13146==============================
13147
13148When you start Emacs, it loads your ‘.emacs’ file unless you tell it not
13149to by specifying ‘-q’ on the command line.  (The ‘emacs -q’ command
13150gives you a plain, out-of-the-box Emacs.)
13151
13152   A ‘.emacs’ file contains Lisp expressions.  Often, these are no more
13153than expressions to set values; sometimes they are function definitions.
13154
13155   *Note The Init File ‘~/.emacs’: (emacs)Init File, for a short
13156description of initialization files.
13157
13158   This chapter goes over some of the same ground, but is a walk among
13159extracts from a complete, long-used ‘.emacs’ file—my own.
13160
13161   The first part of the file consists of comments: reminders to myself.
13162By now, of course, I remember these things, but when I started, I did
13163not.
13164
13165     ;;;; Bob's .emacs file
13166     ; Robert J. Chassell
13167     ; 26 September 1985
13168
13169Look at that date!  I started this file a long time ago.  I have been
13170adding to it ever since.
13171
13172     ; Each section in this file is introduced by a
13173     ; line beginning with four semicolons; and each
13174     ; entry is introduced by a line beginning with
13175     ; three semicolons.
13176
13177This describes the usual conventions for comments in Emacs Lisp.
13178Everything on a line that follows a semicolon is a comment.  Two, three,
13179and four semicolons are used as subsection and section markers.  (*Note
13180(elisp)Comments::, for more about comments.)
13181
13182     ;;;; The Help Key
13183     ; Control-h is the help key;
13184     ; after typing control-h, type a letter to
13185     ; indicate the subject about which you want help.
13186     ; For an explanation of the help facility,
13187     ; type control-h two times in a row.
13188
13189Just remember: type ‘C-h’ two times for help.
13190
13191     ; To find out about any mode, type control-h m
13192     ; while in that mode.  For example, to find out
13193     ; about mail mode, enter mail mode and then type
13194     ; control-h m.
13195
13196“Mode help”, as I call this, is very helpful.  Usually, it tells you all
13197you need to know.
13198
13199   Of course, you don’t need to include comments like these in your
13200‘.emacs’ file.  I included them in mine because I kept forgetting about
13201Mode help or the conventions for comments—but I was able to remember to
13202look here to remind myself.
13203
13204
13205File: eintr.info,  Node: Text and Auto-fill,  Next: Mail Aliases,  Prev: Beginning init File,  Up: Emacs Initialization
13206
1320716.4 Text and Auto Fill Mode
13208============================
13209
13210Now we come to the part that turns on Text mode and Auto Fill mode.
13211
13212     ;;; Text mode and Auto Fill mode
13213     ;; The next two lines put Emacs into Text mode
13214     ;; and Auto Fill mode, and are for writers who
13215     ;; want to start writing prose rather than code.
13216     (setq-default major-mode 'text-mode)
13217     (add-hook 'text-mode-hook 'turn-on-auto-fill)
13218
13219   Here is the first part of this ‘.emacs’ file that does something
13220besides remind a forgetful human!
13221
13222   The first of the two lines in parentheses tells Emacs to turn on Text
13223mode when you find a file, _unless_ that file should go into some other
13224mode, such as C mode.
13225
13226   When Emacs reads a file, it looks at the extension to the file name,
13227if any.  (The extension is the part that comes after a ‘.’.)  If the
13228file ends with a ‘.c’ or ‘.h’ extension then Emacs turns on C mode.
13229Also, Emacs looks at first nonblank line of the file; if the line says
13230‘-*- C -*-’, Emacs turns on C mode.  Emacs possesses a list of
13231extensions and specifications that it uses automatically.  In addition,
13232Emacs looks near the last page for a per-buffer, local variables list,
13233if any.
13234
13235   *Note How Major Modes are Chosen: (emacs)Choosing Modes.
13236
13237   *Note Local Variables in Files: (emacs)File Variables.
13238
13239   Now, back to the ‘.emacs’ file.
13240
13241   Here is the line again; how does it work?
13242
13243     (setq major-mode 'text-mode)
13244
13245This line is a short, but complete Emacs Lisp expression.
13246
13247   We are already familiar with ‘setq’.  It sets the following variable,
13248‘major-mode’, to the subsequent value, which is ‘text-mode’.  The
13249single-quote before ‘text-mode’ tells Emacs to deal directly with the
13250‘text-mode’ symbol, not with whatever it might stand for.  *Note Setting
13251the Value of a Variable: set & setq, for a reminder of how ‘setq’ works.
13252The main point is that there is no difference between the procedure you
13253use to set a value in your ‘.emacs’ file and the procedure you use
13254anywhere else in Emacs.
13255
13256   Here is the next line:
13257
13258     (add-hook 'text-mode-hook 'turn-on-auto-fill)
13259
13260In this line, the ‘add-hook’ command adds ‘turn-on-auto-fill’ to the
13261variable.
13262
13263   ‘turn-on-auto-fill’ is the name of a program, that, you guessed it!,
13264turns on Auto Fill mode.
13265
13266   Every time Emacs turns on Text mode, Emacs runs the commands hooked
13267onto Text mode.  So every time Emacs turns on Text mode, Emacs also
13268turns on Auto Fill mode.
13269
13270   In brief, the first line causes Emacs to enter Text mode when you
13271edit a file, unless the file name extension, a first non-blank line, or
13272local variables to tell Emacs otherwise.
13273
13274   Text mode among other actions, sets the syntax table to work
13275conveniently for writers.  In Text mode, Emacs considers an apostrophe
13276as part of a word like a letter; but Emacs does not consider a period or
13277a space as part of a word.  Thus, ‘M-f’ moves you over ‘it's’.  On the
13278other hand, in C mode, ‘M-f’ stops just after the ‘t’ of ‘it's’.
13279
13280   The second line causes Emacs to turn on Auto Fill mode when it turns
13281on Text mode.  In Auto Fill mode, Emacs automatically breaks a line that
13282is too wide and brings the excessively wide part of the line down to the
13283next line.  Emacs breaks lines between words, not within them.
13284
13285   When Auto Fill mode is turned off, lines continue to the right as you
13286type them.  Depending on how you set the value of ‘truncate-lines’, the
13287words you type either disappear off the right side of the screen, or
13288else are shown, in a rather ugly and unreadable manner, as a
13289continuation line on the screen.
13290
13291   In addition, in this part of my ‘.emacs’ file, I tell the Emacs fill
13292commands to insert two spaces after a colon:
13293
13294     (setq colon-double-space t)
13295
13296
13297File: eintr.info,  Node: Mail Aliases,  Next: Indent Tabs Mode,  Prev: Text and Auto-fill,  Up: Emacs Initialization
13298
1329916.5 Mail Aliases
13300=================
13301
13302Here is a ‘setq’ that turns on mail aliases, along with more reminders.
13303
13304     ;;; Message mode
13305     ; To enter message mode, type 'C-x m'
13306     ; To enter RMAIL (for reading mail),
13307     ; type 'M-x rmail'
13308     (setq mail-aliases t)
13309
13310This ‘setq’ sets the value of the variable ‘mail-aliases’ to ‘t’.  Since
13311‘t’ means true, the line says, in effect, “Yes, use mail aliases.”
13312
13313   Mail aliases are convenient short names for long email addresses or
13314for lists of email addresses.  The file where you keep your aliases is
13315‘~/.mailrc’.  You write an alias like this:
13316
13317     alias geo george@foobar.wiz.edu
13318
13319When you write a message to George, address it to ‘geo’; the mailer will
13320automatically expand ‘geo’ to the full address.
13321
13322
13323File: eintr.info,  Node: Indent Tabs Mode,  Next: Keybindings,  Prev: Mail Aliases,  Up: Emacs Initialization
13324
1332516.6 Indent Tabs Mode
13326=====================
13327
13328By default, Emacs inserts tabs in place of multiple spaces when it
13329formats a region.  (For example, you might indent many lines of text all
13330at once with the ‘indent-region’ command.)  Tabs look fine on a terminal
13331or with ordinary printing, but they produce badly indented output when
13332you use TeX or Texinfo since TeX ignores tabs.
13333
13334   The following turns off Indent Tabs mode:
13335
13336     ;;; Prevent Extraneous Tabs
13337     (setq-default indent-tabs-mode nil)
13338
13339   Note that this line uses ‘setq-default’ rather than the ‘setq’ that
13340we have seen before; ‘setq-default’ sets values only in buffers that do
13341not have their own local values for the variable.
13342
13343   *Note Tabs vs. Spaces: (emacs)Just Spaces.
13344
13345   *Note Local Variables in Files: (emacs)File Variables.
13346
13347
13348File: eintr.info,  Node: Keybindings,  Next: Keymaps,  Prev: Indent Tabs Mode,  Up: Emacs Initialization
13349
1335016.7 Some Keybindings
13351=====================
13352
13353Now for some personal keybindings:
13354
13355     ;;; Compare windows
13356     (global-set-key "\C-cw" 'compare-windows)
13357
13358   ‘compare-windows’ is a nifty command that compares the text in your
13359current window with text in the next window.  It makes the comparison by
13360starting at point in each window, moving over text in each window as far
13361as they match.  I use this command all the time.
13362
13363   This also shows how to set a key globally, for all modes.
13364
13365   The command is ‘global-set-key’.  It is followed by the keybinding.
13366In a ‘.emacs’ file, the keybinding is written as shown: ‘\C-c’ stands
13367for Control-C, which means to press the control key and the ‘c’ key at
13368the same time.  The ‘w’ means to press the ‘w’ key.  The keybinding is
13369surrounded by double quotation marks.  In documentation, you would write
13370this as ‘C-c w’.  (If you were binding a <META> key, such as ‘M-c’,
13371rather than a <CTRL> key, you would write ‘\M-c’ in your ‘.emacs’ file.
13372*Note Rebinding Keys in Your Init File: (emacs)Init Rebinding, for
13373details.)
13374
13375   The command invoked by the keys is ‘compare-windows’.  Note that
13376‘compare-windows’ is preceded by a single-quote; otherwise, Emacs would
13377first try to evaluate the symbol to determine its value.
13378
13379   These three things, the double quotation marks, the backslash before
13380the ‘C’, and the single-quote are necessary parts of keybinding that I
13381tend to forget.  Fortunately, I have come to remember that I should look
13382at my existing ‘.emacs’ file, and adapt what is there.
13383
13384   As for the keybinding itself: ‘C-c w’.  This combines the prefix key,
13385‘C-c’, with a single character, in this case, ‘w’.  This set of keys,
13386‘C-c’ followed by a single character, is strictly reserved for
13387individuals’ own use.  (I call these “own” keys, since these are for my
13388own use.)  You should always be able to create such a keybinding for
13389your own use without stomping on someone else’s keybinding.  If you ever
13390write an extension to Emacs, please avoid taking any of these keys for
13391public use.  Create a key like ‘C-c C-w’ instead.  Otherwise, we will
13392run out of own keys.
13393
13394   Here is another keybinding, with a comment:
13395
13396     ;;; Keybinding for 'occur'
13397     ; I use occur a lot, so let's bind it to a key:
13398     (global-set-key "\C-co" 'occur)
13399
13400   The ‘occur’ command shows all the lines in the current buffer that
13401contain a match for a regular expression.  When the region is active,
13402‘occur’ restricts matches to such region.  Otherwise it uses the entire
13403buffer.  Matching lines are shown in a buffer called ‘*Occur*’.  That
13404buffer serves as a menu to jump to occurrences.
13405
13406   Here is how to unbind a key, so it does not work:
13407
13408     ;;; Unbind 'C-x f'
13409     (global-unset-key "\C-xf")
13410
13411   There is a reason for this unbinding: I found I inadvertently typed
13412‘C-x f’ when I meant to type ‘C-x C-f’.  Rather than find a file, as I
13413intended, I accidentally set the width for filled text, almost always to
13414a width I did not want.  Since I hardly ever reset my default width, I
13415simply unbound the key.
13416
13417   The following rebinds an existing key:
13418
13419     ;;; Rebind 'C-x C-b' for 'buffer-menu'
13420     (global-set-key "\C-x\C-b" 'buffer-menu)
13421
13422   By default, ‘C-x C-b’ runs the ‘list-buffers’ command.  This command
13423lists your buffers in _another_ window.  Since I almost always want to
13424do something in that window, I prefer the ‘buffer-menu’ command, which
13425not only lists the buffers, but moves point into that window.
13426
13427
13428File: eintr.info,  Node: Keymaps,  Next: Loading Files,  Prev: Keybindings,  Up: Emacs Initialization
13429
1343016.8 Keymaps
13431============
13432
13433Emacs uses “keymaps” to record which keys call which commands.  When you
13434use ‘global-set-key’ to set the keybinding for a single command in all
13435parts of Emacs, you are specifying the keybinding in
13436‘current-global-map’.
13437
13438   Specific modes, such as C mode or Text mode, have their own keymaps;
13439the mode-specific keymaps override the global map that is shared by all
13440buffers.
13441
13442   The ‘global-set-key’ function binds, or rebinds, the global keymap.
13443For example, the following binds the key ‘C-x C-b’ to the function
13444‘buffer-menu’:
13445
13446     (global-set-key "\C-x\C-b" 'buffer-menu)
13447
13448   Mode-specific keymaps are bound using the ‘define-key’ function,
13449which takes a specific keymap as an argument, as well as the key and the
13450command.  For example, my ‘.emacs’ file contains the following
13451expression to bind the ‘texinfo-insert-@group’ command to ‘C-c C-c g’:
13452
13453     (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@group)
13454
13455The ‘texinfo-insert-@group’ function itself is a little extension to
13456Texinfo mode that inserts ‘@group’ into a Texinfo file.  I use this
13457command all the time and prefer to type the three strokes ‘C-c C-c g’
13458rather than the six strokes ‘@ g r o u p’.  (‘@group’ and its matching
13459‘@end group’ are commands that keep all enclosed text together on one
13460page; many multi-line examples in this book are surrounded by ‘@group
13461... @end group’.)
13462
13463   Here is the ‘texinfo-insert-@group’ function definition:
13464
13465     (defun texinfo-insert-@group ()
13466       "Insert the string @group in a Texinfo buffer."
13467       (interactive)
13468       (beginning-of-line)
13469       (insert "@group\n"))
13470
13471   (Of course, I could have used Abbrev mode to save typing, rather than
13472write a function to insert a word; but I prefer key strokes consistent
13473with other Texinfo mode key bindings.)
13474
13475   You will see numerous ‘define-key’ expressions in ‘loaddefs.el’ as
13476well as in the various mode libraries, such as ‘cc-mode.el’ and
13477lisp-mode.el’.
13478
13479   *Note Customizing Key Bindings: (emacs)Key Bindings, and *note
13480Keymaps: (elisp)Keymaps, for more information about keymaps.
13481
13482
13483File: eintr.info,  Node: Loading Files,  Next: Autoload,  Prev: Keymaps,  Up: Emacs Initialization
13484
1348516.9 Loading Files
13486==================
13487
13488Many people in the GNU Emacs community have written extensions to Emacs.
13489As time goes by, these extensions are often included in new releases.
13490For example, the Calendar and Diary packages are now part of the
13491standard GNU Emacs, as is Calc.
13492
13493   You can use a ‘load’ command to evaluate a complete file and thereby
13494install all the functions and variables in the file into Emacs.  For
13495example:
13496
13497     (load "~/emacs/slowsplit")
13498
13499   This evaluates, i.e., loads, the ‘slowsplit.el’ file or if it exists,
13500the faster, byte compiled ‘slowsplit.elc’ file from the ‘emacs’
13501sub-directory of your home directory.  The file contains the function
13502‘split-window-quietly’, which John Robinson wrote in 1989.
13503
13504   The ‘split-window-quietly’ function splits a window with the minimum
13505of redisplay.  I installed it in 1989 because it worked well with the
13506slow 1200 baud terminals I was then using.  Nowadays, I only
13507occasionally come across such a slow connection, but I continue to use
13508the function because I like the way it leaves the bottom half of a
13509buffer in the lower of the new windows and the top half in the upper
13510window.
13511
13512   To replace the key binding for the default ‘split-window-vertically’,
13513you must also unset that key and bind the keys to
13514‘split-window-quietly’, like this:
13515
13516     (global-unset-key "\C-x2")
13517     (global-set-key "\C-x2" 'split-window-quietly)
13518
13519   If you load many extensions, as I do, then instead of specifying the
13520exact location of the extension file, as shown above, you can specify
13521that directory as part of Emacs’s ‘load-path’.  Then, when Emacs loads a
13522file, it will search that directory as well as its default list of
13523directories.  (The default list is specified in ‘paths.h’ when Emacs is
13524built.)
13525
13526   The following command adds your ‘~/emacs’ directory to the existing
13527load path:
13528
13529     ;;; Emacs Load Path
13530     (setq load-path (cons "~/emacs" load-path))
13531
13532   Incidentally, ‘load-library’ is an interactive interface to the
13533‘load’ function.  The complete function looks like this:
13534
13535     (defun load-library (library)
13536       "Load the Emacs Lisp library named LIBRARY.
13537     This is an interface to the function `load'.  LIBRARY is searched
13538     for in `load-path', both with and without `load-suffixes' (as
13539     well as `load-file-rep-suffixes').
13540
13541     See Info node `(emacs)Lisp Libraries' for more details.
13542     See `load-file' for a different interface to `load'."
13543       (interactive
13544        (list (completing-read "Load library: "
13545                               (apply-partially 'locate-file-completion-table
13546                                                load-path
13547                                                (get-load-suffixes)))))
13548       (load library))
13549
13550   The name of the function, ‘load-library’, comes from the use of
13551“library” as a conventional synonym for “file”.  The source for the
13552‘load-library’ command is in the ‘files.el’ library.
13553
13554   Another interactive command that does a slightly different job is
13555‘load-file’.  *Note Libraries of Lisp Code for Emacs: (emacs)Lisp
13556Libraries, for information on the distinction between ‘load-library’ and
13557this command.
13558
13559
13560File: eintr.info,  Node: Autoload,  Next: Simple Extension,  Prev: Loading Files,  Up: Emacs Initialization
13561
1356216.10 Autoloading
13563=================
13564
13565Instead of installing a function by loading the file that contains it,
13566or by evaluating the function definition, you can make the function
13567available but not actually install it until it is first called.  This is
13568called “autoloading”.
13569
13570   When you execute an autoloaded function, Emacs automatically
13571evaluates the file that contains the definition, and then calls the
13572function.
13573
13574   Emacs starts quicker with autoloaded functions, since their libraries
13575are not loaded right away; but you need to wait a moment when you first
13576use such a function, while its containing file is evaluated.
13577
13578   Rarely used functions are frequently autoloaded.  The ‘loaddefs.el13579library contains thousands of autoloaded functions, from ‘5x5’ to
13580‘zone’.  Of course, you may come to use a rare function frequently.
13581When you do, you should load that function’s file with a ‘load’
13582expression in your ‘.emacs’ file.
13583
13584   In my ‘.emacs’ file, I load 14 libraries that contain functions that
13585would otherwise be autoloaded.  (Actually, it would have been better to
13586include these files in my dumped Emacs, but I forgot.  *Note Building
13587Emacs: (elisp)Building Emacs, and the ‘INSTALL’ file for more about
13588dumping.)
13589
13590   You may also want to include autoloaded expressions in your ‘.emacs’
13591file.  ‘autoload’ is a built-in function that takes up to five
13592arguments, the final three of which are optional.  The first argument is
13593the name of the function to be autoloaded; the second is the name of the
13594file to be loaded.  The third argument is documentation for the
13595function, and the fourth tells whether the function can be called
13596interactively.  The fifth argument tells what type of object—‘autoload’
13597can handle a keymap or macro as well as a function (the default is a
13598function).
13599
13600   Here is a typical example:
13601
13602     (autoload 'html-helper-mode
13603       "html-helper-mode" "Edit HTML documents" t)
13604
13605(‘html-helper-mode’ is an older alternative to ‘html-mode’, which is a
13606standard part of the distribution.)
13607
13608This expression autoloads the ‘html-helper-mode’ function.  It takes it
13609from the ‘html-helper-mode.el’ file (or from the byte compiled version
13610html-helper-mode.elc’, if that exists.)  The file must be located in a
13611directory specified by ‘load-path’.  The documentation says that this is
13612a mode to help you edit documents written in the HyperText Markup
13613Language.  You can call this mode interactively by typing ‘M-x
13614html-helper-mode’.  (You need to duplicate the function’s regular
13615documentation in the autoload expression because the regular function is
13616not yet loaded, so its documentation is not available.)
13617
13618   *Note Autoload: (elisp)Autoload, for more information.
13619
13620
13621File: eintr.info,  Node: Simple Extension,  Next: X11 Colors,  Prev: Autoload,  Up: Emacs Initialization
13622
1362316.11 A Simple Extension: ‘line-to-top-of-window’
13624=================================================
13625
13626Here is a simple extension to Emacs that moves the line point is on to
13627the top of the window.  I use this all the time, to make text easier to
13628read.
13629
13630   You can put the following code into a separate file and then load it
13631from your ‘.emacs’ file, or you can include it within your ‘.emacs’
13632file.
13633
13634   Here is the definition:
13635
13636     ;;; Line to top of window;
13637     ;;; replace three keystroke sequence  C-u 0 C-l
13638     (defun line-to-top-of-window ()
13639       "Move the line point is on to top of window."
13640       (interactive)
13641       (recenter 0))
13642
13643   Now for the keybinding.
13644
13645   Nowadays, function keys as well as mouse button events and non-ASCII
13646characters are written within square brackets, without quotation marks.
13647(In Emacs version 18 and before, you had to write different function key
13648bindings for each different make of terminal.)
13649
13650   I bind ‘line-to-top-of-window’ to my <F6> function key like this:
13651
13652     (global-set-key [f6] 'line-to-top-of-window)
13653
13654   For more information, see *note Rebinding Keys in Your Init File:
13655(emacs)Init Rebinding.
13656
13657   If you run two versions of GNU Emacs, such as versions 22 and 23, and
13658use one ‘.emacs’ file, you can select which code to evaluate with the
13659following conditional:
13660
13661     (cond
13662      ((= 22 emacs-major-version)
13663       ;; evaluate version 22 code
13664       ( ... ))
13665      ((= 23 emacs-major-version)
13666       ;; evaluate version 23 code
13667       ( ... )))
13668
13669   For example, recent versions blink their cursors by default.  I hate
13670such blinking, as well as other features, so I placed the following in
13671my ‘.emacs’ file(1):
13672
13673     (when (>= emacs-major-version 21)
13674       (blink-cursor-mode 0)
13675       ;; Insert newline when you press 'C-n' (next-line)
13676       ;; at the end of the buffer
13677       (setq next-line-add-newlines t)
13678       ;; Turn on image viewing
13679       (auto-image-file-mode t)
13680       ;; Turn on menu bar (this bar has text)
13681       ;; (Use numeric argument to turn on)
13682       (menu-bar-mode 1)
13683       ;; Turn off tool bar (this bar has icons)
13684       ;; (Use numeric argument to turn on)
13685       (tool-bar-mode nil)
13686       ;; Turn off tooltip mode for tool bar
13687       ;; (This mode causes icon explanations to pop up)
13688       ;; (Use numeric argument to turn on)
13689       (tooltip-mode nil)
13690       ;; If tooltips turned on, make tips appear promptly
13691       (setq tooltip-delay 0.1)  ; default is 0.7 second
13692        )
13693
13694   ---------- Footnotes ----------
13695
13696   (1) When I start instances of Emacs that do not load my ‘.emacs’ file
13697or any site file, I also turn off blinking:
13698
13699     emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
13700
13701Or nowadays, using an even more sophisticated set of options,
13702
13703     emacs -Q -D
13704
13705
13706File: eintr.info,  Node: X11 Colors,  Next: Miscellaneous,  Prev: Simple Extension,  Up: Emacs Initialization
13707
1370816.12 X11 Colors
13709================
13710
13711You can specify colors when you use Emacs with the MIT X Windowing
13712system.
13713
13714   I dislike the default colors and specify my own.
13715
13716   Here are the expressions in my ‘.emacs’ file that set values:
13717
13718     ;; Set cursor color
13719     (set-cursor-color "white")
13720
13721     ;; Set mouse color
13722     (set-mouse-color "white")
13723
13724     ;; Set foreground and background
13725     (set-foreground-color "white")
13726     (set-background-color "darkblue")
13727
13728     ;;; Set highlighting colors for isearch and drag
13729     (set-face-foreground 'highlight "white")
13730     (set-face-background 'highlight "blue")
13731
13732     (set-face-foreground 'region "cyan")
13733     (set-face-background 'region "blue")
13734
13735     (set-face-foreground 'secondary-selection "skyblue")
13736     (set-face-background 'secondary-selection "darkblue")
13737
13738     ;; Set calendar highlighting colors
13739     (with-eval-after-load 'calendar
13740       (set-face-foreground 'diary   "skyblue")
13741       (set-face-background 'holiday "slate blue")
13742       (set-face-foreground 'holiday "white"))
13743
13744   The various shades of blue soothe my eye and prevent me from seeing
13745the screen flicker.
13746
13747   Alternatively, I could have set my specifications in various X
13748initialization files.  For example, I could set the foreground,
13749background, cursor, and pointer (i.e., mouse) colors in my
13750‘~/.Xresources’ file like this:
13751
13752     Emacs*foreground:   white
13753     Emacs*background:   darkblue
13754     Emacs*cursorColor:  white
13755     Emacs*pointerColor: white
13756
13757   In any event, since it is not part of Emacs, I set the root color of
13758my X window in my ‘~/.xinitrc’ file, like this(1):
13759
13760     xsetroot -solid Navy -fg white &
13761
13762   ---------- Footnotes ----------
13763
13764   (1) I also run more modern window managers, such as Enlightenment,
13765Gnome, or KDE; in those cases, I often specify an image rather than a
13766plain color.
13767
13768
13769File: eintr.info,  Node: Miscellaneous,  Next: Mode Line,  Prev: X11 Colors,  Up: Emacs Initialization
13770
1377116.13 Miscellaneous Settings for a ‘.emacs’ File
13772================================================
13773
13774Here are a few miscellaneous settings:
13775
13776   − Set the shape and color of the mouse cursor:
13777
13778          ; Cursor shapes are defined in
13779          ; '/usr/include/X11/cursorfont.h';
13780          ; for example, the 'target' cursor is number 128;
13781          ; the 'top_left_arrow' cursor is number 132.
13782
13783          (let ((mpointer (x-get-resource "*mpointer"
13784                                          "*emacs*mpointer")))
13785            ;; If you have not set your mouse pointer
13786            ;;     then set it, otherwise leave as is:
13787            (if (eq mpointer nil)
13788                (setq mpointer "132")) ; top_left_arrow
13789            (setq x-pointer-shape (string-to-number mpointer))
13790            (set-mouse-color "white"))
13791
13792   − Or you can set the values of a variety of features in an alist,
13793     like this:
13794
13795          (setq-default
13796           default-frame-alist
13797           '((cursor-color . "white")
13798             (mouse-color . "white")
13799             (foreground-color . "white")
13800             (background-color . "DodgerBlue4")
13801             ;; (cursor-type . bar)
13802             (cursor-type . box)
13803             (tool-bar-lines . 0)
13804             (menu-bar-lines . 1)
13805             (width . 80)
13806             (height . 58)
13807             (font .
13808                   "-Misc-Fixed-Medium-R-Normal--20-200-75-75-C-100-ISO8859-1")
13809             ))
13810
13811   − Convert ‘<CTRL>-h’ into <DEL> and <DEL> into ‘<CTRL>-h’.
13812     (Some older keyboards needed this, although I have not seen the
13813     problem recently.)
13814
13815          ;; Translate 'C-h' to <DEL>.
13816          ; (keyboard-translate ?\C-h ?\C-?)
13817
13818          ;; Translate <DEL> to 'C-h'.
13819          (keyboard-translate ?\C-? ?\C-h)
13820
13821   − Turn off a blinking cursor!
13822
13823          (if (fboundp 'blink-cursor-mode)
13824              (blink-cursor-mode -1))
13825
13826     or start GNU Emacs with the command ‘emacs -nbc’.
13827
13828   − When using ‘grep’
13829     ‘-i’   Ignore case distinctions
13830     ‘-n’   Prefix each line of output with line number
13831     ‘-H’   Print the filename for each match.
13832     ‘-e’   Protect patterns beginning with a hyphen character, ‘-’
13833
13834          (setq grep-command "grep -i -nH -e ")
13835
13836   − Find an existing buffer, even if it has a different name
13837     This avoids problems with symbolic links.
13838
13839          (setq find-file-existing-other-name t)
13840
13841   − Set your language environment and default input method
13842
13843          (set-language-environment "latin-1")
13844          ;; Remember you can enable or disable multilingual text input
13845          ;; with the toggle-input-method' (C-\) command
13846          (setq default-input-method "latin-1-prefix")
13847
13848     If you want to write with Chinese GB characters, set this instead:
13849
13850          (set-language-environment "Chinese-GB")
13851          (setq default-input-method "chinese-tonepy")
13852
13853Fixing Unpleasant Key Bindings
13854..............................
13855
13856Some systems bind keys unpleasantly.  Sometimes, for example, the <CTRL>
13857key appears in an awkward spot rather than at the far left of the home
13858row.
13859
13860   Usually, when people fix these sorts of keybindings, they do not
13861change their ‘~/.emacs’ file.  Instead, they bind the proper keys on
13862their consoles with the ‘loadkeys’ or ‘install-keymap’ commands in their
13863boot script and then include ‘xmodmap’ commands in their ‘.xinitrc’ or
13864‘.Xsession’ file for X Windows.
13865
13866For a boot script:
13867
13868     loadkeys /usr/share/keymaps/i386/qwerty/emacs2.kmap.gz
13869or
13870     install-keymap emacs2
13871
13872For a ‘.xinitrc’ or ‘.Xsession’ file when the <Caps Lock> key is at the
13873far left of the home row:
13874
13875     # Bind the key labeled 'Caps Lock' to 'Control'
13876     # (Such a broken user interface suggests that keyboard manufacturers
13877     # think that computers are typewriters from 1885.)
13878
13879     xmodmap -e "clear Lock"
13880     xmodmap -e "add Control = Caps_Lock"
13881
13882In a ‘.xinitrc’ or ‘.Xsession’ file, to convert an <ALT> key to a <META>
13883key:
13884
13885     # Some ill designed keyboards have a key labeled ALT and no Meta
13886     xmodmap -e "keysym Alt_L = Meta_L Alt_L"
13887
13888
13889File: eintr.info,  Node: Mode Line,  Prev: Miscellaneous,  Up: Emacs Initialization
13890
1389116.14 A Modified Mode Line
13892==========================
13893
13894Finally, a feature I really like: a modified mode line.
13895
13896   When I work over a network, I forget which machine I am using.  Also,
13897I tend to I lose track of where I am, and which line point is on.
13898
13899   So I reset my mode line to look like this:
13900
13901     -:-- foo.texi   rattlesnake:/home/bob/  Line 1  (Texinfo Fill) Top
13902
13903   I am visiting a file called ‘foo.texi’, on my machine ‘rattlesnake’
13904in my ‘/home/bob’ buffer.  I am on line 1, in Texinfo mode, and am at
13905the top of the buffer.
13906
13907   My ‘.emacs’ file has a section that looks like this:
13908
13909     ;; Set a Mode Line that tells me which machine, which directory,
13910     ;; and which line I am on, plus the other customary information.
13911     (setq-default mode-line-format
13912      (quote
13913       (#("-" 0 1
13914          (help-echo
13915           "mouse-1: select window, mouse-2: delete others ..."))
13916        mode-line-mule-info
13917        mode-line-modified
13918        mode-line-frame-identification
13919        "    "
13920        mode-line-buffer-identification
13921        "    "
13922        (:eval (substring
13923                (system-name) 0 (string-match "\\..+" (system-name))))
13924        ":"
13925        default-directory
13926        #(" " 0 1
13927          (help-echo
13928           "mouse-1: select window, mouse-2: delete others ..."))
13929        (line-number-mode " Line %l ")
13930        global-mode-string
13931        #("   %[(" 0 6
13932          (help-echo
13933           "mouse-1: select window, mouse-2: delete others ..."))
13934        (:eval (format-time-string "%F"))
13935        mode-line-process
13936        minor-mode-alist
13937        #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
13938        ")%] "
13939        (-3 . "%P")
13940        ;;   "-%-"
13941        )))
13942
13943Here, I redefine the default mode line.  Most of the parts are from the
13944original; but I make a few changes.  I set the _default_ mode line
13945format so as to permit various modes, such as Info, to override it.
13946
13947   Many elements in the list are self-explanatory: ‘mode-line-modified’
13948is a variable that tells whether the buffer has been modified,
13949‘mode-name’ tells the name of the mode, and so on.  However, the format
13950looks complicated because of two features we have not discussed.
13951
13952   The first string in the mode line is a dash or hyphen, ‘-’.  In the
13953old days, it would have been specified simply as ‘"-"’.  But nowadays,
13954Emacs can add properties to a string, such as highlighting or, as in
13955this case, a help feature.  If you place your mouse cursor over the
13956hyphen, some help information appears (By default, you must wait
13957seven-tenths of a second before the information appears.  You can change
13958that timing by changing the value of ‘tooltip-delay’.)
13959
13960   The new string format has a special syntax:
13961
13962     #("-" 0 1 (help-echo "mouse-1: select window, ..."))
13963
13964The ‘#(’ begins a list.  The first element of the list is the string
13965itself, just one ‘-’.  The second and third elements specify the range
13966over which the fourth element applies.  A range starts _after_ a
13967character, so a zero means the range starts just before the first
13968character; a 1 means that the range ends just after the first character.
13969The third element is the property for the range.  It consists of a
13970property list, a property name, in this case, ‘help-echo’, followed by a
13971value, in this case, a string.  The second, third, and fourth elements
13972of this new string format can be repeated.
13973
13974   *Note Text Properties: (elisp)Text Properties, and see *note Mode
13975Line Format: (elisp)Mode Line Format, for more information.
13976
13977   ‘mode-line-buffer-identification’ displays the current buffer name.
13978It is a list beginning ‘(#("%12b" 0 4 ...’.  The ‘#(’ begins the list.
13979
13980   The ‘"%12b"’ displays the current buffer name, using the
13981‘buffer-name’ function with which we are familiar; the ‘12’ specifies
13982the maximum number of characters that will be displayed.  When a name
13983has fewer characters, whitespace is added to fill out to this number.
13984(Buffer names can and often should be longer than 12 characters; this
13985length works well in a typical 80 column wide window.)
13986
13987   ‘:eval’ says to evaluate the following form and use the result as a
13988string to display.  In this case, the expression displays the first
13989component of the full system name.  The end of the first component is a
13990‘.’ (period), so I use the ‘string-match’ function to tell me the length
13991of the first component.  The substring from the zeroth character to that
13992length is the name of the machine.
13993
13994   This is the expression:
13995
13996     (:eval (substring
13997             (system-name) 0 (string-match "\\..+" (system-name))))
13998
13999   ‘%[’ and ‘%]’ cause a pair of square brackets to appear for each
14000recursive editing level.  ‘%n’ says “Narrow” when narrowing is in
14001effect.  ‘%P’ tells you the percentage of the buffer that is above the
14002bottom of the window, or “Top”, “Bottom”, or “All”.  (A lower case ‘p’
14003tell you the percentage above the _top_ of the window.)  ‘%-’ inserts
14004enough dashes to fill out the line.
14005
14006   Remember, you don’t have to like Emacs to like it—your own Emacs can
14007have different colors, different commands, and different keys than a
14008default Emacs.
14009
14010   On the other hand, if you want to bring up a plain out-of-the-box
14011Emacs, with no customization, type:
14012
14013     emacs -q
14014
14015This will start an Emacs that does _not_ load your ‘~/.emacs’
14016initialization file.  A plain, default Emacs.  Nothing more.
14017
14018
14019File: eintr.info,  Node: Debugging,  Next: Conclusion,  Prev: Emacs Initialization,  Up: Top
14020
1402117 Debugging
14022************
14023
14024GNU Emacs has two debuggers, ‘debug’ and ‘edebug’.  The first is built
14025into the internals of Emacs and is always with you; the second requires
14026that you instrument a function before you can use it.
14027
14028   Both debuggers are described extensively in *note Debugging Lisp
14029Programs: (elisp)Debugging.  In this chapter, I will walk through a
14030short example of each.
14031
14032* Menu:
14033
14034* debug::                       How to use the built-in debugger.
14035* debug-on-entry::              Start debugging when you call a function.
14036* debug-on-quit::               Start debugging when you quit with ‘C-g’.
14037* edebug::                      How to use Edebug, a source level debugger.
14038* Debugging Exercises::
14039
14040
14041File: eintr.info,  Node: debug,  Next: debug-on-entry,  Up: Debugging
14042
1404317.1 ‘debug’
14044============
14045
14046Suppose you have written a function definition that is intended to
14047return the sum of the numbers 1 through a given number.  (This is the
14048‘triangle’ function discussed earlier.  *Note Example with Decrementing
14049Counter: Decrementing Example, for a discussion.)
14050
14051   However, your function definition has a bug.  You have mistyped ‘1=’
14052for ‘1-’.  Here is the broken definition:
14053
14054     (defun triangle-bugged (number)
14055       "Return sum of numbers 1 through NUMBER inclusive."
14056       (let ((total 0))
14057         (while (> number 0)
14058           (setq total (+ total number))
14059           (setq number (1= number)))      ; Error here.
14060         total))
14061
14062   If you are reading this in Info, you can evaluate this definition in
14063the normal fashion.  You will see ‘triangle-bugged’ appear in the echo
14064area.
14065
14066   Now evaluate the ‘triangle-bugged’ function with an argument of 4:
14067
14068     (triangle-bugged 4)
14069
14070In a recent GNU Emacs, you will create and enter a ‘*Backtrace*’ buffer
14071that says:
14072
14073     ---------- Buffer: *Backtrace* ----------
14074     Debugger entered--Lisp error: (void-function 1=)
14075       (1= number)
14076       (setq number (1= number))
14077       (while (> number 0) (setq total (+ total number))
14078             (setq number (1= number)))
14079       (let ((total 0)) (while (> number 0) (setq total ...)
14080         (setq number ...)) total)
14081       triangle-bugged(4)
14082       eval((triangle-bugged 4) nil)
14083       eval-expression((triangle-bugged 4) nil nil 127)
14084       funcall-interactively(eval-expression (triangle-bugged 4) nil nil 127)
14085       call-interactively(eval-expression nil nil)
14086       command-execute(eval-expression)
14087     ---------- Buffer: *Backtrace* ----------
14088
14089(I have reformatted this example slightly; the debugger does not fold
14090long lines.  As usual, you can quit the debugger by typing ‘q’ in the
14091‘*Backtrace*’ buffer.)
14092
14093   In practice, for a bug as simple as this, the Lisp error line will
14094tell you what you need to know to correct the definition.  The function
14095‘1=’ is void.
14096
14097   However, suppose you are not quite certain what is going on?  You can
14098read the complete backtrace.
14099
14100   In this case, you need to run a recent GNU Emacs, which automatically
14101starts the debugger that puts you in the ‘*Backtrace*’ buffer; or else,
14102you need to start the debugger manually as described below.
14103
14104   Read the ‘*Backtrace*’ buffer from the bottom up; it tells you what
14105Emacs did that led to the error.  Emacs made an interactive call to ‘C-x
14106C-e’ (‘eval-last-sexp’), which led to the evaluation of the
14107‘triangle-bugged’ expression.  Each line above tells you what the Lisp
14108interpreter evaluated next.
14109
14110   The third line from the top of the buffer is
14111
14112     (setq number (1= number))
14113
14114Emacs tried to evaluate this expression; in order to do so, it tried to
14115evaluate the inner expression shown on the second line from the top:
14116
14117     (1= number)
14118
14119This is where the error occurred; as the top line says:
14120
14121     Debugger entered--Lisp error: (void-function 1=)
14122
14123You can correct the mistake, re-evaluate the function definition, and
14124then run your test again.
14125
14126
14127File: eintr.info,  Node: debug-on-entry,  Next: debug-on-quit,  Prev: debug,  Up: Debugging
14128
1412917.2 ‘debug-on-entry’
14130=====================
14131
14132A recent GNU Emacs starts the debugger automatically when your function
14133has an error.
14134
14135   Incidentally, you can start the debugger manually for all versions of
14136Emacs; the advantage is that the debugger runs even if you do not have a
14137bug in your code.  Sometimes your code will be free of bugs!
14138
14139   You can enter the debugger when you call the function by calling
14140‘debug-on-entry’.
14141
14142Type:
14143
14144     M-x debug-on-entry <RET> triangle-bugged <RET>
14145
14146Now, evaluate the following:
14147
14148     (triangle-bugged 5)
14149
14150All versions of Emacs will create a ‘*Backtrace*’ buffer and tell you
14151that it is beginning to evaluate the ‘triangle-bugged’ function:
14152
14153     ---------- Buffer: *Backtrace* ----------
14154     Debugger entered--entering a function:
14155     * triangle-bugged(5)
14156       eval((triangle-bugged 5) nil)
14157       eval-expression((triangle-bugged 5) nil nil 127)
14158       funcall-interactively(eval-expression (triangle-bugged 5) nil nil 127)
14159       call-interactively(eval-expression nil nil)
14160       command-execute(eval-expression)
14161     ---------- Buffer: *Backtrace* ----------
14162
14163   In the ‘*Backtrace*’ buffer, type ‘d’.  Emacs will evaluate the first
14164expression in ‘triangle-bugged’; the buffer will look like this:
14165
14166     ---------- Buffer: *Backtrace* ----------
14167     Debugger entered--beginning evaluation of function call form:
14168     * (let ((total 0)) (while (> number 0) (setq total ...)
14169             (setq number ...)) total)
14170     * triangle-bugged(5)
14171       eval((triangle-bugged 5))
14172       eval((triangle-bugged 5) nil)
14173       eval-expression((triangle-bugged 5) nil nil 127)
14174       funcall-interactively(eval-expression (triangle-bugged 5) nil nil 127)
14175       call-interactively(eval-expression nil nil)
14176       command-execute(eval-expression)
14177     ---------- Buffer: *Backtrace* ----------
14178
14179Now, type ‘d’ again, eight times, slowly.  Each time you type ‘d’, Emacs
14180will evaluate another expression in the function definition.
14181
14182   Eventually, the buffer will look like this:
14183
14184     ---------- Buffer: *Backtrace* ----------
14185     Debugger entered--beginning evaluation of function call form:
14186     * (setq number (1= number))
14187     * (while (> number 0) (setq total (+ total number))
14188             (setq number (1= number)))
14189     * (let ((total 0)) (while (> number 0) (setq total ...)
14190             (setq number ...)) total)
14191     * triangle-bugged(5)
14192       eval((triangle-bugged 5) nil)
14193       eval-expression((triangle-bugged 5) nil nil 127)
14194       funcall-interactively(eval-expression (triangle-bugged 5) nil nil 127)
14195       call-interactively(eval-expression nil nil)
14196       command-execute(eval-expression)
14197     ---------- Buffer: *Backtrace* ----------
14198
14199Finally, after you type ‘d’ two more times, Emacs will reach the error,
14200and the top two lines of the ‘*Backtrace*’ buffer will look like this:
14201
14202     ---------- Buffer: *Backtrace* ----------
14203     Debugger entered--Lisp error: (void-function 1=)
14204     * (1= number)
14205     ...
14206     ---------- Buffer: *Backtrace* ----------
14207
14208   By typing ‘d’, you were able to step through the function.
14209
14210   You can quit a ‘*Backtrace*’ buffer by typing ‘q’ in it; this quits
14211the trace, but does not cancel ‘debug-on-entry’.
14212
14213   To cancel the effect of ‘debug-on-entry’, call
14214‘cancel-debug-on-entry’ and the name of the function, like this:
14215
14216     M-x cancel-debug-on-entry <RET> triangle-bugged <RET>
14217
14218(If you are reading this in Info, cancel ‘debug-on-entry’ now.)
14219
14220
14221File: eintr.info,  Node: debug-on-quit,  Next: edebug,  Prev: debug-on-entry,  Up: Debugging
14222
1422317.3 ‘debug-on-quit’ and ‘(debug)’
14224==================================
14225
14226In addition to setting ‘debug-on-error’ or calling ‘debug-on-entry’,
14227there are two other ways to start ‘debug’.
14228
14229   You can start ‘debug’ whenever you type ‘C-g’ (‘keyboard-quit’) by
14230setting the variable ‘debug-on-quit’ to ‘t’.  This is useful for
14231debugging infinite loops.
14232
14233   Or, you can insert a line that says ‘(debug)’ into your code where
14234you want the debugger to start, like this:
14235
14236     (defun triangle-bugged (number)
14237       "Return sum of numbers 1 through NUMBER inclusive."
14238       (let ((total 0))
14239         (while (> number 0)
14240           (setq total (+ total number))
14241           (debug)                         ; Start debugger.
14242           (setq number (1= number)))      ; Error here.
14243         total))
14244
14245   The ‘debug’ function is described in detail in *note The Lisp
14246Debugger: (elisp)Debugger.
14247
14248
14249File: eintr.info,  Node: edebug,  Next: Debugging Exercises,  Prev: debug-on-quit,  Up: Debugging
14250
1425117.4 The ‘edebug’ Source Level Debugger
14252=======================================
14253
14254Edebug is a source level debugger.  Edebug normally displays the source
14255of the code you are debugging, with an arrow at the left that shows
14256which line you are currently executing.
14257
14258   You can walk through the execution of a function, line by line, or
14259run quickly until reaching a “breakpoint” where execution stops.
14260
14261   Edebug is described in *note (elisp)Edebug::.
14262
14263   Here is a bugged function definition for ‘triangle-recursively’.
14264*Note Recursion in place of a counter: Recursive triangle function, for
14265a review of it.
14266
14267     (defun triangle-recursively-bugged (number)
14268       "Return sum of numbers 1 through NUMBER inclusive.
14269     Uses recursion."
14270       (if (= number 1)
14271           1
14272         (+ number
14273            (triangle-recursively-bugged
14274             (1= number)))))               ; Error here.
14275
14276Normally, you would install this definition by positioning your cursor
14277after the function’s closing parenthesis and typing ‘C-x C-e’
14278(‘eval-last-sexp’) or else by positioning your cursor within the
14279definition and typing ‘C-M-x’ (‘eval-defun’).  (By default, the
14280‘eval-defun’ command works only in Emacs Lisp mode or in Lisp
14281Interaction mode.)
14282
14283   However, to prepare this function definition for Edebug, you must
14284first “instrument” the code using a different command.  You can do this
14285by positioning your cursor within or just after the definition and
14286typing
14287
14288     M-x edebug-defun <RET>
14289
14290This will cause Emacs to load Edebug automatically if it is not already
14291loaded, and properly instrument the function.
14292
14293   After instrumenting the function, place your cursor after the
14294following expression and type ‘C-x C-e’ (‘eval-last-sexp’):
14295
14296     (triangle-recursively-bugged 3)
14297
14298You will be jumped back to the source for ‘triangle-recursively-bugged’
14299and the cursor positioned at the beginning of the ‘if’ line of the
14300function.  Also, you will see an arrowhead at the left hand side of that
14301line.  The arrowhead marks the line where the function is executing.
14302(In the following examples, we show the arrowhead with ‘=>’; in a
14303windowing system, you may see the arrowhead as a solid triangle in the
14304window fringe.)
14305
14306     =>★(if (= number 1)
14307
14308In the example, the location of point is displayed as ‘★’ (in a printed
14309book, it is displayed with a five pointed star).
14310
14311   If you now press <SPC>, point will move to the next expression to be
14312executed; the line will look like this:
14313
14314     =>(if ★(= number 1)
14315
14316As you continue to press <SPC>, point will move from expression to
14317expression.  At the same time, whenever an expression returns a value,
14318that value will be displayed in the echo area.  For example, after you
14319move point past ‘number’, you will see the following:
14320
14321     Result: 3 (#o3, #x3, ?\C-c)
14322
14323This means the value of ‘number’ is 3, which is octal three, hexadecimal
14324three, and ASCII Control-C (the third letter of the alphabet, in case
14325you need to know this information).
14326
14327   You can continue moving through the code until you reach the line
14328with the error.  Before evaluation, that line looks like this:
14329
14330     =>        ★(1= number)))))               ; Error here.
14331
14332When you press <SPC> once again, you will produce an error message that
14333says:
14334
14335     Symbol's function definition is void: 1=
14336
14337This is the bug.
14338
14339   Press ‘q’ to quit Edebug.
14340
14341   To remove instrumentation from a function definition, simply
14342re-evaluate it with a command that does not instrument it.  For example,
14343you could place your cursor after the definition’s closing parenthesis
14344and type ‘C-x C-e’.
14345
14346   Edebug does a great deal more than walk with you through a function.
14347You can set it so it races through on its own, stopping only at an error
14348or at specified stopping points; you can cause it to display the
14349changing values of various expressions; you can find out how many times
14350a function is called, and more.
14351
14352   Edebug is described in *note (elisp)Edebug::.
14353
14354
14355File: eintr.info,  Node: Debugging Exercises,  Prev: edebug,  Up: Debugging
14356
1435717.5 Debugging Exercises
14358========================
14359
14360   • Install the ‘count-words-example’ function and then cause it to
14361     enter the built-in debugger when you call it.  Run the command on a
14362     region containing two words.  You will need to press ‘d’ a
14363     remarkable number of times.  On your system, is a hook called after
14364     the command finishes?  (For information on hooks, see *note Command
14365     Loop Overview: (elisp)Command Overview.)
14366
14367   • Copy ‘count-words-example’ into the ‘*scratch*’ buffer, instrument
14368     the function for Edebug, and walk through its execution.  The
14369     function does not need to have a bug, although you can introduce
14370     one if you wish.  If the function lacks a bug, the walk-through
14371     completes without problems.
14372
14373   • While running Edebug, type ‘?’ to see a list of all the Edebug
14374     commands.  (The ‘global-edebug-prefix’ is usually ‘C-x X’, i.e.,
14375     ‘<CTRL>-x’ followed by an upper case ‘X’; use this prefix for
14376     commands made outside of the Edebug debugging buffer.)
14377
14378   • In the Edebug debugging buffer, use the ‘p’ (‘edebug-bounce-point’)
14379     command to see where in the region the ‘count-words-example’ is
14380     working.
14381
14382   • Move point to some spot further down the function and then type the
14383     ‘h’ (‘edebug-goto-here’) command to jump to that location.
14384
14385   • Use the ‘t’ (‘edebug-trace-mode’) command to cause Edebug to walk
14386     through the function on its own; use an upper case ‘T’ for
14387     ‘edebug-Trace-fast-mode’.
14388
14389   • Set a breakpoint, then run Edebug in Trace mode until it reaches
14390     the stopping point.
14391
14392
14393File: eintr.info,  Node: Conclusion,  Next: the-the,  Prev: Debugging,  Up: Top
14394
1439518 Conclusion
14396*************
14397
14398We have now reached the end of this Introduction.  You have now learned
14399enough about programming in Emacs Lisp to set values, to write simple
14400‘.emacs’ files for yourself and your friends, and write simple
14401customizations and extensions to Emacs.
14402
14403   This is a place to stop.  Or, if you wish, you can now go onward, and
14404teach yourself.
14405
14406   You have learned some of the basic nuts and bolts of programming.
14407But only some.  There are a great many more brackets and hinges that are
14408easy to use that we have not touched.
14409
14410   A path you can follow right now lies among the sources to GNU Emacs
14411and in *note The GNU Emacs Lisp Reference Manual: (elisp)Top.
14412
14413   The Emacs Lisp sources are an adventure.  When you read the sources
14414and come across a function or expression that is unfamiliar, you need to
14415figure out or find out what it does.
14416
14417   Go to the Reference Manual.  It is a thorough, complete, and fairly
14418easy-to-read description of Emacs Lisp.  It is written not only for
14419experts, but for people who know what you know.  (The ‘Reference Manual’
14420comes with the standard GNU Emacs distribution.  Like this introduction,
14421it comes as a Texinfo source file, so you can read it on your computer
14422and as a typeset, printed book.)
14423
14424   Go to the other built-in help that is part of GNU Emacs: the built-in
14425documentation for all functions and variables, and
14426‘xref-find-definitions’, the program that takes you to sources.
14427
14428   Here is an example of how I explore the sources.  Because of its
14429name, ‘simple.el’ is the file I looked at first, a long time ago.  As it
14430happens some of the functions in ‘simple.el’ are complicated, or at
14431least look complicated at first sight.  The ‘open-line’ function, for
14432example, looks complicated.
14433
14434   You may want to walk through this function slowly, as we did with the
14435‘forward-sentence’ function.  (*Note The ‘forward-sentence’ function:
14436forward-sentence.)  Or you may want to skip that function and look at
14437another, such as ‘split-line’.  You don’t need to read all the
14438functions.  According to ‘count-words-in-defun’, the ‘split-line’
14439function contains 102 words and symbols.
14440
14441   Even though it is short, ‘split-line’ contains expressions we have
14442not studied: ‘skip-chars-forward’, ‘indent-to’, ‘current-column’ and
14443‘insert-and-inherit’.
14444
14445   Consider the ‘skip-chars-forward’ function.  In GNU Emacs, you can
14446find out more about ‘skip-chars-forward’ by typing ‘C-h f’
14447(‘describe-function’) and the name of the function.  This gives you the
14448function documentation.
14449
14450   You may be able to guess what is done by a well named function such
14451as ‘indent-to’; or you can look it up, too.  Incidentally, the
14452‘describe-function’ function itself is in ‘help.el’; it is one of those
14453long, but decipherable functions.  You can look up ‘describe-function’
14454using the ‘C-h f’ command!
14455
14456   In this instance, since the code is Lisp, the ‘*Help*’ buffer
14457contains the name of the library containing the function’s source.  You
14458can put point over the name of the library and press the <RET> key,
14459which in this situation is bound to ‘help-follow’, and be taken directly
14460to the source, in the same way as ‘M-.’ (‘xref-find-definitions’).
14461
14462   The definition for ‘describe-function’ illustrates how to customize
14463the ‘interactive’ expression without using the standard character codes;
14464and it shows how to create a temporary buffer.
14465
14466   (The ‘indent-to’ function is written in C rather than Emacs Lisp; it
14467is a built-in function.  ‘help-follow’ takes you to its source as does
14468‘xref-find-definitions’, when properly set up.)
14469
14470   You can look at a function’s source using ‘xref-find-definitions’,
14471which is bound to ‘M-.’ Finally, you can find out what the Reference
14472Manual has to say by visiting the manual in Info, and typing ‘i’
14473(‘Info-index’) and the name of the function, or by looking up the
14474function in the index to a printed copy of the manual.
14475
14476   Similarly, you can find out what is meant by ‘insert-and-inherit’.
14477
14478   Other interesting source files include ‘paragraphs.el’,
14479loaddefs.el’, and ‘loadup.el’.  The ‘paragraphs.el’ file includes
14480short, easily understood functions as well as longer ones.  The
14481loaddefs.el’ file contains the many standard autoloads and many
14482keymaps.  I have never looked at it all; only at parts.  ‘loadup.el’ is
14483the file that loads the standard parts of Emacs; it tells you a great
14484deal about how Emacs is built.  (*Note Building Emacs: (elisp)Building
14485Emacs, for more about building.)
14486
14487   As I said, you have learned some nuts and bolts; however, and very
14488importantly, we have hardly touched major aspects of programming; I have
14489said nothing about how to sort information, except to use the predefined
14490‘sort’ function; I have said nothing about how to store information,
14491except to use variables and lists; I have said nothing about how to
14492write programs that write programs.  These are topics for another, and
14493different kind of book, a different kind of learning.
14494
14495   What you have done is learn enough for much practical work with GNU
14496Emacs.  What you have done is get started.  This is the end of a
14497beginning.
14498
14499
14500File: eintr.info,  Node: the-the,  Next: Kill Ring,  Prev: Conclusion,  Up: Top
14501
14502Appendix A The ‘the-the’ Function
14503*********************************
14504
14505Sometimes when you you write text, you duplicate words—as with “you you”
14506near the beginning of this sentence.  I find that most frequently, I
14507duplicate “the”; hence, I call the function for detecting duplicated
14508words, ‘the-the’.
14509
14510   As a first step, you could use the following regular expression to
14511search for duplicates:
14512
14513     \\(\\w+[ \t\n]+\\)\\1
14514
14515This regexp matches one or more word-constituent characters followed by
14516one or more spaces, tabs, or newlines.  However, it does not detect
14517duplicated words on different lines, since the ending of the first word,
14518the end of the line, is different from the ending of the second word, a
14519space.  (For more information about regular expressions, see *note
14520Regular Expression Searches: Regexp Search, as well as *note Syntax of
14521Regular Expressions: (emacs)Regexps, and *note Regular Expressions:
14522(elisp)Regular Expressions.)
14523
14524   You might try searching just for duplicated word-constituent
14525characters but that does not work since the pattern detects doubles such
14526as the two occurrences of “th” in “with the”.
14527
14528   Another possible regexp searches for word-constituent characters
14529followed by non-word-constituent characters, reduplicated.  Here, ‘\\w+’
14530matches one or more word-constituent characters and ‘\\W*’ matches zero
14531or more non-word-constituent characters.
14532
14533     \\(\\(\\w+\\)\\W*\\)\\1
14534
14535Again, not useful.
14536
14537   Here is the pattern that I use.  It is not perfect, but good enough.
14538‘\\b’ matches the empty string, provided it is at the beginning or end
14539of a word; ‘[^@ \n\t]+’ matches one or more occurrences of any
14540characters that are _not_ an @-sign, space, newline, or tab.
14541
14542     \\b\\([^@ \n\t]+\\)[ \n\t]+\\1\\b
14543
14544   One can write more complicated expressions, but I found that this
14545expression is good enough, so I use it.
14546
14547   Here is the ‘the-the’ function, as I include it in my ‘.emacs’ file,
14548along with a handy global key binding:
14549
14550     (defun the-the ()
14551       "Search forward for for a duplicated word."
14552       (interactive)
14553       (message "Searching for for duplicated words ...")
14554       (push-mark)
14555       ;; This regexp is not perfect
14556       ;; but is fairly good over all:
14557       (if (re-search-forward
14558            "\\b\\([^@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
14559           (message "Found duplicated word.")
14560         (message "End of buffer")))
14561
14562     ;; Bind 'the-the' to  C-c \
14563     (global-set-key "\C-c\\" 'the-the)
14564
14565
14566   Here is test text:
14567
14568     one two two three four five
14569     five six seven
14570
14571   You can substitute the other regular expressions shown above in the
14572function definition and try each of them on this list.
14573
14574
14575File: eintr.info,  Node: Kill Ring,  Next: Full Graph,  Prev: the-the,  Up: Top
14576
14577Appendix B Handling the Kill Ring
14578*********************************
14579
14580The kill ring is a list that is transformed into a ring by the workings
14581of the ‘current-kill’ function.  The ‘yank’ and ‘yank-pop’ commands use
14582the ‘current-kill’ function.
14583
14584   This appendix describes the ‘current-kill’ function as well as both
14585the ‘yank’ and the ‘yank-pop’ commands, but first, consider the workings
14586of the kill ring.
14587
14588* Menu:
14589
14590* What the Kill Ring Does::
14591* current-kill::
14592* yank::                        Paste a copy of a clipped element.
14593* yank-pop::                    Insert element pointed to.
14594* ring file::
14595
14596
14597File: eintr.info,  Node: What the Kill Ring Does,  Next: current-kill,  Up: Kill Ring
14598
14599What the Kill Ring Does
14600=======================
14601
14602The kill ring has a default maximum length of sixty items; this number
14603is too large for an explanation.  Instead, set it to four.  Please
14604evaluate the following:
14605
14606     (setq old-kill-ring-max kill-ring-max)
14607     (setq kill-ring-max 4)
14608
14609Then, please copy each line of the following indented example into the
14610kill ring.  You may kill each line with ‘C-k’ or mark it and copy it
14611with ‘M-w’.
14612
14613(In a read-only buffer, such as the ‘*info*’ buffer, the kill command,
14614‘C-k’ (‘kill-line’), will not remove the text, merely copy it to the
14615kill ring.  However, your machine may beep at you.  Alternatively, for
14616silence, you may copy the region of each line with the ‘M-w’
14617(‘kill-ring-save’) command.  You must mark each line for this command to
14618succeed, but it does not matter at which end you put point or mark.)
14619
14620Please invoke the calls in order, so that five elements attempt to fill
14621the kill ring:
14622
14623     first some text
14624     second piece of text
14625     third line
14626     fourth line of text
14627     fifth bit of text
14628
14629Then find the value of ‘kill-ring’ by evaluating
14630
14631     kill-ring
14632
14633It is:
14634
14635     ("fifth bit of text" "fourth line of text"
14636     "third line" "second piece of text")
14637
14638The first element, ‘first some text’, was dropped.
14639
14640   To return to the old value for the length of the kill ring, evaluate:
14641
14642     (setq kill-ring-max old-kill-ring-max)
14643
14644
14645File: eintr.info,  Node: current-kill,  Next: yank,  Prev: What the Kill Ring Does,  Up: Kill Ring
14646
14647B.1 The ‘current-kill’ Function
14648===============================
14649
14650The ‘current-kill’ function changes the element in the kill ring to
14651which ‘kill-ring-yank-pointer’ points.  (Also, the ‘kill-new’ function
14652sets ‘kill-ring-yank-pointer’ to point to the latest element of the kill
14653ring.  The ‘kill-new’ function is used directly or indirectly by
14654‘kill-append’, ‘copy-region-as-kill’, ‘kill-ring-save’, ‘kill-line’, and
14655‘kill-region’.)
14656
14657* Menu:
14658
14659* Code for current-kill::
14660* Understanding current-kill::
14661
14662
14663File: eintr.info,  Node: Code for current-kill,  Next: Understanding current-kill,  Up: current-kill
14664
14665The code for ‘current-kill’
14666---------------------------
14667
14668The ‘current-kill’ function is used by ‘yank’ and by ‘yank-pop’.  Here
14669is the code for ‘current-kill’:
14670
14671     (defun current-kill (n &optional do-not-move)
14672       "Rotate the yanking point by N places, and then return that kill.
14673     If N is zero and `interprogram-paste-function' is set to a
14674     function that returns a string or a list of strings, and if that
14675     function doesn't return nil, then that string (or list) is added
14676     to the front of the kill ring and the string (or first string in
14677     the list) is returned as the latest kill.
14678     If N is not zero, and if `yank-pop-change-selection' is
14679     non-nil, use `interprogram-cut-function' to transfer the
14680     kill at the new yank point into the window system selection.
14681     If optional arg DO-NOT-MOVE is non-nil, then don't actually
14682     move the yanking point; just return the Nth kill forward."
14683
14684       (let ((interprogram-paste (and (= n 0)
14685                                      interprogram-paste-function
14686                                      (funcall interprogram-paste-function))))
14687         (if interprogram-paste
14688             (progn
14689               ;; Disable the interprogram cut function when we add the new
14690               ;; text to the kill ring, so Emacs doesn't try to own the
14691               ;; selection, with identical text.
14692               (let ((interprogram-cut-function nil))
14693                 (if (listp interprogram-paste)
14694                   (mapc 'kill-new (nreverse interprogram-paste))
14695                   (kill-new interprogram-paste)))
14696               (car kill-ring))
14697           (or kill-ring (error "Kill ring is empty"))
14698           (let ((ARGth-kill-element
14699                  (nthcdr (mod (- n (length kill-ring-yank-pointer))
14700                               (length kill-ring))
14701                          kill-ring)))
14702             (unless do-not-move
14703               (setq kill-ring-yank-pointer ARGth-kill-element)
14704               (when (and yank-pop-change-selection
14705                          (> n 0)
14706                          interprogram-cut-function)
14707                 (funcall interprogram-cut-function (car ARGth-kill-element))))
14708             (car ARGth-kill-element)))))
14709
14710   Remember also that the ‘kill-new’ function sets
14711‘kill-ring-yank-pointer’ to the latest element of the kill ring, which
14712means that all the functions that call it set the value indirectly:
14713‘kill-append’, ‘copy-region-as-kill’, ‘kill-ring-save’, ‘kill-line’, and
14714‘kill-region’.
14715
14716   Here is the line in ‘kill-new’, which is explained in *note The
14717‘kill-new’ function: kill-new function.
14718
14719     (setq kill-ring-yank-pointer kill-ring)
14720
14721
14722File: eintr.info,  Node: Understanding current-kill,  Prev: Code for current-kill,  Up: current-kill
14723
14724‘current-kill’ in Outline
14725-------------------------
14726
14727The ‘current-kill’ function looks complex, but as usual, it can be
14728understood by taking it apart piece by piece.  First look at it in
14729skeletal form:
14730
14731     (defun current-kill (n &optional do-not-move)
14732       "Rotate the yanking point by N places, and then return that kill."
14733       (let VARLIST
14734         BODY...)
14735
14736   This function takes two arguments, one of which is optional.  It has
14737a documentation string.  It is _not_ interactive.
14738
14739* Menu:
14740
14741* Body of current-kill::
14742* Digression concerning error::  How to mislead humans, but not computers.
14743* Determining the Element::
14744
14745
14746File: eintr.info,  Node: Body of current-kill,  Next: Digression concerning error,  Up: Understanding current-kill
14747
14748The Body of ‘current-kill’
14749..........................
14750
14751The body of the function definition is a ‘let’ expression, which itself
14752has a body as well as a VARLIST.
14753
14754   The ‘let’ expression declares a variable that will be only usable
14755within the bounds of this function.  This variable is called
14756‘interprogram-paste’ and is for copying to another program.  It is not
14757for copying within this instance of GNU Emacs.  Most window systems
14758provide a facility for interprogram pasting.  Sadly, that facility
14759usually provides only for the last element.  Most windowing systems have
14760not adopted a ring of many possibilities, even though Emacs has provided
14761it for decades.
14762
14763   The ‘if’ expression has two parts, one if there exists
14764‘interprogram-paste’ and one if not.
14765
14766   Let us consider the else-part of the ‘current-kill’ function.  (The
14767then-part uses the ‘kill-new’ function, which we have already described.
14768*Note The ‘kill-new’ function: kill-new function.)
14769
14770     (or kill-ring (error "Kill ring is empty"))
14771     (let ((ARGth-kill-element
14772            (nthcdr (mod (- n (length kill-ring-yank-pointer))
14773                         (length kill-ring))
14774                    kill-ring)))
14775       (or do-not-move
14776           (setq kill-ring-yank-pointer ARGth-kill-element))
14777       (car ARGth-kill-element))
14778
14779The code first checks whether the kill ring has content; otherwise it
14780signals an error.
14781
14782   Note that the ‘or’ expression is very similar to testing length with
14783an ‘if’:
14784
14785     (if (zerop (length kill-ring))          ; if-part
14786         (error "Kill ring is empty"))       ; then-part
14787       ;; No else-part
14788
14789If there is not anything in the kill ring, its length must be zero and
14790an error message sent to the user: ‘Kill ring is empty’.  The
14791‘current-kill’ function uses an ‘or’ expression which is simpler.  But
14792an ‘if’ expression reminds us what goes on.
14793
14794   This ‘if’ expression uses the function ‘zerop’ which returns true if
14795the value it is testing is zero.  When ‘zerop’ tests true, the then-part
14796of the ‘if’ is evaluated.  The then-part is a list starting with the
14797function ‘error’, which is a function that is similar to the ‘message’
14798function (*note The ‘message’ Function: message.) in that it prints a
14799one-line message in the echo area.  However, in addition to printing a
14800message, ‘error’ also stops evaluation of the function within which it
14801is embedded.  This means that the rest of the function will not be
14802evaluated if the length of the kill ring is zero.
14803
14804   Then the ‘current-kill’ function selects the element to return.  The
14805selection depends on the number of places that ‘current-kill’ rotates
14806and on where ‘kill-ring-yank-pointer’ points.
14807
14808   Next, either the optional ‘do-not-move’ argument is true or the
14809current value of ‘kill-ring-yank-pointer’ is set to point to the list.
14810Finally, another expression returns the first element of the list even
14811if the ‘do-not-move’ argument is true.
14812
14813
14814File: eintr.info,  Node: Digression concerning error,  Next: Determining the Element,  Prev: Body of current-kill,  Up: Understanding current-kill
14815
14816Digression about the word “error”
14817.................................
14818
14819In my opinion, it is slightly misleading, at least to humans, to use the
14820term “error” as the name of the ‘error’ function.  A better term would
14821be “cancel”.  Strictly speaking, of course, you cannot point to, much
14822less rotate a pointer to a list that has no length, so from the point of
14823view of the computer, the word “error” is correct.  But a human expects
14824to attempt this sort of thing, if only to find out whether the kill ring
14825is full or empty.  This is an act of exploration.
14826
14827   From the human point of view, the act of exploration and discovery is
14828not necessarily an error, and therefore should not be labeled as one,
14829even in the bowels of a computer.  As it is, the code in Emacs implies
14830that a human who is acting virtuously, by exploring his or her
14831environment, is making an error.  This is bad.  Even though the computer
14832takes the same steps as it does when there is an error, a term such as
14833“cancel” would have a clearer connotation.
14834
14835
14836File: eintr.info,  Node: Determining the Element,  Prev: Digression concerning error,  Up: Understanding current-kill
14837
14838Determining the Element
14839.......................
14840
14841Among other actions, the else-part of the ‘if’ expression sets the value
14842of ‘kill-ring-yank-pointer’ to ‘ARGth-kill-element’ when the kill ring
14843has something in it and the value of ‘do-not-move’ is ‘nil’.
14844
14845   The code looks like this:
14846
14847     (nthcdr (mod (- n (length kill-ring-yank-pointer))
14848                  (length kill-ring))
14849             kill-ring)))
14850
14851   This needs some examination.  Unless it is not supposed to move the
14852pointer, the ‘current-kill’ function changes where
14853‘kill-ring-yank-pointer’ points.  That is what the
14854‘(setq kill-ring-yank-pointer ARGth-kill-element))’ expression does.
14855Also, clearly, ‘ARGth-kill-element’ is being set to be equal to some CDR
14856of the kill ring, using the ‘nthcdr’ function that is described in an
14857earlier section.  (*Note copy-region-as-kill::.)  How does it do this?
14858
14859   As we have seen before (*note nthcdr::), the ‘nthcdr’ function works
14860by repeatedly taking the CDR of a list—it takes the CDR of the CDR of
14861the CDR ...
14862
14863   The two following expressions produce the same result:
14864
14865     (setq kill-ring-yank-pointer (cdr kill-ring))
14866
14867     (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
14868
14869   However, the ‘nthcdr’ expression is more complicated.  It uses the
14870‘mod’ function to determine which CDR to select.
14871
14872   (You will remember to look at inner functions first; indeed, we will
14873have to go inside the ‘mod’.)
14874
14875   The ‘mod’ function returns the value of its first argument modulo the
14876second; that is to say, it returns the remainder after dividing the
14877first argument by the second.  The value returned has the same sign as
14878the second argument.
14879
14880   Thus,
14881
14882     (mod 12 4)
14883       ⇒ 0  ;; because there is no remainder
14884     (mod 13 4)
14885       ⇒ 1
14886
14887   In this case, the first argument is often smaller than the second.
14888That is fine.
14889
14890     (mod 0 4)
14891       ⇒ 0
14892     (mod 1 4)
14893       ⇒ 1
14894
14895   We can guess what the ‘-’ function does.  It is like ‘+’ but
14896subtracts instead of adds; the ‘-’ function subtracts its second
14897argument from its first.  Also, we already know what the ‘length’
14898function does (*note length::).  It returns the length of a list.
14899
14900   And ‘n’ is the name of the required argument to the ‘current-kill’
14901function.
14902
14903   So when the first argument to ‘nthcdr’ is zero, the ‘nthcdr’
14904expression returns the whole list, as you can see by evaluating the
14905following:
14906
14907     ;; kill-ring-yank-pointer and kill-ring have a length of four
14908     ;; and (mod (- 0 4) 4) ⇒ 0
14909     (nthcdr (mod (- 0 4) 4)
14910             '("fourth line of text"
14911               "third line"
14912               "second piece of text"
14913               "first some text"))
14914
14915   When the first argument to the ‘current-kill’ function is one, the
14916‘nthcdr’ expression returns the list without its first element.
14917
14918     (nthcdr (mod (- 1 4) 4)
14919             '("fourth line of text"
14920               "third line"
14921               "second piece of text"
14922               "first some text"))
14923
14924   Incidentally, both ‘kill-ring’ and ‘kill-ring-yank-pointer’ are
14925“global variables”.  That means that any expression in Emacs Lisp can
14926access them.  They are not like the local variables set by ‘let’ or like
14927the symbols in an argument list.  Local variables can only be accessed
14928within the ‘let’ that defines them or the function that specifies them
14929in an argument list (and within expressions called by them).
14930
14931   (*Note ‘let’ Prevents Confusion: Prevent confusion, and *note The
14932‘defun’ Macro: defun.)
14933
14934
14935File: eintr.info,  Node: yank,  Next: yank-pop,  Prev: current-kill,  Up: Kill Ring
14936
14937B.2 ‘yank’
14938==========
14939
14940After learning about ‘current-kill’, the code for the ‘yank’ function is
14941almost easy.
14942
14943   The ‘yank’ function does not use the ‘kill-ring-yank-pointer’
14944variable directly.  It calls ‘insert-for-yank’ which calls
14945‘current-kill’ which sets the ‘kill-ring-yank-pointer’ variable.
14946
14947   The code looks like this:
14948
14949     (defun yank (&optional arg)
14950       "Reinsert (\"paste\") the last stretch of killed text.
14951     More precisely, reinsert the stretch of killed text most recently
14952     killed OR yanked.  Put point at end, and set mark at beginning.
14953     With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
14954     With argument N, reinsert the Nth most recently killed stretch of killed
14955     text.
14956
14957     When this command inserts killed text into the buffer, it honors
14958     `yank-excluded-properties' and `yank-handler' as described in the
14959     doc string for `insert-for-yank-1', which see.
14960
14961     See also the command `yank-pop' (\\[yank-pop])."
14962       (interactive "*P")
14963       (setq yank-window-start (window-start))
14964       ;; If we don't get all the way thru, make last-command indicate that
14965       ;; for the following command.
14966       (setq this-command t)
14967       (push-mark (point))
14968       (insert-for-yank (current-kill (cond
14969                                       ((listp arg) 0)
14970                                       ((eq arg '-) -2)
14971                                       (t (1- arg)))))
14972       (if (consp arg)
14973           ;; This is like exchange-point-and-mark, but doesn't activate the mark.
14974           ;; It is cleaner to avoid activation, even though the command
14975           ;; loop would deactivate the mark because we inserted text.
14976           (goto-char (prog1 (mark t)
14977                        (set-marker (mark-marker) (point) (current-buffer)))))
14978       ;; If we do get all the way thru, make this-command indicate that.
14979       (if (eq this-command t)
14980           (setq this-command 'yank))
14981       nil)
14982
14983   The key expression is ‘insert-for-yank’, which inserts the string
14984returned by ‘current-kill’, but removes some text properties from it.
14985
14986   However, before getting to that expression, the function sets the
14987value of ‘yank-window-start’ to the position returned by the
14988‘(window-start)’ expression, the position at which the display currently
14989starts.  The ‘yank’ function also sets ‘this-command’ and pushes the
14990mark.
14991
14992   After it yanks the appropriate element, if the optional argument is a
14993CONS rather than a number or nothing, it puts point at beginning of the
14994yanked text and mark at its end.
14995
14996   (The ‘prog1’ function is like ‘progn’ but returns the value of its
14997first argument rather than the value of its last argument.  Its first
14998argument is forced to return the buffer’s mark as an integer.  You can
14999see the documentation for these functions by placing point over them in
15000this buffer and then typing ‘C-h f’ (‘describe-function’) followed by a
15001‘RET’; the default is the function.)
15002
15003   The last part of the function tells what to do when it succeeds.
15004
15005
15006File: eintr.info,  Node: yank-pop,  Next: ring file,  Prev: yank,  Up: Kill Ring
15007
15008B.3 ‘yank-pop’
15009==============
15010
15011After understanding ‘yank’ and ‘current-kill’, you know how to approach
15012the ‘yank-pop’ function.  Leaving out the documentation to save space,
15013it looks like this:
15014
15015     (defun yank-pop (&optional arg)
15016       "..."
15017       (interactive "*p")
15018       (if (not (eq last-command 'yank))
15019           (error "Previous command was not a yank"))
15020       (setq this-command 'yank)
15021       (unless arg (setq arg 1))
15022       (let ((inhibit-read-only t)
15023             (before (< (point) (mark t))))
15024         (if before
15025             (funcall (or yank-undo-function 'delete-region) (point) (mark t))
15026           (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
15027         (setq yank-undo-function nil)
15028         (set-marker (mark-marker) (point) (current-buffer))
15029         (insert-for-yank (current-kill arg))
15030         ;; Set the window start back where it was in the yank command,
15031         ;; if possible.
15032         (set-window-start (selected-window) yank-window-start t)
15033         (if before
15034             ;; This is like exchange-point-and-mark,
15035             ;;     but doesn't activate the mark.
15036             ;; It is cleaner to avoid activation, even though the command
15037             ;; loop would deactivate the mark because we inserted text.
15038             (goto-char (prog1 (mark t)
15039                          (set-marker (mark-marker)
15040                                      (point)
15041                                      (current-buffer))))))
15042       nil)
15043
15044   The function is interactive with a small ‘p’ so the prefix argument
15045is processed and passed to the function.  The command can only be used
15046after a previous yank; otherwise an error message is sent.  This check
15047uses the variable ‘last-command’ which is set by ‘yank’ and is discussed
15048elsewhere.  (*Note copy-region-as-kill::.)
15049
15050   The ‘let’ clause sets the variable ‘before’ to true or false
15051depending whether point is before or after mark and then the region
15052between point and mark is deleted.  This is the region that was just
15053inserted by the previous yank and it is this text that will be replaced.
15054
15055   ‘funcall’ calls its first argument as a function, passing remaining
15056arguments to it.  The first argument is whatever the ‘or’ expression
15057returns.  The two remaining arguments are the positions of point and
15058mark set by the preceding ‘yank’ command.
15059
15060   There is more, but that is the hardest part.
15061
15062
15063File: eintr.info,  Node: ring file,  Prev: yank-pop,  Up: Kill Ring
15064
15065B.4 The ‘ring.el’ File
15066======================
15067
15068Interestingly, GNU Emacs posses a file called ‘ring.el’ that provides
15069many of the features we just discussed.  But functions such as
15070‘kill-ring-yank-pointer’ do not use this library, possibly because they
15071were written earlier.
15072
15073
15074File: eintr.info,  Node: Full Graph,  Next: Free Software and Free Manuals,  Prev: Kill Ring,  Up: Top
15075
15076Appendix C A Graph with Labeled Axes
15077************************************
15078
15079Printed axes help you understand a graph.  They convey scale.  In an
15080earlier chapter (*note Readying a Graph: Readying a Graph.), we wrote
15081the code to print the body of a graph.  Here we write the code for
15082printing and labeling vertical and horizontal axes, along with the body
15083itself.
15084
15085* Menu:
15086
15087* Labeled Example::
15088* print-graph Varlist::         ‘let’ expression in ‘print-graph’.
15089* print-Y-axis::                Print a label for the vertical axis.
15090* print-X-axis::                Print a horizontal label.
15091* Print Whole Graph::           The function to print a complete graph.
15092
15093
15094File: eintr.info,  Node: Labeled Example,  Next: print-graph Varlist,  Up: Full Graph
15095
15096Labeled Example Graph
15097=====================
15098
15099Since insertions fill a buffer to the right and below point, the new
15100graph printing function should first print the Y or vertical axis, then
15101the body of the graph, and finally the X or horizontal axis.  This
15102sequence lays out for us the contents of the function:
15103
15104  1. Set up code.
15105
15106  2. Print Y axis.
15107
15108  3. Print body of graph.
15109
15110  4. Print X axis.
15111
15112   Here is an example of how a finished graph should look:
15113
15114         10 -
15115                       *
15116                       *  *
15117                       *  **
15118                       *  ***
15119          5 -      *   *******
15120                 * *** *******
15121                 *************
15122               ***************
15123          1 - ****************
15124              |   |    |    |
15125              1   5   10   15
15126
15127In this graph, both the vertical and the horizontal axes are labeled
15128with numbers.  However, in some graphs, the horizontal axis is time and
15129would be better labeled with months, like this:
15130
15131          5 -      *
15132                 * ** *
15133                 *******
15134               ********** **
15135          1 - **************
15136              |    ^      |
15137              Jan  June   Jan
15138
15139   Indeed, with a little thought, we can easily come up with a variety
15140of vertical and horizontal labeling schemes.  Our task could become
15141complicated.  But complications breed confusion.  Rather than permit
15142this, it is better choose a simple labeling scheme for our first effort,
15143and to modify or replace it later.
15144
15145   These considerations suggest the following outline for the
15146‘print-graph’ function:
15147
15148     (defun print-graph (numbers-list)
15149       "DOCUMENTATION..."
15150       (let ((height  ...
15151             ...))
15152         (print-Y-axis height ... )
15153         (graph-body-print numbers-list)
15154         (print-X-axis ... )))
15155
15156   We can work on each part of the ‘print-graph’ function definition in
15157turn.
15158
15159
15160File: eintr.info,  Node: print-graph Varlist,  Next: print-Y-axis,  Prev: Labeled Example,  Up: Full Graph
15161
15162C.1 The ‘print-graph’ Varlist
15163=============================
15164
15165In writing the ‘print-graph’ function, the first task is to write the
15166varlist in the ‘let’ expression.  (We will leave aside for the moment
15167any thoughts about making the function interactive or about the contents
15168of its documentation string.)
15169
15170   The varlist should set several values.  Clearly, the top of the label
15171for the vertical axis must be at least the height of the graph, which
15172means that we must obtain this information here.  Note that the
15173‘print-graph-body’ function also requires this information.  There is no
15174reason to calculate the height of the graph in two different places, so
15175we should change ‘print-graph-body’ from the way we defined it earlier
15176to take advantage of the calculation.
15177
15178   Similarly, both the function for printing the X axis labels and the
15179‘print-graph-body’ function need to learn the value of the width of each
15180symbol.  We can perform the calculation here and change the definition
15181for ‘print-graph-body’ from the way we defined it in the previous
15182chapter.
15183
15184   The length of the label for the horizontal axis must be at least as
15185long as the graph.  However, this information is used only in the
15186function that prints the horizontal axis, so it does not need to be
15187calculated here.
15188
15189   These thoughts lead us directly to the following form for the varlist
15190in the ‘let’ for ‘print-graph’:
15191
15192     (let ((height (apply 'max numbers-list)) ; First version.
15193           (symbol-width (length graph-blank)))
15194
15195As we shall see, this expression is not quite right.
15196
15197
15198File: eintr.info,  Node: print-Y-axis,  Next: print-X-axis,  Prev: print-graph Varlist,  Up: Full Graph
15199
15200C.2 The ‘print-Y-axis’ Function
15201===============================
15202
15203The job of the ‘print-Y-axis’ function is to print a label for the
15204vertical axis that looks like this:
15205
15206         10 -
15207
15208
15209
15210
15211          5 -
15212
15213
15214
15215          1 -
15216
15217The function should be passed the height of the graph, and then should
15218construct and insert the appropriate numbers and marks.
15219
15220* Menu:
15221
15222* print-Y-axis in Detail::
15223* Height of label::             What height for the Y axis?
15224* Compute a Remainder::         How to compute the remainder of a division.
15225* Y Axis Element::              Construct a line for the Y axis.
15226* Y-axis-column::               Generate a list of Y axis labels.
15227* print-Y-axis Penultimate::    A not quite final version.
15228
15229
15230File: eintr.info,  Node: print-Y-axis in Detail,  Next: Height of label,  Up: print-Y-axis
15231
15232The ‘print-Y-axis’ Function in Detail
15233-------------------------------------
15234
15235It is easy enough to see in the figure what the Y axis label should look
15236like; but to say in words, and then to write a function definition to do
15237the job is another matter.  It is not quite true to say that we want a
15238number and a tic every five lines: there are only three lines between
15239the ‘1’ and the ‘5’ (lines 2, 3, and 4), but four lines between the ‘5’
15240and the ‘10’ (lines 6, 7, 8, and 9).  It is better to say that we want a
15241number and a tic mark on the base line (number 1) and then that we want
15242a number and a tic on the fifth line from the bottom and on every line
15243that is a multiple of five.
15244
15245
15246File: eintr.info,  Node: Height of label,  Next: Compute a Remainder,  Prev: print-Y-axis in Detail,  Up: print-Y-axis
15247
15248What height should the label be?
15249--------------------------------
15250
15251The next issue is what height the label should be?  Suppose the maximum
15252height of tallest column of the graph is seven.  Should the highest
15253label on the Y axis be ‘5 -’, and should the graph stick up above the
15254label?  Or should the highest label be ‘7 -’, and mark the peak of the
15255graph?  Or should the highest label be ‘10 -’, which is a multiple of
15256five, and be higher than the topmost value of the graph?
15257
15258   The latter form is preferred.  Most graphs are drawn within
15259rectangles whose sides are an integral number of steps long—5, 10, 15,
15260and so on for a step distance of five.  But as soon as we decide to use
15261a step height for the vertical axis, we discover that the simple
15262expression in the varlist for computing the height is wrong.  The
15263expression is ‘(apply 'max numbers-list)’.  This returns the precise
15264height, not the maximum height plus whatever is necessary to round up to
15265the nearest multiple of five.  A more complex expression is required.
15266
15267   As usual in cases like this, a complex problem becomes simpler if it
15268is divided into several smaller problems.
15269
15270   First, consider the case when the highest value of the graph is an
15271integral multiple of five—when it is 5, 10, 15, or some higher multiple
15272of five.  We can use this value as the Y axis height.
15273
15274   A fairly simply way to determine whether a number is a multiple of
15275five is to divide it by five and see if the division results in a
15276remainder.  If there is no remainder, the number is a multiple of five.
15277Thus, seven divided by five has a remainder of two, and seven is not an
15278integral multiple of five.  Put in slightly different language, more
15279reminiscent of the classroom, five goes into seven once, with a
15280remainder of two.  However, five goes into ten twice, with no remainder:
15281ten is an integral multiple of five.
15282
15283
15284File: eintr.info,  Node: Compute a Remainder,  Next: Y Axis Element,  Prev: Height of label,  Up: print-Y-axis
15285
15286C.2.1 Side Trip: Compute a Remainder
15287------------------------------------
15288
15289In Lisp, the function for computing a remainder is ‘%’.  The function
15290returns the remainder of its first argument divided by its second
15291argument.  As it happens, ‘%’ is a function in Emacs Lisp that you
15292cannot discover using ‘apropos’: you find nothing if you type ‘M-x
15293apropos <RET> remainder <RET>’.  The only way to learn of the existence
15294of ‘%’ is to read about it in a book such as this or in the Emacs Lisp
15295sources.
15296
15297   You can try the ‘%’ function by evaluating the following two
15298expressions:
15299
15300     (% 7 5)
15301
15302     (% 10 5)
15303
15304The first expression returns 2 and the second expression returns 0.
15305
15306   To test whether the returned value is zero or some other number, we
15307can use the ‘zerop’ function.  This function returns ‘t’ if its
15308argument, which must be a number, is zero.
15309
15310     (zerop (% 7 5))
15311          ⇒ nil
15312
15313     (zerop (% 10 5))
15314          ⇒ t
15315
15316   Thus, the following expression will return ‘t’ if the height of the
15317graph is evenly divisible by five:
15318
15319     (zerop (% height 5))
15320
15321(The value of ‘height’, of course, can be found from ‘(apply 'max
15322numbers-list)’.)
15323
15324   On the other hand, if the value of ‘height’ is not a multiple of
15325five, we want to reset the value to the next higher multiple of five.
15326This is straightforward arithmetic using functions with which we are
15327already familiar.  First, we divide the value of ‘height’ by five to
15328determine how many times five goes into the number.  Thus, five goes
15329into twelve twice.  If we add one to this quotient and multiply by five,
15330we will obtain the value of the next multiple of five that is larger
15331than the height.  Five goes into twelve twice.  Add one to two, and
15332multiply by five; the result is fifteen, which is the next multiple of
15333five that is higher than twelve.  The Lisp expression for this is:
15334
15335     (* (1+ (/ height 5)) 5)
15336
15337For example, if you evaluate the following, the result is 15:
15338
15339     (* (1+ (/ 12 5)) 5)
15340
15341   All through this discussion, we have been using 5 as the value for
15342spacing labels on the Y axis; but we may want to use some other value.
15343For generality, we should replace 5 with a variable to which we can
15344assign a value.  The best name I can think of for this variable is
15345‘Y-axis-label-spacing’.
15346
15347   Using this term, and an ‘if’ expression, we produce the following:
15348
15349     (if (zerop (% height Y-axis-label-spacing))
15350         height
15351       ;; else
15352       (* (1+ (/ height Y-axis-label-spacing))
15353          Y-axis-label-spacing))
15354
15355This expression returns the value of ‘height’ itself if the height is an
15356even multiple of the value of the ‘Y-axis-label-spacing’ or else it
15357computes and returns a value of ‘height’ that is equal to the next
15358higher multiple of the value of the ‘Y-axis-label-spacing’.
15359
15360   We can now include this expression in the ‘let’ expression of the
15361‘print-graph’ function (after first setting the value of
15362‘Y-axis-label-spacing’):
15363
15364     (defvar Y-axis-label-spacing 5
15365       "Number of lines from one Y axis label to next.")
15366
15367     ...
15368     (let* ((height (apply 'max numbers-list))
15369            (height-of-top-line
15370             (if (zerop (% height Y-axis-label-spacing))
15371                 height
15372               ;; else
15373               (* (1+ (/ height Y-axis-label-spacing))
15374                  Y-axis-label-spacing)))
15375            (symbol-width (length graph-blank))))
15376     ...
15377
15378(Note use of the ‘let*’ function: the initial value of height is
15379computed once by the ‘(apply 'max numbers-list)’ expression and then the
15380resulting value of ‘height’ is used to compute its final value.  *Note
15381The ‘let*’ expression: fwd-para let, for more about ‘let*’.)
15382
15383
15384File: eintr.info,  Node: Y Axis Element,  Next: Y-axis-column,  Prev: Compute a Remainder,  Up: print-Y-axis
15385
15386C.2.2 Construct a Y Axis Element
15387--------------------------------
15388
15389When we print the vertical axis, we want to insert strings such as ‘5 -’
15390and ‘10 - ’ every five lines.  Moreover, we want the numbers and dashes
15391to line up, so shorter numbers must be padded with leading spaces.  If
15392some of the strings use two digit numbers, the strings with single digit
15393numbers must include a leading blank space before the number.
15394
15395   To figure out the length of the number, the ‘length’ function is
15396used.  But the ‘length’ function works only with a string, not with a
15397number.  So the number has to be converted from being a number to being
15398a string.  This is done with the ‘number-to-string’ function.  For
15399example,
15400
15401     (length (number-to-string 35))
15402          ⇒ 2
15403
15404     (length (number-to-string 100))
15405          ⇒ 3
15406
15407(‘number-to-string’ is also called ‘int-to-string’; you will see this
15408alternative name in various sources.)
15409
15410   In addition, in each label, each number is followed by a string such
15411as ‘ - ’, which we will call the ‘Y-axis-tic’ marker.  This variable is
15412defined with ‘defvar’:
15413
15414     (defvar Y-axis-tic " - "
15415        "String that follows number in a Y axis label.")
15416
15417   The length of the Y label is the sum of the length of the Y axis tic
15418mark and the length of the number of the top of the graph.
15419
15420     (length (concat (number-to-string height) Y-axis-tic)))
15421
15422   This value will be calculated by the ‘print-graph’ function in its
15423varlist as ‘full-Y-label-width’ and passed on.  (Note that we did not
15424think to include this in the varlist when we first proposed it.)
15425
15426   To make a complete vertical axis label, a tic mark is concatenated
15427with a number; and the two together may be preceded by one or more
15428spaces depending on how long the number is.  The label consists of three
15429parts: the (optional) leading spaces, the number, and the tic mark.  The
15430function is passed the value of the number for the specific row, and the
15431value of the width of the top line, which is calculated (just once) by
15432‘print-graph’.
15433
15434     (defun Y-axis-element (number full-Y-label-width)
15435       "Construct a NUMBERed label element.
15436     A numbered element looks like this `  5 - ',
15437     and is padded as needed so all line up with
15438     the element for the largest number."
15439       (let* ((leading-spaces
15440              (- full-Y-label-width
15441                 (length
15442                  (concat (number-to-string number)
15443                          Y-axis-tic)))))
15444         (concat
15445          (make-string leading-spaces ? )
15446          (number-to-string number)
15447          Y-axis-tic)))
15448
15449   The ‘Y-axis-element’ function concatenates together the leading
15450spaces, if any; the number, as a string; and the tic mark.
15451
15452   To figure out how many leading spaces the label will need, the
15453function subtracts the actual length of the label—the length of the
15454number plus the length of the tic mark—from the desired label width.
15455
15456   Blank spaces are inserted using the ‘make-string’ function.  This
15457function takes two arguments: the first tells it how long the string
15458will be and the second is a symbol for the character to insert, in a
15459special format.  The format is a question mark followed by a blank
15460space, like this, ‘? ’.  *Note Character Type: (elisp)Character Type,
15461for a description of the syntax for characters.  (Of course, you might
15462want to replace the blank space by some other character ... You know
15463what to do.)
15464
15465   The ‘number-to-string’ function is used in the concatenation
15466expression, to convert the number to a string that is concatenated with
15467the leading spaces and the tic mark.
15468
15469
15470File: eintr.info,  Node: Y-axis-column,  Next: print-Y-axis Penultimate,  Prev: Y Axis Element,  Up: print-Y-axis
15471
15472C.2.3 Create a Y Axis Column
15473----------------------------
15474
15475The preceding functions provide all the tools needed to construct a
15476function that generates a list of numbered and blank strings to insert
15477as the label for the vertical axis:
15478
15479     (defun Y-axis-column (height width-of-label)
15480       "Construct list of Y axis labels and blank strings.
15481     For HEIGHT of line above base and WIDTH-OF-LABEL."
15482       (let (Y-axis)
15483         (while (> height 1)
15484           (if (zerop (% height Y-axis-label-spacing))
15485               ;; Insert label.
15486               (setq Y-axis
15487                     (cons
15488                      (Y-axis-element height width-of-label)
15489                      Y-axis))
15490             ;; Else, insert blanks.
15491             (setq Y-axis
15492                   (cons
15493                    (make-string width-of-label ? )
15494                    Y-axis)))
15495           (setq height (1- height)))
15496         ;; Insert base line.
15497         (setq Y-axis
15498               (cons (Y-axis-element 1 width-of-label) Y-axis))
15499         (nreverse Y-axis)))
15500
15501   In this function, we start with the value of ‘height’ and
15502repetitively subtract one from its value.  After each subtraction, we
15503test to see whether the value is an integral multiple of the
15504‘Y-axis-label-spacing’.  If it is, we construct a numbered label using
15505the ‘Y-axis-element’ function; if not, we construct a blank label using
15506the ‘make-string’ function.  The base line consists of the number one
15507followed by a tic mark.
15508
15509
15510File: eintr.info,  Node: print-Y-axis Penultimate,  Prev: Y-axis-column,  Up: print-Y-axis
15511
15512C.2.4 The Not Quite Final Version of ‘print-Y-axis’
15513---------------------------------------------------
15514
15515The list constructed by the ‘Y-axis-column’ function is passed to the
15516‘print-Y-axis’ function, which inserts the list as a column.
15517
15518     (defun print-Y-axis (height full-Y-label-width)
15519       "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
15520     Height must be the maximum height of the graph.
15521     Full width is the width of the highest label element."
15522     ;; Value of height and full-Y-label-width
15523     ;; are passed by print-graph.
15524       (let ((start (point)))
15525         (insert-rectangle
15526          (Y-axis-column height full-Y-label-width))
15527         ;; Place point ready for inserting graph.
15528         (goto-char start)
15529         ;; Move point forward by value of full-Y-label-width
15530         (forward-char full-Y-label-width)))
15531
15532   The ‘print-Y-axis’ uses the ‘insert-rectangle’ function to insert the
15533Y axis labels created by the ‘Y-axis-column’ function.  In addition, it
15534places point at the correct position for printing the body of the graph.
15535
15536   You can test ‘print-Y-axis’:
15537
15538  1. Install
15539
15540          Y-axis-label-spacing
15541          Y-axis-tic
15542          Y-axis-element
15543          Y-axis-column
15544          print-Y-axis
15545
15546  2. Copy the following expression:
15547
15548          (print-Y-axis 12 5)
15549
15550  3. Switch to the ‘*scratch*’ buffer and place the cursor where you
15551     want the axis labels to start.
15552
15553  4. Type ‘M-:’ (‘eval-expression’).
15554
15555  5. Yank the ‘graph-body-print’ expression into the minibuffer with
15556     ‘C-y’ (‘yank)’.
15557
15558  6. Press <RET> to evaluate the expression.
15559
15560   Emacs will print labels vertically, the top one being ‘10 - ’.  (The
15561‘print-graph’ function will pass the value of ‘height-of-top-line’,
15562which in this case will end up as 15, thereby getting rid of what might
15563appear as a bug.)
15564
15565
15566File: eintr.info,  Node: print-X-axis,  Next: Print Whole Graph,  Prev: print-Y-axis,  Up: Full Graph
15567
15568C.3 The ‘print-X-axis’ Function
15569===============================
15570
15571X axis labels are much like Y axis labels, except that the ticks are on
15572a line above the numbers.  Labels should look like this:
15573
15574         |   |    |    |
15575         1   5   10   15
15576
15577   The first tic is under the first column of the graph and is preceded
15578by several blank spaces.  These spaces provide room in rows above for
15579the Y axis labels.  The second, third, fourth, and subsequent ticks are
15580all spaced equally, according to the value of ‘X-axis-label-spacing’.
15581
15582   The second row of the X axis consists of numbers, preceded by several
15583blank spaces and also separated according to the value of the variable
15584‘X-axis-label-spacing’.
15585
15586   The value of the variable ‘X-axis-label-spacing’ should itself be
15587measured in units of ‘symbol-width’, since you may want to change the
15588width of the symbols that you are using to print the body of the graph
15589without changing the ways the graph is labeled.
15590
15591* Menu:
15592
15593* Similarities differences::    Much like ‘print-Y-axis’, but not exactly.
15594* X Axis Tic Marks::            Create tic marks for the horizontal axis.
15595
15596
15597File: eintr.info,  Node: Similarities differences,  Next: X Axis Tic Marks,  Up: print-X-axis
15598
15599Similarities and differences
15600----------------------------
15601
15602The ‘print-X-axis’ function is constructed in more or less the same
15603fashion as the ‘print-Y-axis’ function except that it has two lines: the
15604line of tic marks and the numbers.  We will write a separate function to
15605print each line and then combine them within the ‘print-X-axis’
15606function.
15607
15608   This is a three step process:
15609
15610  1. Write a function to print the X axis tic marks,
15611     ‘print-X-axis-tic-line’.
15612
15613  2. Write a function to print the X numbers,
15614     ‘print-X-axis-numbered-line’.
15615
15616  3. Write a function to print both lines, the ‘print-X-axis’ function,
15617     using ‘print-X-axis-tic-line’ and ‘print-X-axis-numbered-line’.
15618
15619
15620File: eintr.info,  Node: X Axis Tic Marks,  Prev: Similarities differences,  Up: print-X-axis
15621
15622C.3.1 X Axis Tic Marks
15623----------------------
15624
15625The first function should print the X axis tic marks.  We must specify
15626the tic marks themselves and their spacing:
15627
15628     (defvar X-axis-label-spacing
15629       (if (boundp 'graph-blank)
15630           (* 5 (length graph-blank)) 5)
15631       "Number of units from one X axis label to next.")
15632
15633(Note that the value of ‘graph-blank’ is set by another ‘defvar’.  The
15634‘boundp’ predicate checks whether it has already been set; ‘boundp’
15635returns ‘nil’ if it has not.  If ‘graph-blank’ were unbound and we did
15636not use this conditional construction, in a recent GNU Emacs, we would
15637enter the debugger and see an error message saying
15638‘Debugger entered--Lisp error: (void-variable graph-blank)’.)
15639
15640   Here is the ‘defvar’ for ‘X-axis-tic-symbol’:
15641
15642     (defvar X-axis-tic-symbol "|"
15643       "String to insert to point to a column in X axis.")
15644
15645   The goal is to make a line that looks like this:
15646
15647            |   |    |    |
15648
15649   The first tic is indented so that it is under the first column, which
15650is indented to provide space for the Y axis labels.
15651
15652   A tic element consists of the blank spaces that stretch from one tic
15653to the next plus a tic symbol.  The number of blanks is determined by
15654the width of the tic symbol and the ‘X-axis-label-spacing’.
15655
15656   The code looks like this:
15657
15658     ;;; X-axis-tic-element
15659     ...
15660     (concat
15661      (make-string
15662       ;; Make a string of blanks.
15663       (-  (* symbol-width X-axis-label-spacing)
15664           (length X-axis-tic-symbol))
15665       ? )
15666      ;; Concatenate blanks with tic symbol.
15667      X-axis-tic-symbol)
15668     ...
15669
15670   Next, we determine how many blanks are needed to indent the first tic
15671mark to the first column of the graph.  This uses the value of
15672‘full-Y-label-width’ passed it by the ‘print-graph’ function.
15673
15674   The code to make ‘X-axis-leading-spaces’ looks like this:
15675
15676     ;; X-axis-leading-spaces
15677     ...
15678     (make-string full-Y-label-width ? )
15679     ...
15680
15681   We also need to determine the length of the horizontal axis, which is
15682the length of the numbers list, and the number of ticks in the
15683horizontal axis:
15684
15685     ;; X-length
15686     ...
15687     (length numbers-list)
15688
15689     ;; tic-width
15690     ...
15691     (* symbol-width X-axis-label-spacing)
15692
15693     ;; number-of-X-ticks
15694     (if (zerop (% (X-length tic-width)))
15695         (/ (X-length tic-width))
15696       (1+ (/ (X-length tic-width))))
15697
15698   All this leads us directly to the function for printing the X axis
15699tic line:
15700
15701     (defun print-X-axis-tic-line
15702       (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
15703       "Print ticks for X axis."
15704         (insert X-axis-leading-spaces)
15705         (insert X-axis-tic-symbol)  ; Under first column.
15706         ;; Insert second tic in the right spot.
15707         (insert (concat
15708                  (make-string
15709                   (-  (* symbol-width X-axis-label-spacing)
15710                       ;; Insert white space up to second tic symbol.
15711                       (* 2 (length X-axis-tic-symbol)))
15712                   ? )
15713                  X-axis-tic-symbol))
15714         ;; Insert remaining ticks.
15715         (while (> number-of-X-tics 1)
15716           (insert X-axis-tic-element)
15717           (setq number-of-X-tics (1- number-of-X-tics))))
15718
15719   The line of numbers is equally straightforward:
15720
15721   First, we create a numbered element with blank spaces before each
15722number:
15723
15724     (defun X-axis-element (number)
15725       "Construct a numbered X axis element."
15726       (let ((leading-spaces
15727              (-  (* symbol-width X-axis-label-spacing)
15728                  (length (number-to-string number)))))
15729         (concat (make-string leading-spaces ? )
15730                 (number-to-string number))))
15731
15732   Next, we create the function to print the numbered line, starting
15733with the number 1 under the first column:
15734
15735     (defun print-X-axis-numbered-line
15736       (number-of-X-tics X-axis-leading-spaces)
15737       "Print line of X-axis numbers"
15738       (let ((number X-axis-label-spacing))
15739         (insert X-axis-leading-spaces)
15740         (insert "1")
15741         (insert (concat
15742                  (make-string
15743                   ;; Insert white space up to next number.
15744                   (-  (* symbol-width X-axis-label-spacing) 2)
15745                   ? )
15746                  (number-to-string number)))
15747         ;; Insert remaining numbers.
15748         (setq number (+ number X-axis-label-spacing))
15749         (while (> number-of-X-tics 1)
15750           (insert (X-axis-element number))
15751           (setq number (+ number X-axis-label-spacing))
15752           (setq number-of-X-tics (1- number-of-X-tics)))))
15753
15754   Finally, we need to write the ‘print-X-axis’ that uses
15755‘print-X-axis-tic-line’ and ‘print-X-axis-numbered-line’.
15756
15757   The function must determine the local values of the variables used by
15758both ‘print-X-axis-tic-line’ and ‘print-X-axis-numbered-line’, and then
15759it must call them.  Also, it must print the carriage return that
15760separates the two lines.
15761
15762   The function consists of a varlist that specifies five local
15763variables, and calls to each of the two line printing functions:
15764
15765     (defun print-X-axis (numbers-list)
15766       "Print X axis labels to length of NUMBERS-LIST."
15767       (let* ((leading-spaces
15768               (make-string full-Y-label-width ? ))
15769            ;; symbol-width is provided by graph-body-print
15770            (tic-width (* symbol-width X-axis-label-spacing))
15771            (X-length (length numbers-list))
15772            (X-tic
15773             (concat
15774              (make-string
15775               ;; Make a string of blanks.
15776               (-  (* symbol-width X-axis-label-spacing)
15777                   (length X-axis-tic-symbol))
15778               ? )
15779              ;; Concatenate blanks with tic symbol.
15780              X-axis-tic-symbol))
15781            (tic-number
15782             (if (zerop (% X-length tic-width))
15783                 (/ X-length tic-width)
15784               (1+ (/ X-length tic-width)))))
15785         (print-X-axis-tic-line tic-number leading-spaces X-tic)
15786         (insert "\n")
15787         (print-X-axis-numbered-line tic-number leading-spaces)))
15788
15789   You can test ‘print-X-axis’:
15790
15791  1. Install ‘X-axis-tic-symbol’, ‘X-axis-label-spacing’,
15792     ‘print-X-axis-tic-line’, as well as ‘X-axis-element’,
15793     ‘print-X-axis-numbered-line’, and ‘print-X-axis’.
15794
15795  2. Copy the following expression:
15796
15797          (progn
15798           (let ((full-Y-label-width 5)
15799                 (symbol-width 1))
15800             (print-X-axis
15801              '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
15802
15803  3. Switch to the ‘*scratch*’ buffer and place the cursor where you
15804     want the axis labels to start.
15805
15806  4. Type ‘M-:’ (‘eval-expression’).
15807
15808  5. Yank the test expression into the minibuffer with ‘C-y’ (‘yank)’.
15809
15810  6. Press <RET> to evaluate the expression.
15811
15812   Emacs will print the horizontal axis like this:
15813
15814          |   |    |    |    |
15815          1   5   10   15   20
15816
15817
15818File: eintr.info,  Node: Print Whole Graph,  Prev: print-X-axis,  Up: Full Graph
15819
15820C.4 Printing the Whole Graph
15821============================
15822
15823Now we are nearly ready to print the whole graph.
15824
15825   The function to print the graph with the proper labels follows the
15826outline we created earlier (*note A Graph with Labeled Axes: Full
15827Graph.), but with additions.
15828
15829   Here is the outline:
15830
15831     (defun print-graph (numbers-list)
15832       "DOCUMENTATION..."
15833       (let ((height  ...
15834             ...))
15835         (print-Y-axis height ... )
15836         (graph-body-print numbers-list)
15837         (print-X-axis ... )))
15838
15839* Menu:
15840
15841* The final version::           A few changes.
15842* Test print-graph::            Run a short test.
15843* Graphing words in defuns::    Executing the final code.
15844* lambda::                      How to write an anonymous function.
15845* mapcar::                      Apply a function to elements of a list.
15846* Another Bug::                 Yet another bug ... most insidious.
15847* Final printed graph::         The graph itself!
15848
15849
15850File: eintr.info,  Node: The final version,  Next: Test print-graph,  Up: Print Whole Graph
15851
15852Changes for the Final Version
15853-----------------------------
15854
15855The final version is different from what we planned in two ways: first,
15856it contains additional values calculated once in the varlist; second, it
15857carries an option to specify the labels’ increment per row.  This latter
15858feature turns out to be essential; otherwise, a graph may have more rows
15859than fit on a display or on a sheet of paper.
15860
15861   This new feature requires a change to the ‘Y-axis-column’ function,
15862to add ‘vertical-step’ to it.  The function looks like this:
15863
15864     ;;; Final version.
15865     (defun Y-axis-column
15866       (height width-of-label &optional vertical-step)
15867       "Construct list of labels for Y axis.
15868     HEIGHT is maximum height of graph.
15869     WIDTH-OF-LABEL is maximum width of label.
15870     VERTICAL-STEP, an option, is a positive integer
15871     that specifies how much a Y axis label increments
15872     for each line.  For example, a step of 5 means
15873     that each line is five units of the graph."
15874       (let (Y-axis
15875             (number-per-line (or vertical-step 1)))
15876         (while (> height 1)
15877           (if (zerop (% height Y-axis-label-spacing))
15878               ;; Insert label.
15879               (setq Y-axis
15880                     (cons
15881                      (Y-axis-element
15882                       (* height number-per-line)
15883                       width-of-label)
15884                      Y-axis))
15885             ;; Else, insert blanks.
15886             (setq Y-axis
15887                   (cons
15888                    (make-string width-of-label ? )
15889                    Y-axis)))
15890           (setq height (1- height)))
15891         ;; Insert base line.
15892         (setq Y-axis (cons (Y-axis-element
15893                             (or vertical-step 1)
15894                             width-of-label)
15895                            Y-axis))
15896         (nreverse Y-axis)))
15897
15898   The values for the maximum height of graph and the width of a symbol
15899are computed by ‘print-graph’ in its ‘let’ expression; so
15900‘graph-body-print’ must be changed to accept them.
15901
15902     ;;; Final version.
15903     (defun graph-body-print (numbers-list height symbol-width)
15904       "Print a bar graph of the NUMBERS-LIST.
15905     The numbers-list consists of the Y-axis values.
15906     HEIGHT is maximum height of graph.
15907     SYMBOL-WIDTH is number of each column."
15908       (let (from-position)
15909         (while numbers-list
15910           (setq from-position (point))
15911           (insert-rectangle
15912            (column-of-graph height (car numbers-list)))
15913           (goto-char from-position)
15914           (forward-char symbol-width)
15915           ;; Draw graph column by column.
15916           (sit-for 0)
15917           (setq numbers-list (cdr numbers-list)))
15918         ;; Place point for X axis labels.
15919         (forward-line height)
15920         (insert "\n")))
15921
15922   Finally, the code for the ‘print-graph’ function:
15923
15924     ;;; Final version.
15925     (defun print-graph
15926       (numbers-list &optional vertical-step)
15927       "Print labeled bar graph of the NUMBERS-LIST.
15928     The numbers-list consists of the Y-axis values.
15929
15930     Optionally, VERTICAL-STEP, a positive integer,
15931     specifies how much a Y axis label increments for
15932     each line.  For example, a step of 5 means that
15933     each row is five units."
15934       (let* ((symbol-width (length graph-blank))
15935              ;; height is both the largest number
15936              ;; and the number with the most digits.
15937              (height (apply 'max numbers-list))
15938              (height-of-top-line
15939               (if (zerop (% height Y-axis-label-spacing))
15940                   height
15941                 ;; else
15942                 (* (1+ (/ height Y-axis-label-spacing))
15943                    Y-axis-label-spacing)))
15944              (vertical-step (or vertical-step 1))
15945              (full-Y-label-width
15946               (length
15947                (concat
15948                 (number-to-string
15949                  (* height-of-top-line vertical-step))
15950                 Y-axis-tic))))
15951
15952         (print-Y-axis
15953          height-of-top-line full-Y-label-width vertical-step)
15954         (graph-body-print
15955          numbers-list height-of-top-line symbol-width)
15956         (print-X-axis numbers-list)))
15957
15958
15959File: eintr.info,  Node: Test print-graph,  Next: Graphing words in defuns,  Prev: The final version,  Up: Print Whole Graph
15960
15961C.4.1 Testing ‘print-graph’
15962---------------------------
15963
15964We can test the ‘print-graph’ function with a short list of numbers:
15965
15966  1. Install the final versions of ‘Y-axis-column’, ‘graph-body-print’,
15967     and ‘print-graph’ (in addition to the rest of the code.)
15968
15969  2. Copy the following expression:
15970
15971          (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
15972
15973  3. Switch to the ‘*scratch*’ buffer and place the cursor where you
15974     want the axis labels to start.
15975
15976  4. Type ‘M-:’ (‘eval-expression’).
15977
15978  5. Yank the test expression into the minibuffer with ‘C-y’ (‘yank)’.
15979
15980  6. Press <RET> to evaluate the expression.
15981
15982   Emacs will print a graph that looks like this:
15983
15984     10 -
15985
15986
15987              *
15988             **   *
15989      5 -   ****  *
15990            **** ***
15991          * *********
15992          ************
15993      1 - *************
15994
15995          |   |    |    |
15996          1   5   10   15
15997
15998   On the other hand, if you pass ‘print-graph’ a ‘vertical-step’ value
15999of 2, by evaluating this expression:
16000
16001     (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
16002
16003The graph looks like this:
16004
16005     20 -
16006
16007
16008              *
16009             **   *
16010     10 -   ****  *
16011            **** ***
16012          * *********
16013          ************
16014      2 - *************
16015
16016          |   |    |    |
16017          1   5   10   15
16018
16019(A question: is the ‘2’ on the bottom of the vertical axis a bug or a
16020feature?  If you think it is a bug, and should be a ‘1’ instead, (or
16021even a ‘0’), you can modify the sources.)
16022
16023
16024File: eintr.info,  Node: Graphing words in defuns,  Next: lambda,  Prev: Test print-graph,  Up: Print Whole Graph
16025
16026C.4.2 Graphing Numbers of Words and Symbols
16027-------------------------------------------
16028
16029Now for the graph for which all this code was written: a graph that
16030shows how many function definitions contain fewer than 10 words and
16031symbols, how many contain between 10 and 19 words and symbols, how many
16032contain between 20 and 29 words and symbols, and so on.
16033
16034   This is a multi-step process.  First make sure you have loaded all
16035the requisite code.
16036
16037   It is a good idea to reset the value of ‘top-of-ranges’ in case you
16038have set it to some different value.  You can evaluate the following:
16039
16040     (setq top-of-ranges
16041      '(10  20  30  40  50
16042        60  70  80  90 100
16043       110 120 130 140 150
16044       160 170 180 190 200
16045       210 220 230 240 250
16046       260 270 280 290 300)
16047
16048Next create a list of the number of words and symbols in each range.
16049
16050Evaluate the following:
16051
16052     (setq list-for-graph
16053            (defuns-per-range
16054              (sort
16055               (recursive-lengths-list-many-files
16056                (directory-files "/usr/local/emacs/lisp"
16057                                 t ".+el$"))
16058               '<)
16059              top-of-ranges))
16060
16061On my old machine, this took about an hour.  It looked though 303 Lisp
16062files in my copy of Emacs version 19.23.  After all that computing, the
16063‘list-for-graph’ had this value:
16064
16065     (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
16066     90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
16067
16068This means that my copy of Emacs had 537 function definitions with fewer
16069than 10 words or symbols in them, 1,027 function definitions with 10 to
1607019 words or symbols in them, 955 function definitions with 20 to 29
16071words or symbols in them, and so on.
16072
16073   Clearly, just by looking at this list we can see that most function
16074definitions contain ten to thirty words and symbols.
16075
16076   Now for printing.  We do _not_ want to print a graph that is 1,030
16077lines high ... Instead, we should print a graph that is fewer than
16078twenty-five lines high.  A graph that height can be displayed on almost
16079any monitor, and easily printed on a sheet of paper.
16080
16081   This means that each value in ‘list-for-graph’ must be reduced to
16082one-fiftieth its present value.
16083
16084   Here is a short function to do just that, using two functions we have
16085not yet seen, ‘mapcar’ and ‘lambda’.
16086
16087     (defun one-fiftieth (full-range)
16088       "Return list, each number one-fiftieth of previous."
16089      (mapcar (lambda (arg) (/ arg 50)) full-range))
16090
16091
16092File: eintr.info,  Node: lambda,  Next: mapcar,  Prev: Graphing words in defuns,  Up: Print Whole Graph
16093
16094C.4.3 A ‘lambda’ Expression: Useful Anonymity
16095---------------------------------------------
16096
16097‘lambda’ is the symbol for an anonymous function, a function without a
16098name.  Every time you use an anonymous function, you need to include its
16099whole body.
16100
16101Thus,
16102
16103     (lambda (arg) (/ arg 50))
16104
16105is a function that returns the value resulting from dividing whatever is
16106passed to it as ‘arg’ by 50.
16107
16108   Earlier, for example, we had a function ‘multiply-by-seven’; it
16109multiplied its argument by 7.  This function is similar, except it
16110divides its argument by 50; and, it has no name.  The anonymous
16111equivalent of ‘multiply-by-seven’ is:
16112
16113     (lambda (number) (* 7 number))
16114
16115(*Note The ‘defun’ Macro: defun.)
16116
16117If we want to multiply 3 by 7, we can write:
16118
16119     (multiply-by-seven 3)
16120      \_______________/ ^
16121              |         |
16122           function  argument
16123
16124
16125This expression returns 21.
16126
16127Similarly, we can write:
16128
16129     ((lambda (number) (* 7 number)) 3)
16130      \____________________________/ ^
16131                    |                |
16132           anonymous function     argument
16133
16134
16135If we want to divide 100 by 50, we can write:
16136
16137     ((lambda (arg) (/ arg 50)) 100)
16138      \______________________/  \_/
16139                  |              |
16140         anonymous function   argument
16141
16142
16143This expression returns 2.  The 100 is passed to the function, which
16144divides that number by 50.
16145
16146   *Note Lambda Expressions: (elisp)Lambda Expressions, for more about
16147‘lambda’.  Lisp and lambda expressions derive from the Lambda Calculus.
16148
16149
16150File: eintr.info,  Node: mapcar,  Next: Another Bug,  Prev: lambda,  Up: Print Whole Graph
16151
16152C.4.4 The ‘mapcar’ Function
16153---------------------------
16154
16155‘mapcar’ is a function that calls its first argument with each element
16156of its second argument, in turn.  The second argument must be a
16157sequence.
16158
16159   The ‘map’ part of the name comes from the mathematical phrase,
16160“mapping over a domain”, meaning to apply a function to each of the
16161elements in a domain.  The mathematical phrase is based on the metaphor
16162of a surveyor walking, one step at a time, over an area he is mapping.
16163And ‘car’, of course, comes from the Lisp notion of the first of a list.
16164
16165For example,
16166
16167     (mapcar '1+ '(2 4 6))
16168          ⇒ (3 5 7)
16169
16170The function ‘1+’ which adds one to its argument, is executed on _each_
16171element of the list, and a new list is returned.
16172
16173   Contrast this with ‘apply’, which applies its first argument to all
16174the remaining.  (*Note Readying a Graph: Readying a Graph, for an
16175explanation of ‘apply’.)
16176
16177   In the definition of ‘one-fiftieth’, the first argument is the
16178anonymous function:
16179
16180     (lambda (arg) (/ arg 50))
16181
16182and the second argument is ‘full-range’, which will be bound to
16183‘list-for-graph’.
16184
16185   The whole expression looks like this:
16186
16187     (mapcar (lambda (arg) (/ arg 50)) full-range))
16188
16189   *Note Mapping Functions: (elisp)Mapping Functions, for more about
16190‘mapcar’.
16191
16192   Using the ‘one-fiftieth’ function, we can generate a list in which
16193each element is one-fiftieth the size of the corresponding element in
16194‘list-for-graph’.
16195
16196     (setq fiftieth-list-for-graph
16197           (one-fiftieth list-for-graph))
16198
16199   The resulting list looks like this:
16200
16201     (10 20 19 15 11 9 6 5 4 3 3 2 2
16202     1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
16203
16204This, we are almost ready to print!  (We also notice the loss of
16205information: many of the higher ranges are 0, meaning that fewer than 50
16206defuns had that many words or symbols—but not necessarily meaning that
16207none had that many words or symbols.)
16208
16209
16210File: eintr.info,  Node: Another Bug,  Next: Final printed graph,  Prev: mapcar,  Up: Print Whole Graph
16211
16212C.4.5 Another Bug ... Most Insidious
16213------------------------------------
16214
16215I said “almost ready to print”!  Of course, there is a bug in the
16216‘print-graph’ function ... It has a ‘vertical-step’ option, but not a
16217‘horizontal-step’ option.  The ‘top-of-range’ scale goes from 10 to 300
16218by tens.  But the ‘print-graph’ function will print only by ones.
16219
16220   This is a classic example of what some consider the most insidious
16221type of bug, the bug of omission.  This is not the kind of bug you can
16222find by studying the code, for it is not in the code; it is an omitted
16223feature.  Your best actions are to try your program early and often; and
16224try to arrange, as much as you can, to write code that is easy to
16225understand and easy to change.  Try to be aware, whenever you can, that
16226whatever you have written, _will_ be rewritten, if not soon, eventually.
16227A hard maxim to follow.
16228
16229   It is the ‘print-X-axis-numbered-line’ function that needs the work;
16230and then the ‘print-X-axis’ and the ‘print-graph’ functions need to be
16231adapted.  Not much needs to be done; there is one nicety: the numbers
16232ought to line up under the tic marks.  This takes a little thought.
16233
16234   Here is the corrected ‘print-X-axis-numbered-line’:
16235
16236     (defun print-X-axis-numbered-line
16237       (number-of-X-tics X-axis-leading-spaces
16238        &optional horizontal-step)
16239       "Print line of X-axis numbers"
16240       (let ((number X-axis-label-spacing)
16241             (horizontal-step (or horizontal-step 1)))
16242         (insert X-axis-leading-spaces)
16243         ;; Delete extra leading spaces.
16244         (delete-char
16245          (- (1-
16246              (length (number-to-string horizontal-step)))))
16247         (insert (concat
16248                  (make-string
16249                   ;; Insert white space.
16250                   (-  (* symbol-width
16251                          X-axis-label-spacing)
16252                       (1-
16253                        (length
16254                         (number-to-string horizontal-step)))
16255                       2)
16256                   ? )
16257                  (number-to-string
16258                   (* number horizontal-step))))
16259         ;; Insert remaining numbers.
16260         (setq number (+ number X-axis-label-spacing))
16261         (while (> number-of-X-tics 1)
16262           (insert (X-axis-element
16263                    (* number horizontal-step)))
16264           (setq number (+ number X-axis-label-spacing))
16265           (setq number-of-X-tics (1- number-of-X-tics)))))
16266
16267   If you are reading this in Info, you can see the new versions of
16268‘print-X-axis’ ‘print-graph’ and evaluate them.  If you are reading this
16269in a printed book, you can see the changed lines here (the full text is
16270too much to print).
16271
16272     (defun print-X-axis (numbers-list horizontal-step)
16273       "Print X axis labels to length of NUMBERS-LIST.
16274     Optionally, HORIZONTAL-STEP, a positive integer,
16275     specifies how much an X  axis label increments for
16276     each column."
16277     ;; Value of symbol-width and full-Y-label-width
16278     ;; are passed by print-graph.
16279       (let* ((leading-spaces
16280               (make-string full-Y-label-width ? ))
16281            ;; symbol-width is provided by graph-body-print
16282            (tic-width (* symbol-width X-axis-label-spacing))
16283            (X-length (length numbers-list))
16284            (X-tic
16285             (concat
16286              (make-string
16287               ;; Make a string of blanks.
16288               (-  (* symbol-width X-axis-label-spacing)
16289                   (length X-axis-tic-symbol))
16290               ? )
16291              ;; Concatenate blanks with tic symbol.
16292              X-axis-tic-symbol))
16293            (tic-number
16294             (if (zerop (% X-length tic-width))
16295                 (/ X-length tic-width)
16296               (1+ (/ X-length tic-width)))))
16297
16298         (print-X-axis-tic-line
16299          tic-number leading-spaces X-tic)
16300         (insert "\n")
16301         (print-X-axis-numbered-line
16302          tic-number leading-spaces horizontal-step)))
16303
16304     (defun print-graph
16305       (numbers-list &optional vertical-step horizontal-step)
16306       "Print labeled bar graph of the NUMBERS-LIST.
16307     The numbers-list consists of the Y-axis values.
16308
16309     Optionally, VERTICAL-STEP, a positive integer,
16310     specifies how much a Y axis label increments for
16311     each line.  For example, a step of 5 means that
16312     each row is five units.
16313
16314     Optionally, HORIZONTAL-STEP, a positive integer,
16315     specifies how much an X  axis label increments for
16316     each column."
16317       (let* ((symbol-width (length graph-blank))
16318              ;; height is both the largest number
16319              ;; and the number with the most digits.
16320              (height (apply 'max numbers-list))
16321              (height-of-top-line
16322               (if (zerop (% height Y-axis-label-spacing))
16323                   height
16324                 ;; else
16325                 (* (1+ (/ height Y-axis-label-spacing))
16326                    Y-axis-label-spacing)))
16327              (vertical-step (or vertical-step 1))
16328              (full-Y-label-width
16329               (length
16330                (concat
16331                 (number-to-string
16332                  (* height-of-top-line vertical-step))
16333                 Y-axis-tic))))
16334         (print-Y-axis
16335          height-of-top-line full-Y-label-width vertical-step)
16336         (graph-body-print
16337             numbers-list height-of-top-line symbol-width)
16338         (print-X-axis numbers-list horizontal-step)))
16339
16340
16341File: eintr.info,  Node: Final printed graph,  Prev: Another Bug,  Up: Print Whole Graph
16342
16343C.4.6 The Printed Graph
16344-----------------------
16345
16346When made and installed, you can call the ‘print-graph’ command like
16347this:
16348
16349     (print-graph fiftieth-list-for-graph 50 10)
16350
16351Here is the graph:
16352
16353
16354     1000 -  *
16355             **
16356             **
16357             **
16358             **
16359      750 -  ***
16360             ***
16361             ***
16362             ***
16363             ****
16364      500 - *****
16365            ******
16366            ******
16367            ******
16368            *******
16369      250 - ********
16370            *********                     *
16371            ***********                   *
16372            *************                 *
16373       50 - ***************** *           *
16374            |   |    |    |    |    |    |    |
16375           10  50  100  150  200  250  300  350
16376
16377
16378
16379The largest group of functions contain 10–19 words and symbols each.
16380
16381
16382File: eintr.info,  Node: Free Software and Free Manuals,  Next: GNU Free Documentation License,  Prev: Full Graph,  Up: Top
16383
16384Appendix D Free Software and Free Manuals
16385*****************************************
16386
16387*by Richard M. Stallman*
16388
16389   The biggest deficiency in free operating systems is not in the
16390software—it is the lack of good free manuals that we can include in
16391these systems.  Many of our most important programs do not come with
16392full manuals.  Documentation is an essential part of any software
16393package; when an important free software package does not come with a
16394free manual, that is a major gap.  We have many such gaps today.
16395
16396   Once upon a time, many years ago, I thought I would learn Perl.  I
16397got a copy of a free manual, but I found it hard to read.  When I asked
16398Perl users about alternatives, they told me that there were better
16399introductory manuals—but those were not free.
16400
16401   Why was this?  The authors of the good manuals had written them for
16402O’Reilly Associates, which published them with restrictive terms—no
16403copying, no modification, source files not available—which exclude them
16404from the free software community.
16405
16406   That wasn’t the first time this sort of thing has happened, and (to
16407our community’s great loss) it was far from the last.  Proprietary
16408manual publishers have enticed a great many authors to restrict their
16409manuals since then.  Many times I have heard a GNU user eagerly tell me
16410about a manual that he is writing, with which he expects to help the GNU
16411project—and then had my hopes dashed, as he proceeded to explain that he
16412had signed a contract with a publisher that would restrict it so that we
16413cannot use it.
16414
16415   Given that writing good English is a rare skill among programmers, we
16416can ill afford to lose manuals this way.
16417
16418   Free documentation, like free software, is a matter of freedom, not
16419price.  The problem with these manuals was not that O’Reilly Associates
16420charged a price for printed copies—that in itself is fine.  The Free
16421Software Foundation sells printed copies (https://shop.fsf.org) of free
16422GNU manuals (https://www.gnu.org/doc/doc.html), too.  But GNU manuals
16423are available in source code form, while these manuals are available
16424only on paper.  GNU manuals come with permission to copy and modify; the
16425Perl manuals do not.  These restrictions are the problems.
16426
16427   The criterion for a free manual is pretty much the same as for free
16428software: it is a matter of giving all users certain freedoms.
16429Redistribution (including commercial redistribution) must be permitted,
16430so that the manual can accompany every copy of the program, on-line or
16431on paper.  Permission for modification is crucial too.
16432
16433   As a general rule, I don’t believe that it is essential for people to
16434have permission to modify all sorts of articles and books.  The issues
16435for writings are not necessarily the same as those for software.  For
16436example, I don’t think you or I are obliged to give permission to modify
16437articles like this one, which describe our actions and our views.
16438
16439   But there is a particular reason why the freedom to modify is crucial
16440for documentation for free software.  When people exercise their right
16441to modify the software, and add or change its features, if they are
16442conscientious they will change the manual too—so they can provide
16443accurate and usable documentation with the modified program.  A manual
16444which forbids programmers to be conscientious and finish the job, or
16445more precisely requires them to write a new manual from scratch if they
16446change the program, does not fill our community’s needs.
16447
16448   While a blanket prohibition on modification is unacceptable, some
16449kinds of limits on the method of modification pose no problem.  For
16450example, requirements to preserve the original author’s copyright
16451notice, the distribution terms, or the list of authors, are ok.  It is
16452also no problem to require modified versions to include notice that they
16453were modified, even to have entire sections that may not be deleted or
16454changed, as long as these sections deal with nontechnical topics.  (Some
16455GNU manuals have them.)
16456
16457   These kinds of restrictions are not a problem because, as a practical
16458matter, they don’t stop the conscientious programmer from adapting the
16459manual to fit the modified program.  In other words, they don’t block
16460the free software community from making full use of the manual.
16461
16462   However, it must be possible to modify all the technical content of
16463the manual, and then distribute the result in all the usual media,
16464through all the usual channels; otherwise, the restrictions do block the
16465community, the manual is not free, and so we need another manual.
16466
16467   Unfortunately, it is often hard to find someone to write another
16468manual when a proprietary manual exists.  The obstacle is that many
16469users think that a proprietary manual is good enough—so they don’t see
16470the need to write a free manual.  They do not see that the free
16471operating system has a gap that needs filling.
16472
16473   Why do users think that proprietary manuals are good enough?  Some
16474have not considered the issue.  I hope this article will do something to
16475change that.
16476
16477   Other users consider proprietary manuals acceptable for the same
16478reason so many people consider proprietary software acceptable: they
16479judge in purely practical terms, not using freedom as a criterion.
16480These people are entitled to their opinions, but since those opinions
16481spring from values which do not include freedom, they are no guide for
16482those of us who do value freedom.
16483
16484   Please spread the word about this issue.  We continue to lose manuals
16485to proprietary publishing.  If we spread the word that proprietary
16486manuals are not sufficient, perhaps the next person who wants to help
16487GNU by writing documentation will realize, before it is too late, that
16488he must above all make it free.
16489
16490   We can also encourage commercial publishers to sell free, copylefted
16491manuals instead of proprietary ones.  One way you can help this is to
16492check the distribution terms of a manual before you buy it, and prefer
16493copylefted manuals to non-copylefted ones.
16494
16495
16496
16497Note: The Free Software Foundation maintains a page on its Web site that
16498lists free books available from other publishers:
16499<https://www.gnu.org/doc/other-free-books.html>
16500
16501
16502File: eintr.info,  Node: GNU Free Documentation License,  Next: Index,  Prev: Free Software and Free Manuals,  Up: Top
16503
16504Appendix E GNU Free Documentation License
16505*****************************************
16506
16507                     Version 1.3, 3 November 2008
16508
16509     Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc.
16510     <https://fsf.org/>
16511
16512     Everyone is permitted to copy and distribute verbatim copies
16513     of this license document, but changing it is not allowed.
16514
16515  0. PREAMBLE
16516
16517     The purpose of this License is to make a manual, textbook, or other
16518     functional and useful document “free” in the sense of freedom: to
16519     assure everyone the effective freedom to copy and redistribute it,
16520     with or without modifying it, either commercially or
16521     noncommercially.  Secondarily, this License preserves for the
16522     author and publisher a way to get credit for their work, while not
16523     being considered responsible for modifications made by others.
16524
16525     This License is a kind of “copyleft”, which means that derivative
16526     works of the document must themselves be free in the same sense.
16527     It complements the GNU General Public License, which is a copyleft
16528     license designed for free software.
16529
16530     We have designed this License in order to use it for manuals for
16531     free software, because free software needs free documentation: a
16532     free program should come with manuals providing the same freedoms
16533     that the software does.  But this License is not limited to
16534     software manuals; it can be used for any textual work, regardless
16535     of subject matter or whether it is published as a printed book.  We
16536     recommend this License principally for works whose purpose is
16537     instruction or reference.
16538
16539  1. APPLICABILITY AND DEFINITIONS
16540
16541     This License applies to any manual or other work, in any medium,
16542     that contains a notice placed by the copyright holder saying it can
16543     be distributed under the terms of this License.  Such a notice
16544     grants a world-wide, royalty-free license, unlimited in duration,
16545     to use that work under the conditions stated herein.  The
16546     “Document”, below, refers to any such manual or work.  Any member
16547     of the public is a licensee, and is addressed as “you”.  You accept
16548     the license if you copy, modify or distribute the work in a way
16549     requiring permission under copyright law.
16550
16551     A “Modified Version” of the Document means any work containing the
16552     Document or a portion of it, either copied verbatim, or with
16553     modifications and/or translated into another language.
16554
16555     A “Secondary Section” is a named appendix or a front-matter section
16556     of the Document that deals exclusively with the relationship of the
16557     publishers or authors of the Document to the Document’s overall
16558     subject (or to related matters) and contains nothing that could
16559     fall directly within that overall subject.  (Thus, if the Document
16560     is in part a textbook of mathematics, a Secondary Section may not
16561     explain any mathematics.)  The relationship could be a matter of
16562     historical connection with the subject or with related matters, or
16563     of legal, commercial, philosophical, ethical or political position
16564     regarding them.
16565
16566     The “Invariant Sections” are certain Secondary Sections whose
16567     titles are designated, as being those of Invariant Sections, in the
16568     notice that says that the Document is released under this License.
16569     If a section does not fit the above definition of Secondary then it
16570     is not allowed to be designated as Invariant.  The Document may
16571     contain zero Invariant Sections.  If the Document does not identify
16572     any Invariant Sections then there are none.
16573
16574     The “Cover Texts” are certain short passages of text that are
16575     listed, as Front-Cover Texts or Back-Cover Texts, in the notice
16576     that says that the Document is released under this License.  A
16577     Front-Cover Text may be at most 5 words, and a Back-Cover Text may
16578     be at most 25 words.
16579
16580     A “Transparent” copy of the Document means a machine-readable copy,
16581     represented in a format whose specification is available to the
16582     general public, that is suitable for revising the document
16583     straightforwardly with generic text editors or (for images composed
16584     of pixels) generic paint programs or (for drawings) some widely
16585     available drawing editor, and that is suitable for input to text
16586     formatters or for automatic translation to a variety of formats
16587     suitable for input to text formatters.  A copy made in an otherwise
16588     Transparent file format whose markup, or absence of markup, has
16589     been arranged to thwart or discourage subsequent modification by
16590     readers is not Transparent.  An image format is not Transparent if
16591     used for any substantial amount of text.  A copy that is not
16592     “Transparent” is called “Opaque”.
16593
16594     Examples of suitable formats for Transparent copies include plain
16595     ASCII without markup, Texinfo input format, LaTeX input format,
16596     SGML or XML using a publicly available DTD, and standard-conforming
16597     simple HTML, PostScript or PDF designed for human modification.
16598     Examples of transparent image formats include PNG, XCF and JPG.
16599     Opaque formats include proprietary formats that can be read and
16600     edited only by proprietary word processors, SGML or XML for which
16601     the DTD and/or processing tools are not generally available, and
16602     the machine-generated HTML, PostScript or PDF produced by some word
16603     processors for output purposes only.
16604
16605     The “Title Page” means, for a printed book, the title page itself,
16606     plus such following pages as are needed to hold, legibly, the
16607     material this License requires to appear in the title page.  For
16608     works in formats which do not have any title page as such, “Title
16609     Page” means the text near the most prominent appearance of the
16610     work’s title, preceding the beginning of the body of the text.
16611
16612     The “publisher” means any person or entity that distributes copies
16613     of the Document to the public.
16614
16615     A section “Entitled XYZ” means a named subunit of the Document
16616     whose title either is precisely XYZ or contains XYZ in parentheses
16617     following text that translates XYZ in another language.  (Here XYZ
16618     stands for a specific section name mentioned below, such as
16619     “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.)
16620     To “Preserve the Title” of such a section when you modify the
16621     Document means that it remains a section “Entitled XYZ” according
16622     to this definition.
16623
16624     The Document may include Warranty Disclaimers next to the notice
16625     which states that this License applies to the Document.  These
16626     Warranty Disclaimers are considered to be included by reference in
16627     this License, but only as regards disclaiming warranties: any other
16628     implication that these Warranty Disclaimers may have is void and
16629     has no effect on the meaning of this License.
16630
16631  2. VERBATIM COPYING
16632
16633     You may copy and distribute the Document in any medium, either
16634     commercially or noncommercially, provided that this License, the
16635     copyright notices, and the license notice saying this License
16636     applies to the Document are reproduced in all copies, and that you
16637     add no other conditions whatsoever to those of this License.  You
16638     may not use technical measures to obstruct or control the reading
16639     or further copying of the copies you make or distribute.  However,
16640     you may accept compensation in exchange for copies.  If you
16641     distribute a large enough number of copies you must also follow the
16642     conditions in section 3.
16643
16644     You may also lend copies, under the same conditions stated above,
16645     and you may publicly display copies.
16646
16647  3. COPYING IN QUANTITY
16648
16649     If you publish printed copies (or copies in media that commonly
16650     have printed covers) of the Document, numbering more than 100, and
16651     the Document’s license notice requires Cover Texts, you must
16652     enclose the copies in covers that carry, clearly and legibly, all
16653     these Cover Texts: Front-Cover Texts on the front cover, and
16654     Back-Cover Texts on the back cover.  Both covers must also clearly
16655     and legibly identify you as the publisher of these copies.  The
16656     front cover must present the full title with all words of the title
16657     equally prominent and visible.  You may add other material on the
16658     covers in addition.  Copying with changes limited to the covers, as
16659     long as they preserve the title of the Document and satisfy these
16660     conditions, can be treated as verbatim copying in other respects.
16661
16662     If the required texts for either cover are too voluminous to fit
16663     legibly, you should put the first ones listed (as many as fit
16664     reasonably) on the actual cover, and continue the rest onto
16665     adjacent pages.
16666
16667     If you publish or distribute Opaque copies of the Document
16668     numbering more than 100, you must either include a machine-readable
16669     Transparent copy along with each Opaque copy, or state in or with
16670     each Opaque copy a computer-network location from which the general
16671     network-using public has access to download using public-standard
16672     network protocols a complete Transparent copy of the Document, free
16673     of added material.  If you use the latter option, you must take
16674     reasonably prudent steps, when you begin distribution of Opaque
16675     copies in quantity, to ensure that this Transparent copy will
16676     remain thus accessible at the stated location until at least one
16677     year after the last time you distribute an Opaque copy (directly or
16678     through your agents or retailers) of that edition to the public.
16679
16680     It is requested, but not required, that you contact the authors of
16681     the Document well before redistributing any large number of copies,
16682     to give them a chance to provide you with an updated version of the
16683     Document.
16684
16685  4. MODIFICATIONS
16686
16687     You may copy and distribute a Modified Version of the Document
16688     under the conditions of sections 2 and 3 above, provided that you
16689     release the Modified Version under precisely this License, with the
16690     Modified Version filling the role of the Document, thus licensing
16691     distribution and modification of the Modified Version to whoever
16692     possesses a copy of it.  In addition, you must do these things in
16693     the Modified Version:
16694
16695       A. Use in the Title Page (and on the covers, if any) a title
16696          distinct from that of the Document, and from those of previous
16697          versions (which should, if there were any, be listed in the
16698          History section of the Document).  You may use the same title
16699          as a previous version if the original publisher of that
16700          version gives permission.
16701
16702       B. List on the Title Page, as authors, one or more persons or
16703          entities responsible for authorship of the modifications in
16704          the Modified Version, together with at least five of the
16705          principal authors of the Document (all of its principal
16706          authors, if it has fewer than five), unless they release you
16707          from this requirement.
16708
16709       C. State on the Title page the name of the publisher of the
16710          Modified Version, as the publisher.
16711
16712       D. Preserve all the copyright notices of the Document.
16713
16714       E. Add an appropriate copyright notice for your modifications
16715          adjacent to the other copyright notices.
16716
16717       F. Include, immediately after the copyright notices, a license
16718          notice giving the public permission to use the Modified
16719          Version under the terms of this License, in the form shown in
16720          the Addendum below.
16721
16722       G. Preserve in that license notice the full lists of Invariant
16723          Sections and required Cover Texts given in the Document’s
16724          license notice.
16725
16726       H. Include an unaltered copy of this License.
16727
16728       I. Preserve the section Entitled “History”, Preserve its Title,
16729          and add to it an item stating at least the title, year, new
16730          authors, and publisher of the Modified Version as given on the
16731          Title Page.  If there is no section Entitled “History” in the
16732          Document, create one stating the title, year, authors, and
16733          publisher of the Document as given on its Title Page, then add
16734          an item describing the Modified Version as stated in the
16735          previous sentence.
16736
16737       J. Preserve the network location, if any, given in the Document
16738          for public access to a Transparent copy of the Document, and
16739          likewise the network locations given in the Document for
16740          previous versions it was based on.  These may be placed in the
16741          “History” section.  You may omit a network location for a work
16742          that was published at least four years before the Document
16743          itself, or if the original publisher of the version it refers
16744          to gives permission.
16745
16746       K. For any section Entitled “Acknowledgements” or “Dedications”,
16747          Preserve the Title of the section, and preserve in the section
16748          all the substance and tone of each of the contributor
16749          acknowledgements and/or dedications given therein.
16750
16751       L. Preserve all the Invariant Sections of the Document, unaltered
16752          in their text and in their titles.  Section numbers or the
16753          equivalent are not considered part of the section titles.
16754
16755       M. Delete any section Entitled “Endorsements”.  Such a section
16756          may not be included in the Modified Version.
16757
16758       N. Do not retitle any existing section to be Entitled
16759          “Endorsements” or to conflict in title with any Invariant
16760          Section.
16761
16762       O. Preserve any Warranty Disclaimers.
16763
16764     If the Modified Version includes new front-matter sections or
16765     appendices that qualify as Secondary Sections and contain no
16766     material copied from the Document, you may at your option designate
16767     some or all of these sections as invariant.  To do this, add their
16768     titles to the list of Invariant Sections in the Modified Version’s
16769     license notice.  These titles must be distinct from any other
16770     section titles.
16771
16772     You may add a section Entitled “Endorsements”, provided it contains
16773     nothing but endorsements of your Modified Version by various
16774     parties—for example, statements of peer review or that the text has
16775     been approved by an organization as the authoritative definition of
16776     a standard.
16777
16778     You may add a passage of up to five words as a Front-Cover Text,
16779     and a passage of up to 25 words as a Back-Cover Text, to the end of
16780     the list of Cover Texts in the Modified Version.  Only one passage
16781     of Front-Cover Text and one of Back-Cover Text may be added by (or
16782     through arrangements made by) any one entity.  If the Document
16783     already includes a cover text for the same cover, previously added
16784     by you or by arrangement made by the same entity you are acting on
16785     behalf of, you may not add another; but you may replace the old
16786     one, on explicit permission from the previous publisher that added
16787     the old one.
16788
16789     The author(s) and publisher(s) of the Document do not by this
16790     License give permission to use their names for publicity for or to
16791     assert or imply endorsement of any Modified Version.
16792
16793  5. COMBINING DOCUMENTS
16794
16795     You may combine the Document with other documents released under
16796     this License, under the terms defined in section 4 above for
16797     modified versions, provided that you include in the combination all
16798     of the Invariant Sections of all of the original documents,
16799     unmodified, and list them all as Invariant Sections of your
16800     combined work in its license notice, and that you preserve all
16801     their Warranty Disclaimers.
16802
16803     The combined work need only contain one copy of this License, and
16804     multiple identical Invariant Sections may be replaced with a single
16805     copy.  If there are multiple Invariant Sections with the same name
16806     but different contents, make the title of each such section unique
16807     by adding at the end of it, in parentheses, the name of the
16808     original author or publisher of that section if known, or else a
16809     unique number.  Make the same adjustment to the section titles in
16810     the list of Invariant Sections in the license notice of the
16811     combined work.
16812
16813     In the combination, you must combine any sections Entitled
16814     “History” in the various original documents, forming one section
16815     Entitled “History”; likewise combine any sections Entitled
16816     “Acknowledgements”, and any sections Entitled “Dedications”.  You
16817     must delete all sections Entitled “Endorsements.”
16818
16819  6. COLLECTIONS OF DOCUMENTS
16820
16821     You may make a collection consisting of the Document and other
16822     documents released under this License, and replace the individual
16823     copies of this License in the various documents with a single copy
16824     that is included in the collection, provided that you follow the
16825     rules of this License for verbatim copying of each of the documents
16826     in all other respects.
16827
16828     You may extract a single document from such a collection, and
16829     distribute it individually under this License, provided you insert
16830     a copy of this License into the extracted document, and follow this
16831     License in all other respects regarding verbatim copying of that
16832     document.
16833
16834  7. AGGREGATION WITH INDEPENDENT WORKS
16835
16836     A compilation of the Document or its derivatives with other
16837     separate and independent documents or works, in or on a volume of a
16838     storage or distribution medium, is called an “aggregate” if the
16839     copyright resulting from the compilation is not used to limit the
16840     legal rights of the compilation’s users beyond what the individual
16841     works permit.  When the Document is included in an aggregate, this
16842     License does not apply to the other works in the aggregate which
16843     are not themselves derivative works of the Document.
16844
16845     If the Cover Text requirement of section 3 is applicable to these
16846     copies of the Document, then if the Document is less than one half
16847     of the entire aggregate, the Document’s Cover Texts may be placed
16848     on covers that bracket the Document within the aggregate, or the
16849     electronic equivalent of covers if the Document is in electronic
16850     form.  Otherwise they must appear on printed covers that bracket
16851     the whole aggregate.
16852
16853  8. TRANSLATION
16854
16855     Translation is considered a kind of modification, so you may
16856     distribute translations of the Document under the terms of section
16857     4.  Replacing Invariant Sections with translations requires special
16858     permission from their copyright holders, but you may include
16859     translations of some or all Invariant Sections in addition to the
16860     original versions of these Invariant Sections.  You may include a
16861     translation of this License, and all the license notices in the
16862     Document, and any Warranty Disclaimers, provided that you also
16863     include the original English version of this License and the
16864     original versions of those notices and disclaimers.  In case of a
16865     disagreement between the translation and the original version of
16866     this License or a notice or disclaimer, the original version will
16867     prevail.
16868
16869     If a section in the Document is Entitled “Acknowledgements”,
16870     “Dedications”, or “History”, the requirement (section 4) to
16871     Preserve its Title (section 1) will typically require changing the
16872     actual title.
16873
16874  9. TERMINATION
16875
16876     You may not copy, modify, sublicense, or distribute the Document
16877     except as expressly provided under this License.  Any attempt
16878     otherwise to copy, modify, sublicense, or distribute it is void,
16879     and will automatically terminate your rights under this License.
16880
16881     However, if you cease all violation of this License, then your
16882     license from a particular copyright holder is reinstated (a)
16883     provisionally, unless and until the copyright holder explicitly and
16884     finally terminates your license, and (b) permanently, if the
16885     copyright holder fails to notify you of the violation by some
16886     reasonable means prior to 60 days after the cessation.
16887
16888     Moreover, your license from a particular copyright holder is
16889     reinstated permanently if the copyright holder notifies you of the
16890     violation by some reasonable means, this is the first time you have
16891     received notice of violation of this License (for any work) from
16892     that copyright holder, and you cure the violation prior to 30 days
16893     after your receipt of the notice.
16894
16895     Termination of your rights under this section does not terminate
16896     the licenses of parties who have received copies or rights from you
16897     under this License.  If your rights have been terminated and not
16898     permanently reinstated, receipt of a copy of some or all of the
16899     same material does not give you any rights to use it.
16900
16901  10. FUTURE REVISIONS OF THIS LICENSE
16902
16903     The Free Software Foundation may publish new, revised versions of
16904     the GNU Free Documentation License from time to time.  Such new
16905     versions will be similar in spirit to the present version, but may
16906     differ in detail to address new problems or concerns.  See
16907     <https://www.gnu.org/licenses/>.
16908
16909     Each version of the License is given a distinguishing version
16910     number.  If the Document specifies that a particular numbered
16911     version of this License “or any later version” applies to it, you
16912     have the option of following the terms and conditions either of
16913     that specified version or of any later version that has been
16914     published (not as a draft) by the Free Software Foundation.  If the
16915     Document does not specify a version number of this License, you may
16916     choose any version ever published (not as a draft) by the Free
16917     Software Foundation.  If the Document specifies that a proxy can
16918     decide which future versions of this License can be used, that
16919     proxy’s public statement of acceptance of a version permanently
16920     authorizes you to choose that version for the Document.
16921
16922  11. RELICENSING
16923
16924     “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any
16925     World Wide Web server that publishes copyrightable works and also
16926     provides prominent facilities for anybody to edit those works.  A
16927     public wiki that anybody can edit is an example of such a server.
16928     A “Massive Multiauthor Collaboration” (or “MMC”) contained in the
16929     site means any set of copyrightable works thus published on the MMC
16930     site.
16931
16932     “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0
16933     license published by Creative Commons Corporation, a not-for-profit
16934     corporation with a principal place of business in San Francisco,
16935     California, as well as future copyleft versions of that license
16936     published by that same organization.
16937
16938     “Incorporate” means to publish or republish a Document, in whole or
16939     in part, as part of another Document.
16940
16941     An MMC is “eligible for relicensing” if it is licensed under this
16942     License, and if all works that were first published under this
16943     License somewhere other than this MMC, and subsequently
16944     incorporated in whole or in part into the MMC, (1) had no cover
16945     texts or invariant sections, and (2) were thus incorporated prior
16946     to November 1, 2008.
16947
16948     The operator of an MMC Site may republish an MMC contained in the
16949     site under CC-BY-SA on the same site at any time before August 1,
16950     2009, provided the MMC is eligible for relicensing.
16951
16952ADDENDUM: How to use this License for your documents
16953====================================================
16954
16955To use this License in a document you have written, include a copy of
16956the License in the document and put the following copyright and license
16957notices just after the title page:
16958
16959       Copyright (C)  YEAR  YOUR NAME.
16960       Permission is granted to copy, distribute and/or modify this document
16961       under the terms of the GNU Free Documentation License, Version 1.3
16962       or any later version published by the Free Software Foundation;
16963       with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
16964       Texts.  A copy of the license is included in the section entitled ``GNU
16965       Free Documentation License''.
16966
16967   If you have Invariant Sections, Front-Cover Texts and Back-Cover
16968Texts, replace the “with...Texts.” line with this:
16969
16970         with the Invariant Sections being LIST THEIR TITLES, with
16971         the Front-Cover Texts being LIST, and with the Back-Cover Texts
16972         being LIST.
16973
16974   If you have Invariant Sections without Cover Texts, or some other
16975combination of the three, merge those two alternatives to suit the
16976situation.
16977
16978   If your document contains nontrivial examples of program code, we
16979recommend releasing these examples in parallel under your choice of free
16980software license, such as the GNU General Public License, to permit
16981their use in free software.
16982
16983
16984File: eintr.info,  Node: Index,  Next: About the Author,  Prev: GNU Free Documentation License,  Up: Top
16985
16986Index
16987*****
16988
16989�[index�]
16990* Menu:
16991
16992* % (remainder function):                Compute a Remainder. (line   6)
16993* ' for quoting:                         Run a Program.       (line  13)
16994* (debug) in code:                       debug-on-quit.       (line  13)
16995* * (multiplication):                    defun.               (line 102)
16996* * for read-only buffer:                Read-only buffer.    (line   6)
16997* *scratch* buffer:                      print-elements-of-list.
16998                                                              (line   9)
16999* .emacs file:                           Emacs Initialization.
17000                                                              (line   6)
17001* .emacs file, beginning of:             Beginning init File. (line   6)
17002* / (division):                          Large buffer case.   (line  38)
17003* <= (less than or equal):               Inc Example parts.   (line  47)
17004* > (greater than):                      if in more detail.   (line  31)
17005* Accumulate, type of recursive pattern: Accumulate.          (line   6)
17006* add-hook:                              Text and Auto-fill.  (line  54)
17007* and:                                   kill-new function.   (line 211)
17008* and <1>:                               fwd-para let.        (line  46)
17009* Anonymous function:                    lambda.              (line   6)
17010* apostrophe for quoting:                Run a Program.       (line  13)
17011* append-to-buffer:                      append-to-buffer.    (line   6)
17012* apply:                                 Columns of a graph.  (line 143)
17013* apropos:                               Columns of a graph.  (line  33)
17014* Argument as local variable:            Dec Example altogether.
17015                                                              (line  27)
17016* argument defined:                      Arguments.           (line  16)
17017* argument list defined:                 defun.               (line  60)
17018* Argument, wrong type of:               Wrong Type of Argument.
17019                                                              (line   6)
17020* Arguments:                             Arguments.           (line   6)
17021* Arguments’ data types:                 Data types.          (line   6)
17022* Arguments, variable number of:         Variable Number of Arguments.
17023                                                              (line   6)
17024* Asterisk for read-only buffer:         Read-only buffer.    (line   6)
17025* Auto Fill mode turned on:              Text and Auto-fill.  (line  54)
17026* autoload:                              Autoload.            (line   6)
17027* Automatic mode selection:              Text and Auto-fill.  (line  22)
17028* Axis, print horizontal:                print-X-axis.        (line   6)
17029* Axis, print vertical:                  print-Y-axis.        (line   6)
17030* beginning-of-buffer:                   beginning-of-buffer. (line   6)
17031* bind defined:                          set & setq.          (line   6)
17032* Bindings, key, fixing unpleasant:      Miscellaneous.       (line  88)
17033* body defined:                          defun.               (line  38)
17034* Body of graph:                         Readying a Graph.    (line   6)
17035* Buffer size:                           Buffer Size & Locations.
17036                                                              (line   6)
17037* Buffer, history of word:               Buffer Names.        (line  67)
17038* buffer-file-name:                      Buffer Names.        (line   6)
17039* buffer-menu, bound to key:             Keybindings.         (line  71)
17040* buffer-name:                           Buffer Names.        (line   6)
17041* Bug, most insidious type:              Another Bug.         (line   6)
17042* Building robots:                       Building Robots.     (line   6)
17043* Byte compiling:                        Byte Compiling.      (line   6)
17044* C language primitives:                 Primitive Functions. (line   6)
17045* C, a digression into:                  Digression into C.   (line   6)
17046* call defined:                          Switching Buffers.   (line  55)
17047* cancel-debug-on-entry:                 debug-on-entry.      (line  87)
17048* car, introduced:                       car cdr & cons.      (line   6)
17049* cdr, introduced:                       car cdr & cons.      (line   6)
17050* Changing a function definition:        Change a defun.      (line   6)
17051* Chest of Drawers, metaphor for a symbol: Symbols as Chest.  (line   6)
17052* Clipping text:                         Cutting & Storing Text.
17053                                                              (line   6)
17054* Code installation:                     Permanent Installation.
17055                                                              (line   6)
17056* command defined:                       How to Evaluate.     (line  11)
17057* Comments in Lisp code:                 Change a defun.      (line  22)
17058* Common Lisp:                           Lisp History.        (line  11)
17059* compare-windows:                       Keybindings.         (line  11)
17060* concat:                                Data types.          (line  11)
17061* cond:                                  Recursion with cond. (line   6)
17062* condition-case:                        condition-case.      (line   6)
17063* Conditional ’twixt two versions of Emacs: Simple Extension. (line  37)
17064* Conditional with if:                   if.                  (line   6)
17065* cons, introduced:                      cons.                (line   6)
17066* copy-region-as-kill:                   copy-region-as-kill. (line   6)
17067* copy-to-buffer:                        copy-to-buffer.      (line   6)
17068* Count words recursively:               recursive-count-words.
17069                                                              (line   6)
17070* count-words-example:                   count-words-example. (line   6)
17071* count-words-in-defun:                  count-words-in-defun.
17072                                                              (line  98)
17073* Counting:                              Counting.            (line   6)
17074* Counting words in a defun:             Words in a defun.    (line   6)
17075* Counting words in a defun <1>:         count-words-in-defun.
17076                                                              (line   6)
17077* curly quotes:                          Complete zap-to-char.
17078                                                              (line  43)
17079* current-buffer:                        Getting Buffers.     (line   6)
17080* current-kill:                          current-kill.        (line   6)
17081* curved quotes:                         Complete zap-to-char.
17082                                                              (line  43)
17083* Customizing your .emacs file:          Emacs Initialization.
17084                                                              (line   6)
17085* Cutting and storing text:              Cutting & Storing Text.
17086                                                              (line   6)
17087* Data types:                            Data types.          (line   6)
17088* debug:                                 debug.               (line   6)
17089* debug-on-entry:                        debug-on-entry.      (line   6)
17090* debug-on-quit:                         debug-on-quit.       (line   9)
17091* debugging:                             Debugging.           (line   6)
17092* default.el init file:                  Site-wide Init.      (line   6)
17093* defconst:                              defcustom.           (line 127)
17094* defcustom:                             defcustom.           (line   6)
17095* Deferment in recursion:                No Deferment.        (line   6)
17096* Definition installation:               Install.             (line   6)
17097* Definition writing:                    Writing Defuns.      (line   6)
17098* Definition, how to change:             Change a defun.      (line   6)
17099* defsubst:                              defcustom.           (line 127)
17100* defun:                                 defun.               (line   6)
17101* defvar:                                defvar.              (line   6)
17102* defvar for a user customizable variable: defvar and asterisk.
17103                                                              (line   6)
17104* defvar with an asterisk:               defvar and asterisk. (line   6)
17105* delete-and-extract-region:             Digression into C.   (line   6)
17106* Deleting text:                         Cutting & Storing Text.
17107                                                              (line   6)
17108* describe-function:                     simplified-beginning-of-buffer.
17109                                                              (line  80)
17110* describe-function, introduced:         Finding More.        (line   6)
17111* Digression into C:                     Digression into C.   (line   6)
17112* directory-files:                       Files List.          (line  12)
17113* Division:                              Large buffer case.   (line  38)
17114* dolist:                                dolist.              (line   6)
17115* dotimes:                               dotimes.             (line   6)
17116* Drawers, Chest of, metaphor for a symbol: Symbols as Chest. (line   6)
17117* Duplicated words function:             the-the.             (line   6)
17118* edebug:                                edebug.              (line   6)
17119* Else:                                  else.                (line   6)
17120* Emacs version, choosing:               Simple Extension.    (line  37)
17121* empty list defined:                    Lisp Atoms.          (line  18)
17122* empty string defined:                  Review.              (line 138)
17123* eobp:                                  fwd-para while.      (line  59)
17124* eq:                                    Review.              (line 124)
17125* eq (example of use):                   last-command & this-command.
17126                                                              (line  36)
17127* equal:                                 Review.              (line 124)
17128* Erasing text:                          Cutting & Storing Text.
17129                                                              (line   6)
17130* error:                                 Body of current-kill.
17131                                                              (line  40)
17132* Error for symbol without function:     Void Function.       (line   6)
17133* Error for symbol without value:        Void Variable.       (line   6)
17134* Error message generation:              Making Errors.       (line   6)
17135* evaluate defined:                      Run a Program.       (line   6)
17136* Evaluating inner lists:                Evaluating Inner Lists.
17137                                                              (line   6)
17138* Evaluation:                            Evaluation.          (line   6)
17139* Evaluation practice:                   Practicing Evaluation.
17140                                                              (line   6)
17141* Every, type of recursive pattern:      Every.               (line   6)
17142* Example variable, fill-column:         fill-column Example. (line   6)
17143* expression defined:                    Lisp Atoms.          (line  25)
17144* Falsehood and truth in Emacs Lisp:     Truth & Falsehood.   (line   6)
17145* FDL, GNU Free Documentation License:   GNU Free Documentation License.
17146                                                              (line   6)
17147* files-in-below-directory:              Files List.          (line  25)
17148* fill-column, an example variable:      fill-column Example. (line   6)
17149* filter-buffer-substring:               last-command & this-command.
17150                                                              (line  29)
17151* Find a File:                           Find a File.         (line   6)
17152* Find function documentation:           Finding More.        (line   6)
17153* Find source of function:               Finding More.        (line  13)
17154* Flowers in a field:                    Lisp Lists.          (line  18)
17155* Focusing attention (narrowing):        Narrowing & Widening.
17156                                                              (line   6)
17157* form defined:                          Lisp Atoms.          (line  25)
17158* Formatting convention:                 append save-excursion.
17159                                                              (line  15)
17160* Formatting help:                       Typing Lists.        (line   6)
17161* forward-paragraph:                     forward-paragraph.   (line   6)
17162* forward-sentence:                      forward-sentence.    (line   6)
17163* function defined:                      Making Errors.       (line  48)
17164* function defined <1>:                  Making Errors.       (line  71)
17165* function definition defined:           defun.               (line   6)
17166* Function definition installation:      Install.             (line   6)
17167* Function definition writing:           Writing Defuns.      (line   6)
17168* Function definition, how to change:    Change a defun.      (line   6)
17169* Functions, primitive:                  Primitive Functions. (line   6)
17170* Generate an error message:             Making Errors.       (line   6)
17171* Getting a buffer:                      Getting Buffers.     (line   6)
17172* Global set key:                        Keybindings.         (line  18)
17173* global variable defined:               Determining the Element.
17174                                                              (line  89)
17175* global-set-key:                        Keybindings.         (line  18)
17176* global-unset-key:                      Keybindings.         (line  60)
17177* Graph prototype:                       Readying a Graph.    (line   6)
17178* Graph, printing all:                   Print Whole Graph.   (line   6)
17179* graph-body-print:                      graph-body-print.    (line   6)
17180* graph-body-print Final version.:       The final version.   (line  53)
17181* Handling the kill ring:                Kill Ring.           (line   6)
17182* Help typing lists:                     Typing Lists.        (line   6)
17183* Horizontal axis printing:              print-X-axis.        (line   6)
17184* if:                                    if.                  (line   6)
17185* if-part defined:                       if in more detail.   (line   6)
17186* indent-tabs-mode:                      Indent Tabs Mode.    (line   6)
17187* Indentation for formatting:            append save-excursion.
17188                                                              (line  15)
17189* Initialization file:                   Emacs Initialization.
17190                                                              (line   6)
17191* Initializing a variable:               defvar.              (line   6)
17192* Inner list evaluation:                 Evaluating Inner Lists.
17193                                                              (line   6)
17194* insert-buffer:                         insert-buffer.       (line   6)
17195* insert-buffer, new version body:       New insert-buffer.   (line   6)
17196* insert-buffer-substring:               append-to-buffer overview.
17197                                                              (line   6)
17198* Insidious type of bug:                 Another Bug.         (line   6)
17199* Install a Function Definition:         Install.             (line   6)
17200* Install code permanently:              Permanent Installation.
17201                                                              (line   6)
17202* interactive:                           Interactive.         (line   6)
17203* interactive function defined:          How to Evaluate.     (line  11)
17204* Interactive functions:                 Interactive.         (line   6)
17205* Interactive options:                   Interactive Options. (line   6)
17206* interactive, example use of:           insert-buffer interactive.
17207                                                              (line   6)
17208* Interpreter, Lisp, explained:          Run a Program.       (line  39)
17209* Interpreter, what it does:             Lisp Interpreter.    (line   6)
17210* Keep, type of recursive pattern:       Keep.                (line   6)
17211* Key bindings, fixing:                  Miscellaneous.       (line  88)
17212* Key setting globally:                  Keybindings.         (line  18)
17213* Key unbinding:                         Keybindings.         (line  60)
17214* Keymaps:                               Keymaps.             (line   6)
17215* Keyword:                               Optional Arguments.  (line  11)
17216* Kill ring handling:                    Kill Ring.           (line   6)
17217* Kill ring overview:                    Kill Ring Overview.  (line   6)
17218* kill-append:                           kill-append function.
17219                                                              (line   6)
17220* kill-new:                              kill-new function.   (line   6)
17221* kill-region:                           kill-region.         (line   6)
17222* Killing text:                          Cutting & Storing Text.
17223                                                              (line   6)
17224* lambda:                                lambda.              (line   6)
17225* length:                                length.              (line   6)
17226* lengths-list-file:                     lengths-list-file.   (line  11)
17227* lengths-list-many-files:               lengths-list-many-files.
17228                                                              (line  32)
17229* let:                                   let.                 (line   6)
17230* let expression sample:                 Sample let Expression.
17231                                                              (line   6)
17232* let expression, parts of:              Parts of let Expression.
17233                                                              (line   6)
17234* let variables uninitialized:           Uninitialized let Variables.
17235                                                              (line   6)
17236* let*:                                  fwd-para let.        (line  10)
17237* Library, as term for “file”:           Finding More.        (line  41)
17238* line-to-top-of-window:                 Simple Extension.    (line   6)
17239* Lisp Atoms:                            Lisp Atoms.          (line   6)
17240* Lisp history:                          Lisp History.        (line   6)
17241* Lisp interpreter, explained:           Run a Program.       (line  39)
17242* Lisp interpreter, what it does:        Lisp Interpreter.    (line   6)
17243* Lisp Lists:                            Lisp Lists.          (line   6)
17244* Lisp macro:                            Lisp macro.          (line   6)
17245* list-buffers, rebound:                 Keybindings.         (line  71)
17246* Lists in a computer:                   List Implementation. (line   6)
17247* load-library:                          Loading Files.       (line  53)
17248* load-path:                             Loading Files.       (line  37)
17249* Loading files:                         Loading Files.       (line   6)
17250* local variable defined:                Prevent confusion.   (line   6)
17251* Local variables list, per-buffer,:     Text and Auto-fill.  (line  22)
17252* Location of point:                     Buffer Size & Locations.
17253                                                              (line   6)
17254* looking-at:                            fwd-para while.      (line  81)
17255* Loops:                                 while.               (line   6)
17256* Loops and recursion:                   Loops & Recursion.   (line   6)
17257* Maclisp:                               Lisp History.        (line  11)
17258* Macro, lisp:                           Lisp macro.          (line   6)
17259* Mail aliases:                          Mail Aliases.        (line  14)
17260* make-string:                           Y Axis Element.      (line  75)
17261* mapcar:                                mapcar.              (line   6)
17262* mark:                                  save-excursion.      (line   6)
17263* mark-whole-buffer:                     mark-whole-buffer.   (line   6)
17264* match-beginning:                       fwd-para while.      (line 159)
17265* max:                                   Columns of a graph.  (line 131)
17266* message:                               message.             (line   6)
17267* min:                                   Columns of a graph.  (line 131)
17268* Mode line format:                      Mode Line.           (line   6)
17269* Mode selection, automatic:             Text and Auto-fill.  (line  22)
17270* mode-line-format:                      Mode Line.           (line   6)
17271* Motion by sentence and paragraph:      Regexp Search.       (line   6)
17272* Narrowing:                             Narrowing & Widening.
17273                                                              (line   6)
17274* narrowing defined:                     Buffer Size & Locations.
17275                                                              (line  42)
17276* new version body for insert-buffer:    New insert-buffer.   (line   6)
17277* nil:                                   Truth & Falsehood.   (line   6)
17278* nil, history of word:                  Buffer Names.        (line  42)
17279* No deferment solution:                 No deferment solution.
17280                                                              (line   6)
17281* nreverse:                              Counting function definitions.
17282                                                              (line 100)
17283* nth:                                   nth.                 (line   6)
17284* nthcdr:                                nthcdr.              (line   6)
17285* nthcdr <1>:                            copy-region-as-kill. (line   6)
17286* nthcdr, example:                       kill-new function.   (line 149)
17287* number-to-string:                      Y Axis Element.      (line  13)
17288* occur:                                 Keybindings.         (line  54)
17289* optional:                              Optional Arguments.  (line  11)
17290* Optional arguments:                    Optional Arguments.  (line  11)
17291* Options for interactive:               Interactive Options. (line   6)
17292* or:                                    Insert or.           (line  13)
17293* other-buffer:                          Getting Buffers.     (line   6)
17294* Paragraphs, movement by:               Regexp Search.       (line   6)
17295* Parts of a Recursive Definition:       Recursive Definition Parts.
17296                                                              (line   6)
17297* Parts of let expression:               Parts of let Expression.
17298                                                              (line   6)
17299* Passing information to functions:      Arguments.           (line   6)
17300* Pasting text:                          Yanking.             (line   6)
17301* Patterns, searching for:               Regexp Search.       (line   6)
17302* Per-buffer, local variables list:      Text and Auto-fill.  (line  22)
17303* Permanent code installation:           Permanent Installation.
17304                                                              (line   6)
17305* point:                                 save-excursion.      (line   6)
17306* Point and buffer preservation:         save-excursion.      (line   6)
17307* point defined:                         Buffer Size & Locations.
17308                                                              (line  19)
17309* Point location:                        Buffer Size & Locations.
17310                                                              (line   6)
17311* Practicing evaluation:                 Practicing Evaluation.
17312                                                              (line   6)
17313* Preserving point and buffer:           save-excursion.      (line   6)
17314* Primitive functions:                   Primitive Functions. (line   6)
17315* Primitives written in C:               Primitive Functions. (line   6)
17316* Print horizontal axis:                 print-X-axis.        (line   6)
17317* Print vertical axis:                   print-Y-axis.        (line   6)
17318* print-elements-of-list:                print-elements-of-list.
17319                                                              (line   6)
17320* print-elements-recursively:            Recursion with list. (line  23)
17321* print-graph Final version.:            The final version.   (line  75)
17322* print-graph varlist:                   print-graph Varlist. (line   6)
17323* print-X-axis:                          X Axis Tic Marks.    (line 147)
17324* print-X-axis-numbered-line:            X Axis Tic Marks.    (line 117)
17325* print-X-axis-tic-line:                 X Axis Tic Marks.    (line  83)
17326* print-Y-axis:                          print-Y-axis Penultimate.
17327                                                              (line   9)
17328* Printing the whole graph:              Print Whole Graph.   (line   6)
17329* progn:                                 progn.               (line   6)
17330* Program, running one:                  Run a Program.       (line   6)
17331* Properties, in mode line example:      Mode Line.           (line  64)
17332* Properties, mention of buffer-substring-no-properties: narrow Exercise.
17333                                                              (line  13)
17334* Prototype graph:                       Readying a Graph.    (line   6)
17335* push, example:                         kill-new function.   (line 118)
17336* quote:                                 Run a Program.       (line  13)
17337* quoting using apostrophe:              Run a Program.       (line  13)
17338* re-search-forward:                     re-search-forward.   (line   6)
17339* Read-only buffer:                      Read-only buffer.    (line   6)
17340* Readying a graph:                      Readying a Graph.    (line   6)
17341* Rebinding keys:                        Keymaps.             (line   6)
17342* Recursion:                             Recursion.           (line   6)
17343* Recursion and loops:                   Loops & Recursion.   (line   6)
17344* Recursion without Deferments:          No Deferment.        (line   6)
17345* Recursive Definition Parts:            Recursive Definition Parts.
17346                                                              (line   6)
17347* Recursive pattern - accumulate:        Accumulate.          (line   6)
17348* Recursive pattern - every:             Every.               (line   6)
17349* Recursive pattern - keep:              Keep.                (line   6)
17350* Recursive Patterns:                    Recursive Patterns.  (line   6)
17351* recursive-count-words:                 recursive-count-words.
17352                                                              (line 258)
17353* recursive-graph-body-print:            recursive-graph-body-print.
17354                                                              (line   6)
17355* recursive-lengths-list-many-files:     Several files recursively.
17356                                                              (line  17)
17357* Recursively counting words:            recursive-count-words.
17358                                                              (line   6)
17359* regexp-quote:                          fwd-para let.        (line  74)
17360* Region, what it is:                    save-excursion.      (line   6)
17361* Regular expression searches:           Regexp Search.       (line   6)
17362* Regular expressions for word counting: Counting Words.      (line   6)
17363* Remainder function, %:                 Compute a Remainder. (line   6)
17364* Repetition (loops):                    Loops & Recursion.   (line   6)
17365* Repetition for word counting:          Counting Words.      (line   6)
17366* Retrieving text:                       Yanking.             (line   6)
17367* returned value explained:              How the Interpreter Acts.
17368                                                              (line   6)
17369* reverse:                               Counting function definitions.
17370                                                              (line 115)
17371* Ring, making a list like a:            Kill Ring.           (line   6)
17372* ring.el file:                          ring file.           (line   6)
17373* Robots, building:                      Building Robots.     (line   6)
17374* Run a program:                         Run a Program.       (line   6)
17375* Sample let expression:                 Sample let Expression.
17376                                                              (line   6)
17377* save-excursion:                        save-excursion.      (line   6)
17378* save-restriction:                      save-restriction.    (line   6)
17379* search-forward:                        search-forward.      (line   6)
17380* Searches, illustrating:                Regexp Search.       (line   6)
17381* sentence-end:                          sentence-end.        (line   6)
17382* Sentences, movement by:                Regexp Search.       (line   6)
17383* set:                                   Using set.           (line   6)
17384* set-buffer:                            Switching Buffers.   (line   6)
17385* set-variable:                          defvar and asterisk. (line  22)
17386* setcar:                                setcar.              (line   6)
17387* setcdr:                                setcdr.              (line   6)
17388* setcdr, example:                       kill-new function.   (line 153)
17389* setq:                                  Using setq.          (line   6)
17390* Setting a key globally:                Keybindings.         (line  18)
17391* Setting value of variable:             set & setq.          (line   6)
17392* side effect defined:                   How the Interpreter Acts.
17393                                                              (line  15)
17394* Simple extension in .emacs file:       Simple Extension.    (line   6)
17395* simplified-beginning-of-buffer:        simplified-beginning-of-buffer.
17396                                                              (line   6)
17397* site-init.el init file:                Site-wide Init.      (line   6)
17398* site-load.el init file:                Site-wide Init.      (line   6)
17399* Size of buffer:                        Buffer Size & Locations.
17400                                                              (line   6)
17401* Solution without deferment:            No deferment solution.
17402                                                              (line   6)
17403* sort:                                  Sorting.             (line   6)
17404* Source level debugger:                 edebug.              (line   6)
17405* Special form:                          Complications.       (line  12)
17406* Storing and cutting text:              Cutting & Storing Text.
17407                                                              (line   6)
17408* string defined:                        Lisp Atoms.          (line  64)
17409* substring:                             Data types.          (line  20)
17410* switch-to-buffer:                      Switching Buffers.   (line   6)
17411* Switching to a buffer:                 Switching Buffers.   (line   6)
17412* Symbol names:                          Names & Definitions. (line   6)
17413* Symbol without function error:         Void Function.       (line   6)
17414* Symbol without value error:            Void Variable.       (line   6)
17415* Symbolic expressions, introduced:      Lisp Atoms.          (line  25)
17416* Symbols as a Chest of Drawers:         Symbols as Chest.    (line   6)
17417* Syntax categories and tables:          Syntax.              (line   6)
17418* Tabs, preventing:                      Indent Tabs Mode.    (line   6)
17419* Text between double quotation marks:   Lisp Atoms.          (line  60)
17420* Text Mode turned on:                   Text and Auto-fill.  (line  39)
17421* Text retrieval:                        Yanking.             (line   6)
17422* the-the:                               the-the.             (line   6)
17423* then-part defined:                     if in more detail.   (line   6)
17424* top-of-ranges:                         Counting function definitions.
17425                                                              (line  20)
17426* triangle-bugged:                       debug.               (line  14)
17427* triangle-recursively:                  Recursive triangle function.
17428                                                              (line   6)
17429* Truth and falsehood in Emacs Lisp:     Truth & Falsehood.   (line   6)
17430* Types of data:                         Data types.          (line   6)
17431* Unbinding key:                         Keybindings.         (line  60)
17432* Uninitialized let variables:           Uninitialized let Variables.
17433                                                              (line   6)
17434* Variable initialization:               defvar.              (line   6)
17435* Variable number of arguments:          Variable Number of Arguments.
17436                                                              (line   6)
17437* Variable, example of, fill-column:     fill-column Example. (line   6)
17438* variable, global, defined:             Determining the Element.
17439                                                              (line  89)
17440* variable, local, defined:              Prevent confusion.   (line   6)
17441* Variable, setting value:               set & setq.          (line   6)
17442* Variables:                             Variables.           (line   6)
17443* varlist defined:                       Parts of let Expression.
17444                                                              (line   6)
17445* Version of Emacs, choosing:            Simple Extension.    (line  37)
17446* Vertical axis printing:                print-Y-axis.        (line   6)
17447* what-line:                             what-line.           (line   6)
17448* while:                                 while.               (line   6)
17449* Whitespace in lists:                   Whitespace in Lists. (line   6)
17450* Whole graph printing:                  Print Whole Graph.   (line   6)
17451* Widening:                              Narrowing & Widening.
17452                                                              (line   6)
17453* Widening, example of:                  what-line.           (line   6)
17454* Word counting in a defun:              Words in a defun.    (line   6)
17455* Words and symbols in defun:            Words and Symbols.   (line   6)
17456* Words, counted recursively:            recursive-count-words.
17457                                                              (line   6)
17458* Words, duplicated:                     the-the.             (line   6)
17459* Writing a function definition:         Writing Defuns.      (line   6)
17460* Wrong type of argument:                Wrong Type of Argument.
17461                                                              (line   6)
17462* X axis printing:                       print-X-axis.        (line   6)
17463* X-axis-element:                        X Axis Tic Marks.    (line 106)
17464* Y axis printing:                       print-Y-axis.        (line   6)
17465* Y-axis-column:                         Y-axis-column.       (line  10)
17466* Y-axis-column Final version.:          The final version.   (line  15)
17467* Y-axis-label-spacing:                  Compute a Remainder. (line  79)
17468* Y-axis-tic:                            Y Axis Element.      (line  33)
17469* yank:                                  Yanking.             (line   6)
17470* yank <1>:                              yank.                (line   6)
17471* yank-pop:                              yank-pop.            (line   6)
17472* zap-to-char:                           zap-to-char.         (line   6)
17473* zerop:                                 Body of current-kill.
17474                                                              (line  40)
17475
17476
17477File: eintr.info,  Node: About the Author,  Prev: Index,  Up: Top
17478
17479About the Author
17480****************
17481
17482     Robert J. Chassell (1946–2017) started working with GNU Emacs in
17483     1985.  He wrote and edited, taught Emacs and Emacs Lisp, and spoke
17484     throughout the world on software freedom.  Chassell was a founding
17485     Director and Treasurer of the Free Software Foundation, Inc.  He
17486     was co-author of the ‘Texinfo’ manual, and edited more than a dozen
17487     other books.  He graduated from Cambridge University, in England.
17488     He had an abiding interest in social and economic history and flew
17489     his own airplane.
17490
17491     "Goodbye to Bob Chassell"
17492     (https://www.fsf.org/blogs/community/goodbye-to-bob-chassell)
17493
17494
17495
17496Tag Table:
17497Node: Top1516
17498Node: Preface20935
17499Node: Why22234
17500Node: On Reading this Text22867
17501Node: Who You Are25071
17502Node: Lisp History27805
17503Node: Note for Novices28568
17504Node: Thank You31122
17505Node: List Processing31680
17506Ref: List Processing-Footnote-133060
17507Node: Lisp Lists33204
17508Node: Numbers Lists34082
17509Node: Lisp Atoms35160
17510Node: Whitespace in Lists38937
17511Node: Typing Lists40214
17512Node: Run a Program41310
17513Ref: Run a Program-Footnote-143801
17514Node: Making Errors43947
17515Node: Names & Definitions48995
17516Node: Lisp Interpreter50891
17517Node: Complications52056
17518Node: Byte Compiling54258
17519Node: Evaluation55336
17520Node: How the Interpreter Acts55971
17521Node: Evaluating Inner Lists57209
17522Node: Variables59758
17523Node: fill-column Example61291
17524Node: Void Function62793
17525Node: Void Variable64012
17526Node: Arguments65919
17527Ref: Arguments-Footnote-167593
17528Node: Data types68432
17529Node: Args as Variable or List70542
17530Node: Variable Number of Arguments72134
17531Node: Wrong Type of Argument72984
17532Ref: Wrong Type of Argument-Footnote-176592
17533Node: message76670
17534Ref: message-Footnote-180651
17535Node: set & setq80837
17536Node: Using set81573
17537Node: Using setq83902
17538Node: Counting86134
17539Node: Summary88163
17540Node: Error Message Exercises89967
17541Node: Practicing Evaluation90477
17542Node: How to Evaluate91648
17543Node: Buffer Names93147
17544Node: Getting Buffers98998
17545Ref: Getting Buffers-Footnote-1101566
17546Node: Switching Buffers101791
17547Ref: Switching Buffers-Footnote-1105144
17548Ref: Switching Buffers-Footnote-2105430
17549Node: Buffer Size & Locations106127
17550Node: Evaluation Exercise108289
17551Node: Writing Defuns108565
17552Node: Primitive Functions109901
17553Node: defun111062
17554Node: Install117552
17555Node: Effect of installation118903
17556Node: Change a defun119717
17557Node: Interactive121422
17558Node: Interactive multiply-by-seven122492
17559Node: multiply-by-seven in detail124363
17560Node: Interactive Options127098
17561Node: Permanent Installation130296
17562Node: let132418
17563Node: Prevent confusion133730
17564Node: Parts of let Expression135769
17565Node: Sample let Expression137373
17566Ref: Sample let Expression-Footnote-1139195
17567Node: Uninitialized let Variables139454
17568Node: if141079
17569Node: if in more detail141910
17570Node: type-of-animal in detail144725
17571Node: else147309
17572Node: Truth & Falsehood150209
17573Node: nil explained151153
17574Node: save-excursion153237
17575Node: Point and mark153945
17576Node: Template for save-excursion156967
17577Node: Review158228
17578Node: defun Exercises166047
17579Node: Buffer Walk Through166475
17580Node: Finding More167581
17581Ref: Finding More-Footnote-1170487
17582Node: simplified-beginning-of-buffer170679
17583Node: mark-whole-buffer175174
17584Node: mark-whole-buffer overview175988
17585Node: Body of mark-whole-buffer177359
17586Node: append-to-buffer180477
17587Node: append-to-buffer overview181166
17588Node: append interactive183892
17589Node: append-to-buffer body186365
17590Node: append save-excursion188517
17591Node: Buffer Related Review193552
17592Node: Buffer Exercises195565
17593Node: More Complex196042
17594Node: copy-to-buffer196974
17595Node: insert-buffer199648
17596Node: insert-buffer code200945
17597Node: insert-buffer interactive201934
17598Node: Read-only buffer202456
17599Node: b for interactive203044
17600Node: insert-buffer body204199
17601Node: if & or205401
17602Node: Insert or208441
17603Node: Insert let210778
17604Node: New insert-buffer214601
17605Node: beginning-of-buffer215801
17606Node: Optional Arguments217376
17607Node: beginning-of-buffer opt arg220748
17608Node: Disentangle beginning-of-buffer221644
17609Node: Large buffer case222890
17610Node: Small buffer case225412
17611Node: beginning-of-buffer complete227045
17612Node: Second Buffer Related Review230064
17613Node: optional Exercise231763
17614Node: Narrowing & Widening232235
17615Node: Narrowing advantages232844
17616Node: save-restriction234709
17617Node: what-line236685
17618Node: narrow Exercise240866
17619Node: car cdr & cons241880
17620Node: Strange Names242925
17621Node: car & cdr243940
17622Node: cons248314
17623Node: Build a list249285
17624Ref: Build a list-Footnote-1250829
17625Node: length251013
17626Node: nthcdr252537
17627Node: nth255434
17628Node: setcar256810
17629Node: setcdr259601
17630Node: cons Exercise261135
17631Node: Cutting & Storing Text261508
17632Node: Storing Text262812
17633Node: zap-to-char264832
17634Node: Complete zap-to-char265431
17635Node: zap-to-char interactive268121
17636Node: zap-to-char body269624
17637Node: search-forward271185
17638Node: progn274236
17639Node: Summing up zap-to-char275970
17640Node: kill-region277123
17641Node: Complete kill-region278094
17642Node: condition-case282316
17643Node: Lisp macro284887
17644Node: copy-region-as-kill287287
17645Node: Complete copy-region-as-kill288192
17646Node: copy-region-as-kill body290997
17647Node: last-command & this-command291996
17648Node: kill-append function294293
17649Node: kill-new function298457
17650Node: Digression into C309053
17651Node: defvar314437
17652Node: See variable current value315983
17653Node: defvar and asterisk317891
17654Node: cons & search-fwd Review319733
17655Node: search Exercises322765
17656Node: List Implementation323512
17657Node: Lists diagrammed324597
17658Node: Symbols as Chest330705
17659Node: List Exercise332709
17660Node: Yanking333062
17661Node: Kill Ring Overview334372
17662Node: kill-ring-yank-pointer336068
17663Node: yank nthcdr Exercises338491
17664Node: Loops & Recursion339235
17665Ref: Loops & Recursion-Footnote-1340333
17666Node: while340847
17667Node: Looping with while342214
17668Node: Loop Example344010
17669Node: print-elements-of-list347450
17670Node: Incrementing Loop350014
17671Node: Incrementing Loop Details350577
17672Node: Incrementing Example351963
17673Node: Inc Example parts354332
17674Node: Inc Example altogether358325
17675Node: Decrementing Loop361884
17676Node: Decrementing Example363344
17677Node: Dec Example parts364812
17678Node: Dec Example altogether366843
17679Node: dolist dotimes369072
17680Node: dolist369843
17681Node: dotimes373019
17682Node: Recursion374519
17683Node: Building Robots375616
17684Node: Recursive Definition Parts377316
17685Node: Recursion with list379742
17686Node: Recursive triangle function383323
17687Node: Recursive Example arg of 1 or 2384609
17688Node: Recursive Example arg of 3 or 4386873
17689Node: Recursion with cond389905
17690Node: Recursive Patterns392281
17691Node: Every392683
17692Node: Accumulate395126
17693Node: Keep396395
17694Node: No Deferment398283
17695Node: No deferment solution400982
17696Ref: No deferment solution-Footnote-1404943
17697Ref: No deferment solution-Footnote-2405049
17698Node: Looping exercise405564
17699Node: Regexp Search406788
17700Node: sentence-end408699
17701Node: re-search-forward412602
17702Node: forward-sentence415134
17703Node: Complete forward-sentence415854
17704Node: fwd-sentence while loops419394
17705Node: fwd-sentence re-search423029
17706Node: forward-paragraph425185
17707Node: forward-paragraph in brief426934
17708Node: fwd-para let428389
17709Node: fwd-para while433937
17710Node: Regexp Review442346
17711Node: re-search Exercises444751
17712Node: Counting Words445523
17713Node: Why Count Words446161
17714Node: count-words-example447189
17715Node: Design count-words-example448435
17716Node: Whitespace Bug455055
17717Node: recursive-count-words464637
17718Node: Counting Exercise476716
17719Node: Words in a defun477085
17720Node: Divide and Conquer478671
17721Node: Words and Symbols479888
17722Node: Syntax481937
17723Node: count-words-in-defun485553
17724Node: Several defuns491732
17725Node: Find a File494105
17726Node: lengths-list-file496711
17727Node: Several files501971
17728Node: lengths-list-many-files502680
17729Node: append505466
17730Node: Several files recursively506088
17731Node: Prepare the data508906
17732Node: Data for Display in Detail509952
17733Node: Sorting510866
17734Node: Files List512524
17735Node: Counting function definitions520011
17736Node: Readying a Graph529330
17737Node: Columns of a graph530499
17738Node: graph-body-print544137
17739Node: recursive-graph-body-print548918
17740Node: Printed Axes551584
17741Node: Line Graph Exercise552308
17742Node: Emacs Initialization552490
17743Node: Default Configuration553875
17744Ref: Default Configuration-Footnote-1555851
17745Node: Site-wide Init556167
17746Node: defcustom558213
17747Node: Beginning init File564081
17748Node: Text and Auto-fill566448
17749Node: Mail Aliases570355
17750Node: Indent Tabs Mode571268
17751Node: Keybindings572195
17752Node: Keymaps575868
17753Node: Loading Files578140
17754Node: Autoload581461
17755Node: Simple Extension584329
17756Ref: Simple Extension-Footnote-1586962
17757Node: X11 Colors587227
17758Ref: X11 Colors-Footnote-1589025
17759Node: Miscellaneous589179
17760Node: Mode Line593402
17761Node: Debugging598948
17762Node: debug599765
17763Node: debug-on-entry602962
17764Node: debug-on-quit606566
17765Node: edebug607589
17766Node: Debugging Exercises611701
17767Node: Conclusion613452
17768Node: the-the618807
17769Node: Kill Ring621601
17770Node: What the Kill Ring Does622313
17771Node: current-kill623827
17772Node: Code for current-kill624472
17773Node: Understanding current-kill627293
17774Node: Body of current-kill628033
17775Node: Digression concerning error631167
17776Node: Determining the Element632358
17777Node: yank636063
17778Node: yank-pop639268
17779Node: ring file641787
17780Node: Full Graph642145
17781Node: Labeled Example642917
17782Node: print-graph Varlist644890
17783Node: print-Y-axis646589
17784Node: print-Y-axis in Detail647414
17785Node: Height of label648209
17786Node: Compute a Remainder650213
17787Node: Y Axis Element654066
17788Node: Y-axis-column657819
17789Node: print-Y-axis Penultimate659420
17790Node: print-X-axis661389
17791Node: Similarities differences662636
17792Node: X Axis Tic Marks663455
17793Node: Print Whole Graph670473
17794Node: The final version671500
17795Node: Test print-graph675734
17796Node: Graphing words in defuns677383
17797Node: lambda679971
17798Node: mapcar681619
17799Node: Another Bug683656
17800Node: Final printed graph689156
17801Node: Free Software and Free Manuals690076
17802Node: GNU Free Documentation License696354
17803Node: Index721723
17804Node: About the Author756608
17805
17806End Tag Table
17807
17808
17809Local Variables:
17810coding: utf-8
17811End:
17812