aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRobert J. Chassell2002-09-01 18:54:14 +0000
committerRobert J. Chassell2002-09-01 18:54:14 +0000
commit3d64fcfa3599c5ac69e7055b911e9dc57d4d3e14 (patch)
tree7af1ffc0bb170b79ee43d3ef323166d5ec57502a
parent4c6bc877d6a724d4b395faa076286789ee40df77 (diff)
downloademacs-3d64fcfa3599c5ac69e7055b911e9dc57d4d3e14.tar.gz
emacs-3d64fcfa3599c5ac69e7055b911e9dc57d4d3e14.zip
Remove emacs-lisp-intro.txt erroneously installed
-rw-r--r--lispintro/emacs-lisp-intro.txt16197
1 files changed, 0 insertions, 16197 deletions
diff --git a/lispintro/emacs-lisp-intro.txt b/lispintro/emacs-lisp-intro.txt
deleted file mode 100644
index 345390cfddb..00000000000
--- a/lispintro/emacs-lisp-intro.txt
+++ /dev/null
@@ -1,16197 +0,0 @@
1START-INFO-DIR-ENTRY
2* Emacs Lisp Intro: (eintr).
3 A simple introduction to Emacs Lisp programming.
4END-INFO-DIR-ENTRY
5
6Short Contents
7**************
8
9An Introduction to Programming in Emacs Lisp
10Preface
11List Processing
12Practicing Evaluation
13How To Write Function Definitions
14A Few Buffer-Related Functions
15A Few More Complex Functions
16Narrowing and Widening
17`car', `cdr', `cons': Fundamental Functions
18Cutting and Storing Text
19How Lists are Implemented
20Yanking Text Back
21Loops and Recursion
22Regular Expression Searches
23Counting: Repetition and Regexps
24Counting Words in a `defun'
25Readying a Graph
26Your `.emacs' File
27Debugging
28Conclusion
29The `the-the' Function
30Handling the Kill Ring
31A Graph with Labelled Axes
32GNU Free Documentation License
33Index
34About the Author
35
36
37Table of Contents
38*****************
39
40
41An Introduction to Programming in Emacs Lisp
42
43Preface
44 Why Study Emacs Lisp?
45 On Reading this Text
46 For Whom This is Written
47 Lisp History
48 A Note for Novices
49 Thank You
50
51List Processing
52 Lisp Lists
53 Numbers, Lists inside of Lists
54 Lisp Atoms
55 Whitespace in Lists
56 GNU Emacs Helps You Type Lists
57 Run a Program
58 Generate an Error Message
59 Symbol Names and Function Definitions
60 The Lisp Interpreter
61 Complications
62 Byte Compiling
63 Evaluation
64 Evaluating Inner Lists
65 Variables
66 `fill-column', an Example Variable
67 Error Message for a Symbol Without a Function
68 Error Message for a Symbol Without a Value
69 Arguments
70 Arguments' Data Types
71 An Argument as the Value of a Variable or List
72 Variable Number of Arguments
73 Using the Wrong Type Object as an Argument
74 The `message' Function
75 Setting the Value of a Variable
76 Using `set'
77 Using `setq'
78 Counting
79 Summary
80 Exercises
81
82Practicing Evaluation
83 How to Evaluate
84 Buffer Names
85 Getting Buffers
86 Switching Buffers
87 Buffer Size and the Location of Point
88 Exercise
89
90How To Write Function Definitions
91 An Aside about Primitive Functions
92 The `defun' Special Form
93 Install a Function Definition
94 The effect of installation
95 Change a Function Definition
96 Make a Function Interactive
97 An Interactive `multiply-by-seven', An Overview
98 An Interactive `multiply-by-seven'
99 Different Options for `interactive'
100 Install Code Permanently
101 `let'
102 `let' Prevents Confusion
103 The Parts of a `let' Expression
104 Sample `let' Expression
105 Uninitialized Variables in a `let' Statement
106 The `if' Special Form
107 `if' in more detail
108 The `type-of-animal' Function in Detail
109 If-then-else Expressions
110 Truth and Falsehood in Emacs Lisp
111 An explanation of `nil'
112 `save-excursion'
113 Point and Mark
114 Template for a `save-excursion' Expression
115 Review
116 Exercises
117
118A Few Buffer-Related Functions
119 Finding More Information
120 A Simplified `beginning-of-buffer' Definition
121 The Definition of `mark-whole-buffer'
122 An overview of `mark-whole-buffer'
123 Body of `mark-whole-buffer'
124 The Definition of `append-to-buffer'
125 An Overview of `append-to-buffer'
126 The `append-to-buffer' Interactive Expression
127 The Body of `append-to-buffer'
128 `save-excursion' in `append-to-buffer'
129 Review
130 Exercises
131
132A Few More Complex Functions
133 The Definition of `copy-to-buffer'
134 The Definition of `insert-buffer'
135 The Code for `insert-buffer'
136 The Interactive Expression in `insert-buffer'
137 A Read-only Buffer
138 `b' in an Interactive Expression
139 The Body of the `insert-buffer' Function
140 `insert-buffer' With an `if' Instead of an `or'
141 The `or' in the Body
142 The `let' Expression in `insert-buffer'
143 Complete Definition of `beginning-of-buffer'
144 Optional Arguments
145 `beginning-of-buffer' with an Argument
146 Disentangle `beginning-of-buffer'
147 What happens in a large buffer
148 What happens in a small buffer
149 The Complete `beginning-of-buffer'
150 Review
151 `optional' Argument Exercise
152
153Narrowing and Widening
154 The Advantages of Narrowing
155 The `save-restriction' Special Form
156 `what-line'
157 Exercise with Narrowing
158
159`car', `cdr', `cons': Fundamental Functions
160 Strange Names
161 `car' and `cdr'
162 `cons'
163 Build a list
164 Find the Length of a List: `length'
165 `nthcdr'
166 `nth'
167 `setcar'
168 `setcdr'
169 Exercise
170
171Cutting and Storing Text
172 Storing Text in a List
173 `zap-to-char'
174 The Complete `zap-to-char' Implementation
175 The `interactive' Expression
176 The Body of `zap-to-char'
177 The `search-forward' Function
178 The `progn' Special Form
179 Summing up `zap-to-char'
180 `kill-region'
181 The Complete `kill-region' Definition
182 `condition-case'
183 `delete-and-extract-region'
184 Digression into C
185 Initializing a Variable with `defvar'
186 Seeing the Current Value of a Variable
187 `defvar' and an asterisk
188 `copy-region-as-kill'
189 The complete `copy-region-as-kill' function definition
190 The Body of `copy-region-as-kill'
191 `last-command' and `this-command'
192 The `kill-append' function
193 The `kill-new' function
194 Review
195 Searching Exercises
196
197How Lists are Implemented
198 Lists diagrammed
199 Symbols as a Chest of Drawers
200 Exercise
201
202Yanking Text Back
203 Kill Ring Overview
204 The `kill-ring-yank-pointer' Variable
205 Exercises with `yank' and `nthcdr'
206
207Loops and Recursion
208 `while'
209 Looping with `while'
210 A `while' Loop and a List
211 An Example: `print-elements-of-list'
212 A Loop with an Incrementing Counter
213 Example with incrementing counter
214 The parts of the function definition
215 Putting the function definition together
216 Loop with a Decrementing Counter
217 Example with decrementing counter
218 The parts of the function definition
219 Putting the function definition together
220 Save your time: `dolist' and `dotimes'
221 The `dolist' Macro
222 The `dotimes' Macro
223 Recursion
224 Building Robots: Extending the Metaphor
225 The Parts of a Recursive Definition
226 Recursion with a List
227 Recursion in Place of a Counter
228 An argument of 1 or 2
229 An argument of 3 or 4
230 Recursion Example Using `cond'
231 Recursive Patterns
232 Recursive Pattern: _every_
233 Recursive Pattern: _accumulate_
234 Recursive Pattern: _keep_
235 Recursion without Deferments
236 No Deferment Solution
237 Looping Exercise
238
239Regular Expression Searches
240 The Regular Expression for `sentence-end'
241 The `re-search-forward' Function
242 `forward-sentence'
243 Complete `forward-sentence' function definition
244 The `while' loops
245 The regular expression search
246 `forward-paragraph': a Goldmine of Functions
247 Shortened `forward-paragraph' function definition
248 The `let*' expression
249 The forward motion `while' loop
250 Between paragraphs
251 Within paragraphs
252 No fill prefix
253 With a fill prefix
254 Summary
255 Create Your Own `TAGS' File
256 Review
257 Exercises with `re-search-forward'
258
259Counting: Repetition and Regexps
260 Counting words
261 The `count-words-region' Function
262 Designing `count-words-region'
263 The Whitespace Bug in `count-words-region'
264 Count Words Recursively
265 Exercise: Counting Punctuation
266
267Counting Words in a `defun'
268 Divide and Conquer
269 What to Count?
270 What Constitutes a Word or Symbol?
271 The `count-words-in-defun' Function
272 Count Several `defuns' Within a File
273 Find a File
274 `lengths-list-file' in Detail
275 Count Words in `defuns' in Different Files
276 Determine the lengths of `defuns'
277 The `append' Function
278 Recursively Count Words in Different Files
279 Prepare the Data for Display in a Graph
280 Sorting Lists
281 Making a List of Files
282 Counting function definitions
283
284Readying a Graph
285 Printing the Columns of a Graph
286 The `graph-body-print' Function
287 The `recursive-graph-body-print' Function
288 Need for Printed Axes
289 Exercise
290
291Your `.emacs' File
292 Emacs' Default Configuration
293 Site-wide Initialization Files
294 Specifying Variables using `defcustom'
295 Beginning a `.emacs' File
296 Text and Auto Fill Mode
297 Mail Aliases
298 Indent Tabs Mode
299 Some Keybindings
300 Keymaps
301 Loading Files
302 Autoloading
303 A Simple Extension: `line-to-top-of-window'
304 X11 Colors
305 Miscellaneous Settings for a `.emacs' File
306 A Modified Mode Line
307
308Debugging
309 `debug'
310 `debug-on-entry'
311 `debug-on-quit' and `(debug)'
312 The `edebug' Source Level Debugger
313 Debugging Exercises
314
315Conclusion
316
317The `the-the' Function
318
319Handling the Kill Ring
320 The `rotate-yank-pointer' Function
321 `rotate-yank-pointer' in Outline
322 The Body of `rotate-yank-pointer'
323 Digression about the word `error'
324 The else-part of the `if' expression
325 The `%' remainder function
326 Using `%' in `rotate-yank-pointer'
327 Pointing to the last element
328 `yank'
329 Passing the argument
330 Passing a negative argument
331 `yank-pop'
332
333A Graph with Labelled Axes
334 Labelled Example Graph
335 The `print-graph' Varlist
336 The `print-Y-axis' Function
337 What height should the label be?
338 Side Trip: Compute a Remainder
339 Construct a Y Axis Element
340 Create a Y Axis Column
341 The Not Quite Final Version of `print-Y-axis'
342 The `print-X-axis' Function
343 Similarities and differences
344 X Axis Tic Marks
345 Printing the Whole Graph
346 Changes for the Final Version
347 Testing `print-graph'
348 Graphing Numbers of Words and Symbols
349 A `lambda' Expression: Useful Anonymity
350 The `mapcar' Function
351 Another Bug ... Most Insidious
352 The Printed Graph
353
354GNU Free Documentation License
355
356Index
357
358About the Author
359
360
361An Introduction to Programming in Emacs Lisp
362********************************************
363
364This is an introduction to `Programming in Emacs Lisp', for people
365who are not programmers.
366
367Edition 2.07, 2002 Aug 23
368
369Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002
370Free Software Foundation, Inc.
371
372
373Published by the Free Software Foundation, Inc.
37459 Temple Place, Suite 330
375Boston, MA 02111-1307 USA
376Edition 2.07, 2002 Aug 23
377
378ISBN 1-882114-43-4
379
380Permission is granted to copy, distribute and/or modify this document
381under the terms of the GNU Free Documentation License, Version 1.1 or
382any later version published by the Free Software Foundation; there
383being no Invariant Section, with the Front-Cover Texts being "A GNU
384Manual", and with the Back-Cover Texts as in (a) below. A copy of
385the license is included in the section entitled "GNU Free
386Documentation License".
387
388(a) The FSF's Back-Cover Text is: "You have freedom to copy and
389modify this GNU Manual, like GNU software. Copies published by the
390Free Software Foundation raise funds for GNU development."
391This master menu first lists each chapter and index; then it lists
392every node in every chapter.
393
394Preface
395*******
396
397Most of the GNU Emacs integrated environment is written in the
398programming language called Emacs Lisp. The code written in this
399programming language is the software--the sets of instructions--that
400tell the computer what to do when you give it commands. Emacs is
401designed so that you can write new code in Emacs Lisp and easily
402install it as an extension to the editor.
403
404(GNU Emacs is sometimes called an "extensible editor", but it does
405much more than provide editing capabilities. It is better to refer to
406Emacs as an "extensible computing environment". However, that phrase
407is quite a mouthful. It is easier to refer to Emacs simply as an
408editor. Moreover, everything you do in Emacs--find the Mayan date
409and phases of the moon, simplify polynomials, debug code, manage
410files, read letters, write books--all these activities are kinds of
411editing in the most general sense of the word.)
412
413Why Study Emacs Lisp?
414=====================
415
416Although Emacs Lisp is usually thought of in association only with
417Emacs, it is a full computer programming language. You can use Emacs
418Lisp as you would any other programming language.
419
420Perhaps you want to understand programming; perhaps you want to extend
421Emacs; or perhaps you want to become a programmer. This introduction
422to Emacs Lisp is designed to get you started: to guide you in
423learning the fundamentals of programming, and more importantly, to
424show you how you can teach yourself to go further.
425
426On Reading this Text
427====================
428
429All through this document, you will see little sample programs you can
430run inside of Emacs. If you read this document in Info inside of GNU
431Emacs, you can run the programs as they appear. (This is easy to do
432and is explained when the examples are presented.) Alternatively,
433you can read this introduction as a printed book while sitting beside
434a computer running Emacs. (This is what I like to do; I like printed
435books.) If you don't have a running Emacs beside you, you can still
436read this book, but in this case, it is best to treat it as a novel
437or as a travel guide to a country not yet visited: interesting, but
438not the same as being there.
439
440Much of this introduction is dedicated to walk-throughs or guided
441tours of code used in GNU Emacs. These tours are designed for two
442purposes: first, to give you familiarity with real, working code
443(code you use every day); and, second, to give you familiarity with
444the way Emacs works. It is interesting to see how a working
445environment is implemented. Also, I hope that you will pick up the
446habit of browsing through source code. You can learn from it and
447mine it for ideas. Having GNU Emacs is like having a dragon's cave
448of treasures.
449
450In addition to learning about Emacs as an editor and Emacs Lisp as a
451programming language, the examples and guided tours will give you an
452opportunity to get acquainted with Emacs as a Lisp programming
453environment. GNU Emacs supports programming and provides tools that
454you will want to become comfortable using, such as `M-.' (the key
455which invokes the `find-tag' command). You will also learn about
456buffers and other objects that are part of the environment. Learning
457about these features of Emacs is like learning new routes around your
458home town.
459
460Finally, I hope to convey some of the skills for using Emacs to learn
461aspects of programming that you don't know. You can often use Emacs
462to help you understand what puzzles you or to find out how to do
463something new. This self-reliance is not only a pleasure, but an
464advantage.
465
466For Whom This is Written
467========================
468
469This text is written as an elementary introduction for people who are
470not programmers. If you are a programmer, you may not be satisfied
471with this primer. The reason is that you may have become expert at
472reading reference manuals and be put off by the way this text is
473organized.
474
475An expert programmer who reviewed this text said to me:
476
477 I prefer to learn from reference manuals. I "dive into" each
478 paragraph, and "come up for air" between paragraphs.
479
480 When I get to the end of a paragraph, I assume that that subject
481 is done, finished, that I know everything I need (with the
482 possible exception of the case when the next paragraph starts
483 talking about it in more detail). I expect that a well written
484 reference manual will not have a lot of redundancy, and that it
485 will have excellent pointers to the (one) place where the
486 information I want is.
487
488This introduction is not written for this person!
489
490Firstly, I try to say everything at least three times: first, to
491introduce it; second, to show it in context; and third, to show it in
492a different context, or to review it.
493
494Secondly, I hardly ever put all the information about a subject in one
495place, much less in one paragraph. To my way of thinking, that
496imposes too heavy a burden on the reader. Instead I try to explain
497only what you need to know at the time. (Sometimes I include a
498little extra information so you won't be surprised later when the
499additional information is formally introduced.)
500
501When you read this text, you are not expected to learn everything the
502first time. Frequently, you need only make, as it were, a `nodding
503acquaintance' with some of the items mentioned. My hope is that I
504have structured the text and given you enough hints that you will be
505alert to what is important, and concentrate on it.
506
507You will need to "dive into" some paragraphs; there is no other way
508to read them. But I have tried to keep down the number of such
509paragraphs. This book is intended as an approachable hill, rather
510than as a daunting mountain.
511
512This introduction to `Programming in Emacs Lisp' has a companion
513document, *Note The GNU Emacs Lisp Reference Manual: (elisp)Top. The
514reference manual has more detail than this introduction. In the
515reference manual, all the information about one topic is concentrated
516in one place. You should turn to it if you are like the programmer
517quoted above. And, of course, after you have read this
518`Introduction', you will find the `Reference Manual' useful when you
519are writing your own programs.
520
521Lisp History
522============
523
524Lisp was first developed in the late 1950s at the Massachusetts
525Institute of Technology for research in artificial intelligence. The
526great power of the Lisp language makes it superior for other purposes
527as well, such as writing editor commands and integrated environments.
528
529GNU Emacs Lisp is largely inspired by Maclisp, which was written at
530MIT in the 1960s. It is somewhat inspired by Common Lisp, which
531became a standard in the 1980s. However, Emacs Lisp is much simpler
532than Common Lisp. (The standard Emacs distribution contains an
533optional extensions file, `cl.el', that adds many Common Lisp
534features to Emacs Lisp.)
535
536A Note for Novices
537==================
538
539If you don't know GNU Emacs, you can still read this document
540profitably. However, I recommend you learn Emacs, if only to learn to
541move around your computer screen. You can teach yourself how to use
542Emacs with the on-line tutorial. To use it, type `C-h t'. (This
543means you press and release the <CTRL> key and the `h' at the same
544time, and then press and release `t'.)
545
546Also, I often refer to one of Emacs' standard commands by listing the
547keys which you press to invoke the command and then giving the name of
548the command in parentheses, like this: `M-C-\' (`indent-region').
549What this means is that the `indent-region' command is customarily
550invoked by typing `M-C-\'. (You can, if you wish, change the keys
551that are typed to invoke the command; this is called "rebinding".
552*Note Keymaps: Keymaps.) The abbreviation `M-C-\' means that you
553type your <META> key, <CTRL> key and <\> key all at the same time.
554(On many modern keyboards the <META> key is labelled <ALT>.)
555Sometimes a combination like this is called a keychord, since it is
556similar to the way you play a chord on a piano. If your keyboard does
557not have a <META> key, the <ESC> key prefix is used in place of it.
558In this case, `M-C-\' means that you press and release your <ESC> key
559and then type the <CTRL> key and the <\> key at the same time. But
560usually `M-C-\' means press the <CTRL> key along with the key that is
561labelled <ALT> and, at the same time, press the <\> key.
562
563In addition to typing a lone keychord, you can prefix what you type
564with `C-u', which is called the `universal argument'. The `C-u'
565keychord passes an argument to the subsequent command. Thus, to
566indent a region of plain text by 6 spaces, mark the region, and then
567type `C-u 6 M-C-\'. (If you do not specify a number, Emacs either
568passes the number 4 to the command or otherwise runs the command
569differently than it would otherwise.) *Note Numeric Arguments:
570(emacs)Arguments.
571
572If you are reading this in Info using GNU Emacs, you can read through
573this whole document just by pressing the space bar, <SPC>. (To learn
574about Info, type `C-h i' and then select Info.)
575
576A note on terminology: when I use the word Lisp alone, I often am
577referring to the various dialects of Lisp in general, but when I speak
578of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
579
580Thank You
581=========
582
583My thanks to all who helped me with this book. My especial thanks to
584Jim Blandy, Noah Friedman, Jim Kingdon, Roland McGrath, Frank Ritter,
585Randy Smith, Richard M. Stallman, and Melissa Weisshaus. My thanks
586also go to both Philip Johnson and David Stampe for their patient
587encouragement. My mistakes are my own.
588
589 Robert J. Chassell
590
591List Processing
592***************
593
594To the untutored eye, Lisp is a strange programming language. In Lisp
595code there are parentheses everywhere. Some people even claim that
596the name stands for `Lots of Isolated Silly Parentheses'. But the
597claim is unwarranted. Lisp stands for LISt Processing, and the
598programming language handles _lists_ (and lists of lists) by putting
599them between parentheses. The parentheses mark the boundaries of the
600list. Sometimes a list is preceded by a single apostrophe or
601quotation mark, `''. Lists are the basis of Lisp.
602
603Lisp Lists
604==========
605
606In Lisp, a list looks like this: `'(rose violet daisy buttercup)'.
607This list is preceded by a single apostrophe. It could just as well
608be written as follows, which looks more like the kind of list you are
609likely to be familiar with:
610
611 '(rose
612 violet
613 daisy
614 buttercup)
615
616The elements of this list are the names of the four different flowers,
617separated from each other by whitespace and surrounded by parentheses,
618like flowers in a field with a stone wall around them.
619
620Numbers, Lists inside of Lists
621------------------------------
622
623Lists can also have numbers in them, as in this list: `(+ 2 2)'.
624This list has a plus-sign, `+', followed by two `2's, each separated
625by whitespace.
626
627In Lisp, both data and programs are represented the same way; that is,
628they are both lists of words, numbers, or other lists, separated by
629whitespace and surrounded by parentheses. (Since a program looks like
630data, one program may easily serve as data for another; this is a very
631powerful feature of Lisp.) (Incidentally, these two parenthetical
632remarks are _not_ Lisp lists, because they contain `;' and `.' as
633punctuation marks.)
634
635Here is another list, this time with a list inside of it:
636
637 '(this list has (a list inside of it))
638
639The components of this list are the words `this', `list', `has', and
640the list `(a list inside of it)'. The interior list is made up of
641the words `a', `list', `inside', `of', `it'.
642
643Lisp Atoms
644----------
645
646In Lisp, what we have been calling words are called "atoms". This
647term comes from the historical meaning of the word atom, which means
648`indivisible'. As far as Lisp is concerned, the words we have been
649using in the lists cannot be divided into any smaller parts and still
650mean the same thing as part of a program; likewise with numbers and
651single character symbols like `+'. On the other hand, unlike an
652atom, a list can be split into parts. (*Note `car' `cdr' & `cons'
653Fundamental Functions: car cdr & cons.)
654
655In a list, atoms are separated from each other by whitespace. They
656can be right next to a parenthesis.
657
658Technically speaking, a list in Lisp consists of parentheses
659surrounding atoms separated by whitespace or surrounding other lists
660or surrounding both atoms and other lists. A list can have just one
661atom in it or have nothing in it at all. A list with nothing in it
662looks like this: `()', and is called the "empty list". Unlike
663anything else, an empty list is considered both an atom and a list at
664the same time.
665
666The printed representation of both atoms and lists are called
667"symbolic expressions" or, more concisely, "s-expressions". The word
668"expression" by itself can refer to either the printed
669representation, or to the atom or list as it is held internally in the
670computer. Often, people use the term "expression" indiscriminately.
671(Also, in many texts, the word "form" is used as a synonym for
672expression.)
673
674Incidentally, the atoms that make up our universe were named such when
675they were thought to be indivisible; but it has been found that
676physical atoms are not indivisible. Parts can split off an atom or
677it can fission into two parts of roughly equal size. Physical atoms
678were named prematurely, before their truer nature was found. In
679Lisp, certain kinds of atom, such as an array, can be separated into
680parts; but the mechanism for doing this is different from the
681mechanism for splitting a list. As far as list operations are
682concerned, the atoms of a list are unsplittable.
683
684As in English, the meanings of the component letters of a Lisp atom
685are different from the meaning the letters make as a word. For
686example, the word for the South American sloth, the `ai', is
687completely different from the two words, `a', and `i'.
688
689There are many kinds of atom in nature but only a few in Lisp: for
690example, "numbers", such as 37, 511, or 1729, and "symbols", such as
691`+', `foo', or `forward-line'. The words we have listed in the
692examples above are all symbols. In everyday Lisp conversation, the
693word "atom" is not often used, because programmers usually try to be
694more specific about what kind of atom they are dealing with. Lisp
695programming is mostly about symbols (and sometimes numbers) within
696lists. (Incidentally, the preceding three word parenthetical remark
697is a proper list in Lisp, since it consists of atoms, which in this
698case are symbols, separated by whitespace and enclosed by
699parentheses, without any non-Lisp punctuation.)
700
701In addition, text between double quotation marks--even sentences or
702paragraphs--is an atom. Here is an example:
703
704 '(this list includes "text between quotation marks.")
705
706In Lisp, all of the quoted text including the punctuation mark and the
707blank spaces is a single atom. This kind of atom is called a
708"string" (for `string of characters') and is the sort of thing that
709is used for messages that a computer can print for a human to read.
710Strings are a different kind of atom than numbers or symbols and are
711used differently.
712
713Whitespace in Lists
714-------------------
715
716The amount of whitespace in a list does not matter. From the point
717of view of the Lisp language,
718
719 '(this list
720 looks like this)
721
722is exactly the same as this:
723
724 '(this list looks like this)
725
726Both examples show what to Lisp is the same list, the list made up of
727the symbols `this', `list', `looks', `like', and `this' in that order.
728
729Extra whitespace and newlines are designed to make a list more
730readable by humans. When Lisp reads the expression, it gets rid of
731all the extra whitespace (but it needs to have at least one space
732between atoms in order to tell them apart.)
733
734Odd as it seems, the examples we have seen cover almost all of what
735Lisp lists look like! Every other list in Lisp looks more or less
736like one of these examples, except that the list may be longer and
737more complex. In brief, a list is between parentheses, a string is
738between quotation marks, a symbol looks like a word, and a number
739looks like a number. (For certain situations, square brackets, dots
740and a few other special characters may be used; however, we will go
741quite far without them.)
742
743GNU Emacs Helps You Type Lists
744------------------------------
745
746When you type a Lisp expression in GNU Emacs using either Lisp
747Interaction mode or Emacs Lisp mode, you have available to you several
748commands to format the Lisp expression so it is easy to read. For
749example, pressing the <TAB> key automatically indents the line the
750cursor is on by the right amount. A command to properly indent the
751code in a region is customarily bound to `M-C-\'. Indentation is
752designed so that you can see which elements of a list belong to which
753list--elements of a sub-list are indented more than the elements of
754the enclosing list.
755
756In addition, when you type a closing parenthesis, Emacs momentarily
757jumps the cursor back to the matching opening parenthesis, so you can
758see which one it is. This is very useful, since every list you type
759in Lisp must have its closing parenthesis match its opening
760parenthesis. (*Note Major Modes: (emacs)Major Modes, for more
761information about Emacs' modes.)
762
763Run a Program
764=============
765
766A list in Lisp--any list--is a program ready to run. If you run it
767(for which the Lisp jargon is "evaluate"), the computer will do one
768of three things: do nothing except return to you the list itself; send
769you an error message; or, treat the first symbol in the list as a
770command to do something. (Usually, of course, it is the last of these
771three things that you really want!)
772
773The single apostrophe, `'', that I put in front of some of the
774example lists in preceding sections is called a "quote"; when it
775precedes a list, it tells Lisp to do nothing with the list, other than
776take it as it is written. But if there is no quote preceding a list,
777the first item of the list is special: it is a command for the
778computer to obey. (In Lisp, these commands are called _functions_.)
779The list `(+ 2 2)' shown above did not have a quote in front of it,
780so Lisp understands that the `+' is an instruction to do something
781with the rest of the list: add the numbers that follow.
782
783If you are reading this inside of GNU Emacs in Info, here is how you
784can evaluate such a list: place your cursor immediately after the
785right hand parenthesis of the following list and then type `C-x C-e':
786
787 (+ 2 2)
788
789You will see the number `4' appear in the echo area. (In the jargon,
790what you have just done is "evaluate the list." The echo area is the
791line at the bottom of the screen that displays or "echoes" text.)
792Now try the same thing with a quoted list: place the cursor right
793after the following list and type `C-x C-e':
794
795 '(this is a quoted list)
796
797You will see `(this is a quoted list)' appear in the echo area.
798
799In both cases, what you are doing is giving a command to the program
800inside of GNU Emacs called the "Lisp interpreter"--giving the
801interpreter a command to evaluate the expression. The name of the
802Lisp interpreter comes from the word for the task done by a human who
803comes up with the meaning of an expression--who "interprets" it.
804
805You can also evaluate an atom that is not part of a list--one that is
806not surrounded by parentheses; again, the Lisp interpreter translates
807from the humanly readable expression to the language of the computer.
808But before discussing this (*note Variables::), we will discuss what
809the Lisp interpreter does when you make an error.
810
811Generate an Error Message
812=========================
813
814Partly so you won't worry if you do it accidentally, we will now give
815a command to the Lisp interpreter that generates an error message.
816This is a harmless activity; and indeed, we will often try to generate
817error messages intentionally. Once you understand the jargon, error
818messages can be informative. Instead of being called "error"
819messages, they should be called "help" messages. They are like
820signposts to a traveller in a strange country; deciphering them can be
821hard, but once understood, they can point the way.
822
823The error message is generated by a built-in GNU Emacs debugger. We
824will `enter the debugger'. You get out of the debugger by typing `q'.
825
826What we will do is evaluate a list that is not quoted and does not
827have a meaningful command as its first element. Here is a list almost
828exactly the same as the one we just used, but without the single-quote
829in front of it. Position the cursor right after it and type `C-x
830C-e':
831
832 (this is an unquoted list)
833
834What you see depends on which version of Emacs you are running. GNU
835Emacs version 21 provides more information than version 20 and before.
836First, the more recent result of generating an error; then the
837earlier, version 20 result.
838
839In GNU Emacs version 21, a `*Backtrace*' window will open up and you
840will see the following in it:
841
842 ---------- Buffer: *Backtrace* ----------
843 Debugger entered--Lisp error: (void-function this)
844 (this is an unquoted list)
845 eval((this is an unquoted list))
846 eval-last-sexp-1(nil)
847 eval-last-sexp(nil)
848 call-interactively(eval-last-sexp)
849 ---------- Buffer: *Backtrace* ----------
850
851Your cursor will be in this window (you may have to wait a few seconds
852before it becomes visible). To quit the debugger and make the
853debugger window go away, type:
854
855 q
856
857Please type `q' right now, so you become confident that you can get
858out of the debugger. Then, type `C-x C-e' again to re-enter it.
859
860Based on what we already know, we can almost read this error message.
861
862You read the `*Backtrace*' buffer from the bottom up; it tells you
863what Emacs did. When you typed `C-x C-e', you made an interactive
864call to the command `eval-last-sexp'. `eval' is an abbreviation for
865`evaluate' and `sexp' is an abbreviation for `symbolic expression'.
866The command means `evaluate last symbolic expression', which is the
867expression just before your cursor.
868
869Each line above tells you what the Lisp interpreter evaluated next.
870The most recent action is at the top. The buffer is called the
871`*Backtrace*' buffer because it enables you to track Emacs backwards.
872
873At the top of the `*Backtrace*' buffer, you see the line:
874
875 Debugger entered--Lisp error: (void-function this)
876
877The Lisp interpreter tried to evaluate the first atom of the list, the
878word `this'. It is this action that generated the error message
879`void-function this'.
880
881The message contains the words `void-function' and `this'.
882
883The word `function' was mentioned once before. It is a very
884important word. For our purposes, we can define it by saying that a
885"function" is a set of instructions to the computer that tell the
886computer to do something.
887
888Now we can begin to understand the error message: `void-function
889this'. The function (that is, the word `this') does not have a
890definition of any set of instructions for the computer to carry out.
891
892The slightly odd word, `void-function', is designed to cover the way
893Emacs Lisp is implemented, which is that when a symbol does not have
894a function definition attached to it, the place that should contain
895the instructions is `void'.
896
897On the other hand, since we were able to add 2 plus 2 successfully, by
898evaluating `(+ 2 2)', we can infer that the symbol `+' must have a
899set of instructions for the computer to obey and those instructions
900must be to add the numbers that follow the `+'.
901
902In GNU Emacs version 20, and in earlier versions, you will see only
903one line of error message; it will appear in the echo area and look
904like this:
905
906 Symbol's function definition is void: this
907
908(Also, your terminal may beep at you--some do, some don't; and others
909blink. This is just a device to get your attention.) The message
910goes away as soon as you type another key, even just to move the
911cursor.
912
913We know the meaning of the word `Symbol'. It refers to the first
914atom of the list, the word `this'. The word `function' refers to the
915instructions that tell the computer what to do. (Technically, the
916symbol tells the computer where to find the instructions, but this is
917a complication we can ignore for the moment.)
918
919The error message can be understood: `Symbol's function definition is
920void: this'. The symbol (that is, the word `this') lacks
921instructions for the computer to carry out.
922
923Symbol Names and Function Definitions
924=====================================
925
926We can articulate another characteristic of Lisp based on what we have
927discussed so far--an important characteristic: a symbol, like `+', is
928not itself the set of instructions for the computer to carry out.
929Instead, the symbol is used, perhaps temporarily, as a way of
930locating the definition or set of instructions. What we see is the
931name through which the instructions can be found. Names of people
932work the same way. I can be referred to as `Bob'; however, I am not
933the letters `B', `o', `b' but am the consciousness consistently
934associated with a particular life-form. The name is not me, but it
935can be used to refer to me.
936
937In Lisp, one set of instructions can be attached to several names.
938For example, the computer instructions for adding numbers can be
939linked to the symbol `plus' as well as to the symbol `+' (and are in
940some dialects of Lisp). Among humans, I can be referred to as
941`Robert' as well as `Bob' and by other words as well.
942
943On the other hand, a symbol can have only one function definition
944attached to it at a time. Otherwise, the computer would be confused
945as to which definition to use. If this were the case among people,
946only one person in the world could be named `Bob'. However, the
947function definition to which the name refers can be changed readily.
948(*Note Install a Function Definition: Install.)
949
950Since Emacs Lisp is large, it is customary to name symbols in a way
951that identifies the part of Emacs to which the function belongs.
952Thus, all the names for functions that deal with Texinfo start with
953`texinfo-' and those for functions that deal with reading mail start
954with `rmail-'.
955
956The Lisp Interpreter
957====================
958
959Based on what we have seen, we can now start to figure out what the
960Lisp interpreter does when we command it to evaluate a list. First,
961it looks to see whether there is a quote before the list; if there
962is, the interpreter just gives us the list. On the other hand, if
963there is no quote, the interpreter looks at the first element in the
964list and sees whether it has a function definition. If it does, the
965interpreter carries out the instructions in the function definition.
966Otherwise, the interpreter prints an error message.
967
968This is how Lisp works. Simple. There are added complications which
969we will get to in a minute, but these are the fundamentals. Of
970course, to write Lisp programs, you need to know how to write
971function definitions and attach them to names, and how to do this
972without confusing either yourself or the computer.
973
974Complications
975-------------
976
977Now, for the first complication. In addition to lists, the Lisp
978interpreter can evaluate a symbol that is not quoted and does not have
979parentheses around it. The Lisp interpreter will attempt to determine
980the symbol's value as a "variable". This situation is described in
981the section on variables. (*Note Variables::.)
982
983The second complication occurs because some functions are unusual and
984do not work in the usual manner. Those that don't are called "special
985forms". They are used for special jobs, like defining a function, and
986there are not many of them. In the next few chapters, you will be
987introduced to several of the more important special forms.
988
989The third and final complication is this: if the function that the
990Lisp interpreter is looking at is not a special form, and if it is
991part of a list, the Lisp interpreter looks to see whether the list
992has a list inside of it. If there is an inner list, the Lisp
993interpreter first figures out what it should do with the inside list,
994and then it works on the outside list. If there is yet another list
995embedded inside the inner list, it works on that one first, and so
996on. It always works on the innermost list first. The interpreter
997works on the innermost list first, to evaluate the result of that
998list. The result may be used by the enclosing expression.
999
1000Otherwise, the interpreter works left to right, from one expression to
1001the next.
1002
1003Byte Compiling
1004--------------
1005
1006One other aspect of interpreting: the Lisp interpreter is able to
1007interpret two kinds of entity: humanly readable code, on which we will
1008focus exclusively, and specially processed code, called "byte
1009compiled" code, which is not humanly readable. Byte compiled code
1010runs faster than humanly readable code.
1011
1012You can transform humanly readable code into byte compiled code by
1013running one of the compile commands such as `byte-compile-file'.
1014Byte compiled code is usually stored in a file that ends with a
1015`.elc' extension rather than a `.el' extension. You will see both
1016kinds of file in the `emacs/lisp' directory; the files to read are
1017those with `.el' extensions.
1018
1019As a practical matter, for most things you might do to customize or
1020extend Emacs, you do not need to byte compile; and I will not discuss
1021the topic here. *Note Byte Compilation: (elisp)Byte Compilation, for
1022a full description of byte compilation.
1023
1024Evaluation
1025==========
1026
1027When the Lisp interpreter works on an expression, the term for the
1028activity is called "evaluation". We say that the interpreter
1029`evaluates the expression'. I've used this term several times before.
1030The word comes from its use in everyday language, `to ascertain the
1031value or amount of; to appraise', according to `Webster's New
1032Collegiate Dictionary'.
1033
1034After evaluating an expression, the Lisp interpreter will most likely
1035"return" the value that the computer produces by carrying out the
1036instructions it found in the function definition, or perhaps it will
1037give up on that function and produce an error message. (The
1038interpreter may also find itself tossed, so to speak, to a different
1039function or it may attempt to repeat continually what it is doing for
1040ever and ever in what is called an `infinite loop'. These actions
1041are less common; and we can ignore them.) Most frequently, the
1042interpreter returns a value.
1043
1044At the same time the interpreter returns a value, it may do something
1045else as well, such as move a cursor or copy a file; this other kind of
1046action is called a "side effect". Actions that we humans think are
1047important, such as printing results, are often "side effects" to the
1048Lisp interpreter. The jargon can sound peculiar, but it turns out
1049that it is fairly easy to learn to use side effects.
1050
1051In summary, evaluating a symbolic expression most commonly causes the
1052Lisp interpreter to return a value and perhaps carry out a side
1053effect; or else produce an error.
1054
1055Evaluating Inner Lists
1056----------------------
1057
1058If evaluation applies to a list that is inside another list, the outer
1059list may use the value returned by the first evaluation as information
1060when the outer list is evaluated. This explains why inner expressions
1061are evaluated first: the values they return are used by the outer
1062expressions.
1063
1064We can investigate this process by evaluating another addition
1065example. Place your cursor after the following expression and type
1066`C-x C-e':
1067
1068 (+ 2 (+ 3 3))
1069
1070The number 8 will appear in the echo area.
1071
1072What happens is that the Lisp interpreter first evaluates the inner
1073expression, `(+ 3 3)', for which the value 6 is returned; then it
1074evaluates the outer expression as if it were written `(+ 2 6)', which
1075returns the value 8. Since there are no more enclosing expressions to
1076evaluate, the interpreter prints that value in the echo area.
1077
1078Now it is easy to understand the name of the command invoked by the
1079keystrokes `C-x C-e': the name is `eval-last-sexp'. The letters
1080`sexp' are an abbreviation for `symbolic expression', and `eval' is
1081an abbreviation for `evaluate'. The command means `evaluate last
1082symbolic expression'.
1083
1084As an experiment, you can try evaluating the expression by putting the
1085cursor at the beginning of the next line immediately following the
1086expression, or inside the expression.
1087
1088Here is another copy of the expression:
1089
1090 (+ 2 (+ 3 3))
1091
1092If you place the cursor at the beginning of the blank line that
1093immediately follows the expression and type `C-x C-e', you will still
1094get the value 8 printed in the echo area. Now try putting the cursor
1095inside the expression. If you put it right after the next to last
1096parenthesis (so it appears to sit on top of the last parenthesis),
1097you will get a 6 printed in the echo area! This is because the
1098command evaluates the expression `(+ 3 3)'.
1099
1100Now put the cursor immediately after a number. Type `C-x C-e' and
1101you will get the number itself. In Lisp, if you evaluate a number,
1102you get the number itself--this is how numbers differ from symbols.
1103If you evaluate a list starting with a symbol like `+', you will get a
1104value returned that is the result of the computer carrying out the
1105instructions in the function definition attached to that name. If a
1106symbol by itself is evaluated, something different happens, as we will
1107see in the next section.
1108
1109Variables
1110=========
1111
1112In Emacs Lisp, a symbol can have a value attached to it just as it can
1113have a function definition attached to it. The two are different.
1114The function definition is a set of instructions that a computer will
1115obey. A value, on the other hand, is something, such as number or a
1116name, that can vary (which is why such a symbol is called a variable).
1117The value of a symbol can be any expression in Lisp, such as a symbol,
1118number, list, or string. A symbol that has a value is often called a
1119"variable".
1120
1121A symbol can have both a function definition and a value attached to
1122it at the same time. Or it can have just one or the other. The two
1123are separate. This is somewhat similar to the way the name Cambridge
1124can refer to the city in Massachusetts and have some information
1125attached to the name as well, such as "great programming center".
1126
1127Another way to think about this is to imagine a symbol as being a
1128chest of drawers. The function definition is put in one drawer, the
1129value in another, and so on. What is put in the drawer holding the
1130value can be changed without affecting the contents of the drawer
1131holding the function definition, and vice-versa.
1132
1133`fill-column', an Example Variable
1134----------------------------------
1135
1136The variable `fill-column' illustrates a symbol with a value attached
1137to it: in every GNU Emacs buffer, this symbol is set to some value,
1138usually 72 or 70, but sometimes to some other value. To find the
1139value of this symbol, evaluate it by itself. If you are reading this
1140in Info inside of GNU Emacs, you can do this by putting the cursor
1141after the symbol and typing `C-x C-e':
1142
1143 fill-column
1144
1145After I typed `C-x C-e', Emacs printed the number 72 in my echo area.
1146This is the value for which `fill-column' is set for me as I write
1147this. It may be different for you in your Info buffer. Notice that
1148the value returned as a variable is printed in exactly the same way
1149as the value returned by a function carrying out its instructions.
1150From the point of view of the Lisp interpreter, a value returned is a
1151value returned. What kind of expression it came from ceases to
1152matter once the value is known.
1153
1154A symbol can have any value attached to it or, to use the jargon, we
1155can "bind" the variable to a value: to a number, such as 72; to a
1156string, `"such as this"'; to a list, such as `(spruce pine oak)'; we
1157can even bind a variable to a function definition.
1158
1159A symbol can be bound to a value in several ways. *Note Setting the
1160Value of a Variable: set & setq, for information about one way to do
1161this.
1162
1163Error Message for a Symbol Without a Function
1164---------------------------------------------
1165
1166When we evaluated `fill-column' to find its value as a variable, we
1167did not place parentheses around the word. This is because we did
1168not intend to use it as a function name.
1169
1170If `fill-column' were the first or only element of a list, the Lisp
1171interpreter would attempt to find the function definition attached to
1172it. But `fill-column' has no function definition. Try evaluating
1173this:
1174
1175 (fill-column)
1176
1177In GNU Emacs version 21, you will create a `*Backtrace*' buffer that
1178says:
1179
1180 ---------- Buffer: *Backtrace* ----------
1181 Debugger entered--Lisp error: (void-function fill-column)
1182 (fill-column)
1183 eval((fill-column))
1184 eval-last-sexp-1(nil)
1185 eval-last-sexp(nil)
1186 call-interactively(eval-last-sexp)
1187 ---------- Buffer: *Backtrace* ----------
1188
1189(Remember, to quit the debugger and make the debugger window go away,
1190type `q' in the `*Backtrace*' buffer.)
1191
1192In GNU Emacs 20 and before, you will produce an error message that
1193says:
1194
1195 Symbol's function definition is void: fill-column
1196
1197(The message will go away away as soon as you move the cursor or type
1198another key.)
1199
1200Error Message for a Symbol Without a Value
1201------------------------------------------
1202
1203If you attempt to evaluate a symbol that does not have a value bound
1204to it, you will receive an error message. You can see this by
1205experimenting with our 2 plus 2 addition. In the following
1206expression, put your cursor right after the `+', before the first
1207number 2, type `C-x C-e':
1208
1209 (+ 2 2)
1210
1211In GNU Emacs 21, you will create a `*Backtrace*' buffer that says:
1212
1213 ---------- Buffer: *Backtrace* ----------
1214 Debugger entered--Lisp error: (void-variable +)
1215 eval(+)
1216 eval-last-sexp-1(nil)
1217 eval-last-sexp(nil)
1218 call-interactively(eval-last-sexp)
1219 ---------- Buffer: *Backtrace* ----------
1220
1221(As with the other times we entered the debugger, you can quit by
1222typing `q' in the `*Backtrace*' buffer.)
1223
1224This backtrace is different from the very first error message we saw,
1225which said, `Debugger entered--Lisp error: (void-function this)'. In
1226this case, the function does not have a value as a variable; while in
1227the other error message, the function (the word `this') did not have
1228a definition.
1229
1230In this experiment with the `+', what we did was cause the Lisp
1231interpreter to evaluate the `+' and look for the value of the
1232variable instead of the function definition. We did this by placing
1233the cursor right after the symbol rather than after the parenthesis
1234of the enclosing list as we did before. As a consequence, the Lisp
1235interpreter evaluated the preceding s-expression, which in this case
1236was the `+' by itself.
1237
1238Since `+' does not have a value bound to it, just the function
1239definition, the error message reported that the symbol's value as a
1240variable was void.
1241
1242In GNU Emacs version 20 and before, your error message will say:
1243
1244 Symbol's value as variable is void: +
1245
1246The meaning is the same as in GNU Emacs 21.
1247
1248Arguments
1249=========
1250
1251To see how information is passed to functions, let's look again at
1252our old standby, the addition of two plus two. In Lisp, this is
1253written as follows:
1254
1255 (+ 2 2)
1256
1257If you evaluate this expression, the number 4 will appear in your echo
1258area. What the Lisp interpreter does is add the numbers that follow
1259the `+'.
1260
1261The numbers added by `+' are called the "arguments" of the function
1262`+'. These numbers are the information that is given to or "passed"
1263to the function.
1264
1265The word `argument' comes from the way it is used in mathematics and
1266does not refer to a disputation between two people; instead it refers
1267to the information presented to the function, in this case, to the
1268`+'. In Lisp, the arguments to a function are the atoms or lists
1269that follow the function. The values returned by the evaluation of
1270these atoms or lists are passed to the function. Different functions
1271require different numbers of arguments; some functions require none at
1272all.(1)
1273
1274---------- Footnotes ----------
1275
1276(1) It is curious to track the path by which the word `argument' came
1277to have two different meanings, one in mathematics and the other in
1278everyday English. According to the `Oxford English Dictionary', the
1279word derives from the Latin for `to make clear, prove'; thus it came
1280to mean, by one thread of derivation, `the evidence offered as
1281proof', which is to say, `the information offered', which led to its
1282meaning in Lisp. But in the other thread of derivation, it came to
1283mean `to assert in a manner against which others may make counter
1284assertions', which led to the meaning of the word as a disputation.
1285(Note here that the English word has two different definitions
1286attached to it at the same time. By contrast, in Emacs Lisp, a
1287symbol cannot have two different function definitions at the same
1288time.)
1289
1290Arguments' Data Types
1291---------------------
1292
1293The type of data that should be passed to a function depends on what
1294kind of information it uses. The arguments to a function such as `+'
1295must have values that are numbers, since `+' adds numbers. Other
1296functions use different kinds of data for their arguments.
1297
1298For example, the `concat' function links together or unites two or
1299more strings of text to produce a string. The arguments are strings.
1300Concatenating the two character strings `abc', `def' produces the
1301single string `abcdef'. This can be seen by evaluating the following:
1302
1303 (concat "abc" "def")
1304
1305The value produced by evaluating this expression is `"abcdef"'.
1306
1307A function such as `substring' uses both a string and numbers as
1308arguments. The function returns a part of the string, a substring of
1309the first argument. This function takes three arguments. Its first
1310argument is the string of characters, the second and third arguments
1311are numbers that indicate the beginning and end of the substring. The
1312numbers are a count of the number of characters (including spaces and
1313punctuations) from the beginning of the string.
1314
1315For example, if you evaluate the following:
1316
1317 (substring "The quick brown fox jumped." 16 19)
1318
1319you will see `"fox"' appear in the echo area. The arguments are the
1320string and the two numbers.
1321
1322Note that the string passed to `substring' is a single atom even
1323though it is made up of several words separated by spaces. Lisp
1324counts everything between the two quotation marks as part of the
1325string, including the spaces. You can think of the `substring'
1326function as a kind of `atom smasher' since it takes an otherwise
1327indivisible atom and extracts a part. However, `substring' is only
1328able to extract a substring from an argument that is a string, not
1329from another type of atom such as a number or symbol.
1330
1331An Argument as the Value of a Variable or List
1332----------------------------------------------
1333
1334An argument can be a symbol that returns a value when it is evaluated.
1335For example, when the symbol `fill-column' by itself is evaluated, it
1336returns a number. This number can be used in an addition.
1337
1338Position the cursor after the following expression and type `C-x C-e':
1339
1340 (+ 2 fill-column)
1341
1342The value will be a number two more than what you get by evaluating
1343`fill-column' alone. For me, this is 74, because the value of
1344`fill-column' is 72.
1345
1346As we have just seen, an argument can be a symbol that returns a value
1347when evaluated. In addition, an argument can be a list that returns a
1348value when it is evaluated. For example, in the following expression,
1349the arguments to the function `concat' are the strings `"The "' and
1350`" red foxes."' and the list `(number-to-string (+ 2 fill-column))'.
1351
1352 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
1353
1354If you evaluate this expression--and if, as with my Emacs,
1355`fill-column' evaluates to 72--`"The 74 red foxes."' will appear in
1356the echo area. (Note that you must put spaces after the word `The'
1357and before the word `red' so they will appear in the final string.
1358The function `number-to-string' converts the integer that the
1359addition function returns to a string. `number-to-string' is also
1360known as `int-to-string'.)
1361
1362Variable Number of Arguments
1363----------------------------
1364
1365Some functions, such as `concat', `+' or `*', take any number of
1366arguments. (The `*' is the symbol for multiplication.) This can be
1367seen by evaluating each of the following expressions in the usual
1368way. What you will see in the echo area is printed in this text
1369after `=>', which you may read as `evaluates to'.
1370
1371In the first set, the functions have no arguments:
1372
1373 (+) => 0
1374
1375 (*) => 1
1376
1377In this set, the functions have one argument each:
1378
1379 (+ 3) => 3
1380
1381 (* 3) => 3
1382
1383In this set, the functions have three arguments each:
1384
1385 (+ 3 4 5) => 12
1386
1387 (* 3 4 5) => 60
1388
1389Using the Wrong Type Object as an Argument
1390------------------------------------------
1391
1392When a function is passed an argument of the wrong type, the Lisp
1393interpreter produces an error message. For example, the `+' function
1394expects the values of its arguments to be numbers. As an experiment
1395we can pass it the quoted symbol `hello' instead of a number.
1396Position the cursor after the following expression and type `C-x C-e':
1397
1398 (+ 2 'hello)
1399
1400When you do this you will generate an error message. What has
1401happened is that `+' has tried to add the 2 to the value returned by
1402`'hello', but the value returned by `'hello' is the symbol `hello',
1403not a number. Only numbers can be added. So `+' could not carry out
1404its addition.
1405
1406In GNU Emacs version 21, you will create and enter a `*Backtrace*'
1407buffer that says:
1408
1409 ---------- Buffer: *Backtrace* ----------
1410 Debugger entered--Lisp error:
1411 (wrong-type-argument number-or-marker-p hello)
1412 +(2 hello)
1413 eval((+ 2 (quote hello)))
1414 eval-last-sexp-1(nil)
1415 eval-last-sexp(nil)
1416 call-interactively(eval-last-sexp)
1417 ---------- Buffer: *Backtrace* ----------
1418
1419As usual, the error message tries to be helpful and makes sense after
1420you learn how to read it.
1421
1422The first part of the error message is straightforward; it says
1423`wrong type argument'. Next comes the mysterious jargon word
1424`number-or-marker-p'. This word is trying to tell you what kind of
1425argument the `+' expected.
1426
1427The symbol `number-or-marker-p' says that the Lisp interpreter is
1428trying to determine whether the information presented it (the value of
1429the argument) is a number or a marker (a special object representing a
1430buffer position). What it does is test to see whether the `+' is
1431being given numbers to add. It also tests to see whether the
1432argument is something called a marker, which is a specific feature of
1433Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
1434When the mark is set with the `C-@' or `C-<SPC>' command, its
1435position is kept as a marker. The mark can be considered a
1436number--the number of characters the location is from the beginning
1437of the buffer.) In Emacs Lisp, `+' can be used to add the numeric
1438value of marker positions as numbers.
1439
1440The `p' of `number-or-marker-p' is the embodiment of a practice
1441started in the early days of Lisp programming. The `p' stands for
1442`predicate'. In the jargon used by the early Lisp researchers, a
1443predicate refers to a function to determine whether some property is
1444true or false. So the `p' tells us that `number-or-marker-p' is the
1445name of a function that determines whether it is true or false that
1446the argument supplied is a number or a marker. Other Lisp symbols
1447that end in `p' include `zerop', a function that tests whether its
1448argument has the value of zero, and `listp', a function that tests
1449whether its argument is a list.
1450
1451Finally, the last part of the error message is the symbol `hello'.
1452This is the value of the argument that was passed to `+'. If the
1453addition had been passed the correct type of object, the value passed
1454would have been a number, such as 37, rather than a symbol like
1455`hello'. But then you would not have got the error message.
1456
1457In GNU Emacs version 20 and before, the echo area displays an error
1458message that says:
1459
1460 Wrong type argument: number-or-marker-p, hello
1461
1462This says, in different words, the same as the top line of the
1463`*Backtrace*' buffer.
1464
1465The `message' Function
1466----------------------
1467
1468Like `+', the `message' function takes a variable number of
1469arguments. It is used to send messages to the user and is so useful
1470that we will describe it here.
1471
1472A message is printed in the echo area. For example, you can print a
1473message in your echo area by evaluating the following list:
1474
1475 (message "This message appears in the echo area!")
1476
1477The whole string between double quotation marks is a single argument
1478and is printed in toto. (Note that in this example, the message
1479itself will appear in the echo area within double quotes; that is
1480because you see the value returned by the `message' function. In
1481most uses of `message' in programs that you write, the text will be
1482printed in the echo area as a side-effect, without the quotes. *Note
1483`multiply-by-seven' in detail: multiply-by-seven in detail, for an
1484example of this.)
1485
1486However, if there is a `%s' in the quoted string of characters, the
1487`message' function does not print the `%s' as such, but looks to the
1488argument that follows the string. It evaluates the second argument
1489and prints the value at the location in the string where the `%s' is.
1490
1491You can see this by positioning the cursor after the following
1492expression and typing `C-x C-e':
1493
1494 (message "The name of this buffer is: %s." (buffer-name))
1495
1496In Info, `"The name of this buffer is: *info*."' will appear in the
1497echo area. The function `buffer-name' returns the name of the buffer
1498as a string, which the `message' function inserts in place of `%s'.
1499
1500To print a value as an integer, use `%d' in the same way as `%s'.
1501For example, to print a message in the echo area that states the
1502value of the `fill-column', evaluate the following:
1503
1504 (message "The value of fill-column is %d." fill-column)
1505
1506On my system, when I evaluate this list, `"The value of fill-column
1507is 72."' appears in my echo area(1).
1508
1509If there is more than one `%s' in the quoted string, the value of the
1510first argument following the quoted string is printed at the location
1511of the first `%s' and the value of the second argument is printed at
1512the location of the second `%s', and so on.
1513
1514For example, if you evaluate the following,
1515
1516 (message "There are %d %s in the office!"
1517 (- fill-column 14) "pink elephants")
1518
1519a rather whimsical message will appear in your echo area. On my
1520system it says, `"There are 58 pink elephants in the office!"'.
1521
1522The expression `(- fill-column 14)' is evaluated and the resulting
1523number is inserted in place of the `%d'; and the string in double
1524quotes, `"pink elephants"', is treated as a single argument and
1525inserted in place of the `%s'. (That is to say, a string between
1526double quotes evaluates to itself, like a number.)
1527
1528Finally, here is a somewhat complex example that not only illustrates
1529the computation of a number, but also shows how you can use an
1530expression within an expression to generate the text that is
1531substituted for `%s':
1532
1533 (message "He saw %d %s"
1534 (- fill-column 34)
1535 (concat "red "
1536 (substring
1537 "The quick brown foxes jumped." 16 21)
1538 " leaping."))
1539
1540In this example, `message' has three arguments: the string, `"He saw
1541%d %s"', the expression, `(- fill-column 32)', and the expression
1542beginning with the function `concat'. The value resulting from the
1543evaluation of `(- fill-column 32)' is inserted in place of the `%d';
1544and the value returned by the expression beginning with `concat' is
1545inserted in place of the `%s'.
1546
1547When I evaluate the expression, the message `"He saw 38 red foxes
1548leaping."' appears in my echo area.
1549
1550---------- Footnotes ----------
1551
1552(1) Actually, you can use `%s' to print a number. It is
1553non-specific. `%d' prints only the part of a number left of a
1554decimal point, and not anything that is not a number.
1555
1556Setting the Value of a Variable
1557===============================
1558
1559There are several ways by which a variable can be given a value. One
1560of the ways is to use either the function `set' or the function
1561`setq'. Another way is to use `let' (*note let::). (The jargon for
1562this process is to "bind" a variable to a value.)
1563
1564The following sections not only describe how `set' and `setq' work
1565but also illustrate how arguments are passed.
1566
1567Using `set'
1568-----------
1569
1570To set the value of the symbol `flowers' to the list `'(rose violet
1571daisy buttercup)', evaluate the following expression by positioning
1572the cursor after the expression and typing `C-x C-e'.
1573
1574 (set 'flowers '(rose violet daisy buttercup))
1575
1576The list `(rose violet daisy buttercup)' will appear in the echo
1577area. This is what is _returned_ by the `set' function. As a side
1578effect, the symbol `flowers' is bound to the list ; that is, the
1579symbol `flowers', which can be viewed as a variable, is given the
1580list as its value. (This process, by the way, illustrates how a side
1581effect to the Lisp interpreter, setting the value, can be the primary
1582effect that we humans are interested in. This is because every Lisp
1583function must return a value if it does not get an error, but it will
1584only have a side effect if it is designed to have one.)
1585
1586After evaluating the `set' expression, you can evaluate the symbol
1587`flowers' and it will return the value you just set. Here is the
1588symbol. Place your cursor after it and type `C-x C-e'.
1589
1590 flowers
1591
1592When you evaluate `flowers', the list `(rose violet daisy buttercup)'
1593appears in the echo area.
1594
1595Incidentally, if you evaluate `'flowers', the variable with a quote
1596in front of it, what you will see in the echo area is the symbol
1597itself, `flowers'. Here is the quoted symbol, so you can try this:
1598
1599 'flowers
1600
1601Note also, that when you use `set', you need to quote both arguments
1602to `set', unless you want them evaluated. Since we do not want
1603either argument evaluated, neither the variable `flowers' nor the
1604list `(rose violet daisy buttercup)', both are quoted. (When you use
1605`set' without quoting its first argument, the first argument is
1606evaluated before anything else is done. If you did this and
1607`flowers' did not have a value already, you would get an error
1608message that the `Symbol's value as variable is void'; on the other
1609hand, if `flowers' did return a value after it was evaluated, the
1610`set' would attempt to set the value that was returned. There are
1611situations where this is the right thing for the function to do; but
1612such situations are rare.)
1613
1614Using `setq'
1615------------
1616
1617As a practical matter, you almost always quote the first argument to
1618`set'. The combination of `set' and a quoted first argument is so
1619common that it has its own name: the special form `setq'. This
1620special form is just like `set' except that the first argument is
1621quoted automatically, so you don't need to type the quote mark
1622yourself. Also, as an added convenience, `setq' permits you to set
1623several different variables to different values, all in one
1624expression.
1625
1626To set the value of the variable `carnivores' to the list `'(lion
1627tiger leopard)' using `setq', the following expression is used:
1628
1629 (setq carnivores '(lion tiger leopard))
1630
1631This is exactly the same as using `set' except the first argument is
1632automatically quoted by `setq'. (The `q' in `setq' means `quote'.)
1633
1634With `set', the expression would look like this:
1635
1636 (set 'carnivores '(lion tiger leopard))
1637
1638Also, `setq' can be used to assign different values to different
1639variables. The first argument is bound to the value of the second
1640argument, the third argument is bound to the value of the fourth
1641argument, and so on. For example, you could use the following to
1642assign a list of trees to the symbol `trees' and a list of herbivores
1643to the symbol `herbivores':
1644
1645 (setq trees '(pine fir oak maple)
1646 herbivores '(gazelle antelope zebra))
1647
1648(The expression could just as well have been on one line, but it might
1649not have fit on a page; and humans find it easier to read nicely
1650formatted lists.)
1651
1652Although I have been using the term `assign', there is another way of
1653thinking about the workings of `set' and `setq'; and that is to say
1654that `set' and `setq' make the symbol _point_ to the list. This
1655latter way of thinking is very common and in forthcoming chapters we
1656shall come upon at least one symbol that has `pointer' as part of its
1657name. The name is chosen because the symbol has a value,
1658specifically a list, attached to it; or, expressed another way, the
1659symbol is set to "point" to the list.
1660
1661Counting
1662--------
1663
1664Here is an example that shows how to use `setq' in a counter. You
1665might use this to count how many times a part of your program repeats
1666itself. First set a variable to zero; then add one to the number each
1667time the program repeats itself. To do this, you need a variable that
1668serves as a counter, and two expressions: an initial `setq'
1669expression that sets the counter variable to zero; and a second
1670`setq' expression that increments the counter each time it is
1671evaluated.
1672
1673 (setq counter 0) ; Let's call this the initializer.
1674
1675 (setq counter (+ counter 1)) ; This is the incrementer.
1676
1677 counter ; This is the counter.
1678
1679(The text following the `;' are comments. *Note Change a Function
1680Definition: Change a defun.)
1681
1682If you evaluate the first of these expressions, the initializer,
1683`(setq counter 0)', and then evaluate the third expression,
1684`counter', the number `0' will appear in the echo area. If you then
1685evaluate the second expression, the incrementer, `(setq counter (+
1686counter 1))', the counter will get the value 1. So if you again
1687evaluate `counter', the number `1' will appear in the echo area.
1688Each time you evaluate the second expression, the value of the
1689counter will be incremented.
1690
1691When you evaluate the incrementer, `(setq counter (+ counter 1))',
1692the Lisp interpreter first evaluates the innermost list; this is the
1693addition. In order to evaluate this list, it must evaluate the
1694variable `counter' and the number `1'. When it evaluates the variable
1695`counter', it receives its current value. It passes this value and
1696the number `1' to the `+' which adds them together. The sum is then
1697returned as the value of the inner list and passed to the `setq'
1698which sets the variable `counter' to this new value. Thus, the value
1699of the variable, `counter', is changed.
1700
1701Summary
1702=======
1703
1704Learning Lisp is like climbing a hill in which the first part is the
1705steepest. You have now climbed the most difficult part; what remains
1706becomes easier as you progress onwards.
1707
1708In summary,
1709
1710 * Lisp programs are made up of expressions, which are lists or
1711 single atoms.
1712
1713 * Lists are made up of zero or more atoms or inner lists,
1714 separated by whitespace and surrounded by parentheses. A list
1715 can be empty.
1716
1717 * Atoms are multi-character symbols, like `forward-paragraph',
1718 single character symbols like `+', strings of characters between
1719 double quotation marks, or numbers.
1720
1721 * A number evaluates to itself.
1722
1723 * A string between double quotes also evaluates to itself.
1724
1725 * When you evaluate a symbol by itself, its value is returned.
1726
1727 * When you evaluate a list, the Lisp interpreter looks at the
1728 first symbol in the list and then at the function definition
1729 bound to that symbol. Then the instructions in the function
1730 definition are carried out.
1731
1732 * A single-quote, `'', tells the Lisp interpreter that it should
1733 return the following expression as written, and not evaluate it
1734 as it would if the quote were not there.
1735
1736 * Arguments are the information passed to a function. The
1737 arguments to a function are computed by evaluating the rest of
1738 the elements of the list of which the function is the first
1739 element.
1740
1741 * A function always returns a value when it is evaluated (unless
1742 it gets an error); in addition, it may also carry out some
1743 action called a "side effect". In many cases, a function's
1744 primary purpose is to create a side effect.
1745
1746Exercises
1747=========
1748
1749A few simple exercises:
1750
1751 * Generate an error message by evaluating an appropriate symbol
1752 that is not within parentheses.
1753
1754 * Generate an error message by evaluating an appropriate symbol
1755 that is between parentheses.
1756
1757 * Create a counter that increments by two rather than one.
1758
1759 * Write an expression that prints a message in the echo area when
1760 evaluated.
1761
1762Practicing Evaluation
1763*********************
1764
1765Before learning how to write a function definition in Emacs Lisp, it
1766is useful to spend a little time evaluating various expressions that
1767have already been written. These expressions will be lists with the
1768functions as their first (and often only) element. Since some of the
1769functions associated with buffers are both simple and interesting, we
1770will start with those. In this section, we will evaluate a few of
1771these. In another section, we will study the code of several other
1772buffer-related functions, to see how they were written.
1773
1774How to Evaluate
1775===============
1776
1777Whenever you give an editing command to Emacs Lisp, such as the
1778command to move the cursor or to scroll the screen, you are evaluating
1779an expression, the first element of which is a function. This is how
1780Emacs works.
1781
1782When you type keys, you cause the Lisp interpreter to evaluate an
1783expression and that is how you get your results. Even typing plain
1784text involves evaluating an Emacs Lisp function, in this case, one
1785that uses `self-insert-command', which simply inserts the character
1786you typed. The functions you evaluate by typing keystrokes are called
1787"interactive" functions, or "commands"; how you make a function
1788interactive will be illustrated in the chapter on how to write
1789function definitions. *Note Making a Function Interactive:
1790Interactive.
1791
1792In addition to typing keyboard commands, we have seen a second way to
1793evaluate an expression: by positioning the cursor after a list and
1794typing `C-x C-e'. This is what we will do in the rest of this
1795section. There are other ways to evaluate an expression as well;
1796these will be described as we come to them.
1797
1798Besides being used for practicing evaluation, the functions shown in
1799the next few sections are important in their own right. A study of
1800these functions makes clear the distinction between buffers and
1801files, how to switch to a buffer, and how to determine a location
1802within it.
1803
1804Buffer Names
1805============
1806
1807The two functions, `buffer-name' and `buffer-file-name', show the
1808difference between a file and a buffer. When you evaluate the
1809following expression, `(buffer-name)', the name of the buffer appears
1810in the echo area. When you evaluate `(buffer-file-name)', the name
1811of the file to which the buffer refers appears in the echo area.
1812Usually, the name returned by `(buffer-name)' is the same as the name
1813of the file to which it refers, and the name returned by
1814`(buffer-file-name)' is the full path-name of the file.
1815
1816A file and a buffer are two different entities. A file is information
1817recorded permanently in the computer (unless you delete it). A
1818buffer, on the other hand, is information inside of Emacs that will
1819vanish at the end of the editing session (or when you kill the
1820buffer). Usually, a buffer contains information that you have copied
1821from a file; we say the buffer is "visiting" that file. This copy is
1822what you work on and modify. Changes to the buffer do not change the
1823file, until you save the buffer. When you save the buffer, the
1824buffer is copied to the file and is thus saved permanently.
1825
1826If you are reading this in Info inside of GNU Emacs, you can evaluate
1827each of the following expressions by positioning the cursor after it
1828and typing `C-x C-e'.
1829
1830 (buffer-name)
1831
1832 (buffer-file-name)
1833
1834When I do this, `"introduction.texinfo"' is the value returned by
1835evaluating `(buffer-name)', and
1836`"/gnu/work/intro/introduction.texinfo"' is the value returned by
1837evaluating `(buffer-file-name)'. The former is the name of the
1838buffer and the latter is the name of the file. (In the expressions,
1839the parentheses tell the Lisp interpreter to treat `buffer-name' and
1840`buffer-file-name' as functions; without the parentheses, the
1841interpreter would attempt to evaluate the symbols as variables.
1842*Note Variables::.)
1843
1844In spite of the distinction between files and buffers, you will often
1845find that people refer to a file when they mean a buffer and
1846vice-versa. Indeed, most people say, "I am editing a file," rather
1847than saying, "I am editing a buffer which I will soon save to a
1848file." It is almost always clear from context what people mean.
1849When dealing with computer programs, however, it is important to keep
1850the distinction in mind, since the computer is not as smart as a
1851person.
1852
1853The word `buffer', by the way, comes from the meaning of the word as a
1854cushion that deadens the force of a collision. In early computers, a
1855buffer cushioned the interaction between files and the computer's
1856central processing unit. The drums or tapes that held a file and the
1857central processing unit were pieces of equipment that were very
1858different from each other, working at their own speeds, in spurts.
1859The buffer made it possible for them to work together effectively.
1860Eventually, the buffer grew from being an intermediary, a temporary
1861holding place, to being the place where work is done. This
1862transformation is rather like that of a small seaport that grew into a
1863great city: once it was merely the place where cargo was warehoused
1864temporarily before being loaded onto ships; then it became a business
1865and cultural center in its own right.
1866
1867Not all buffers are associated with files. For example, when you
1868start an Emacs session by typing the command `emacs' alone, without
1869naming any files, Emacs will start with the `*scratch*' buffer on the
1870screen. This buffer is not visiting any file. Similarly, a `*Help*'
1871buffer is not associated with any file.
1872
1873If you switch to the `*scratch*' buffer, type `(buffer-name)',
1874position the cursor after it, and type `C-x C-e' to evaluate the
1875expression, the name `"*scratch*"' is returned and will appear in the
1876echo area. `"*scratch*"' is the name of the buffer. However, if you
1877type `(buffer-file-name)' in the `*scratch*' buffer and evaluate
1878that, `nil' will appear in the echo area. `nil' is from the Latin
1879word for `nothing'; in this case, it means that the `*scratch*'
1880buffer is not associated with any file. (In Lisp, `nil' is also used
1881to mean `false' and is a synonym for the empty list, `()'.)
1882
1883Incidentally, if you are in the `*scratch*' buffer and want the value
1884returned by an expression to appear in the `*scratch*' buffer itself
1885rather than in the echo area, type `C-u C-x C-e' instead of `C-x
1886C-e'. This causes the value returned to appear after the expression.
1887The buffer will look like this:
1888
1889 (buffer-name)"*scratch*"
1890
1891You cannot do this in Info since Info is read-only and it will not
1892allow you to change the contents of the buffer. But you can do this
1893in any buffer you can edit; and when you write code or documentation
1894(such as this book), this feature is very useful.
1895
1896Getting Buffers
1897===============
1898
1899The `buffer-name' function returns the _name_ of the buffer; to get
1900the buffer _itself_, a different function is needed: the
1901`current-buffer' function. If you use this function in code, what
1902you get is the buffer itself.
1903
1904A name and the object or entity to which the name refers are different
1905from each other. You are not your name. You are a person to whom
1906others refer by name. If you ask to speak to George and someone
1907hands you a card with the letters `G', `e', `o', `r', `g', and `e'
1908written on it, you might be amused, but you would not be satisfied.
1909You do not want to speak to the name, but to the person to whom the
1910name refers. A buffer is similar: the name of the scratch buffer is
1911`*scratch*', but the name is not the buffer. To get a buffer itself,
1912you need to use a function such as `current-buffer'.
1913
1914However, there is a slight complication: if you evaluate
1915`current-buffer' in an expression on its own, as we will do here,
1916what you see is a printed representation of the name of the buffer
1917without the contents of the buffer. Emacs works this way for two
1918reasons: the buffer may be thousands of lines long--too long to be
1919conveniently displayed; and, another buffer may have the same contents
1920but a different name, and it is important to distinguish between them.
1921
1922Here is an expression containing the function:
1923
1924 (current-buffer)
1925
1926If you evaluate the expression in the usual way, `#<buffer *info*>'
1927appears in the echo area. The special format indicates that the
1928buffer itself is being returned, rather than just its name.
1929
1930Incidentally, while you can type a number or symbol into a program,
1931you cannot do that with the printed representation of a buffer: the
1932only way to get a buffer itself is with a function such as
1933`current-buffer'.
1934
1935A related function is `other-buffer'. This returns the most recently
1936selected buffer other than the one you are in currently. If you have
1937recently switched back and forth from the `*scratch*' buffer,
1938`other-buffer' will return that buffer.
1939
1940You can see this by evaluating the expression:
1941
1942 (other-buffer)
1943
1944You should see `#<buffer *scratch*>' appear in the echo area, or the
1945name of whatever other buffer you switched back from most recently(1).
1946
1947---------- Footnotes ----------
1948
1949(1) Actually, by default, if the buffer from which you just switched
1950is visible to you in another window, `other-buffer' will choose the
1951most recent buffer that you cannot see; this is a subtlety that I
1952often forget.
1953
1954Switching Buffers
1955=================
1956
1957The `other-buffer' function actually provides a buffer when it is
1958used as an argument to a function that requires one. We can see this
1959by using `other-buffer' and `switch-to-buffer' to switch to a
1960different buffer.
1961
1962But first, a brief introduction to the `switch-to-buffer' function.
1963When you switched back and forth from Info to the `*scratch*' buffer
1964to evaluate `(buffer-name)', you most likely typed `C-x b' and then
1965typed `*scratch*'(1) when prompted in the minibuffer for the name of
1966the buffer to which you wanted to switch. The keystrokes, `C-x b',
1967cause the Lisp interpreter to evaluate the interactive function
1968`switch-to-buffer'. As we said before, this is how Emacs works:
1969different keystrokes call or run different functions. For example,
1970`C-f' calls `forward-char', `M-e' calls `forward-sentence', and so on.
1971
1972By writing `switch-to-buffer' in an expression, and giving it a
1973buffer to switch to, we can switch buffers just the way `C-x b' does.
1974
1975Here is the Lisp expression:
1976
1977 (switch-to-buffer (other-buffer))
1978
1979The symbol `switch-to-buffer' is the first element of the list, so
1980the Lisp interpreter will treat it as a function and carry out the
1981instructions that are attached to it. But before doing that, the
1982interpreter will note that `other-buffer' is inside parentheses and
1983work on that symbol first. `other-buffer' is the first (and in this
1984case, the only) element of this list, so the Lisp interpreter calls
1985or runs the function. It returns another buffer. Next, the
1986interpreter runs `switch-to-buffer', passing to it, as an argument,
1987the other buffer, which is what Emacs will switch to. If you are
1988reading this in Info, try this now. Evaluate the expression. (To
1989get back, type `C-x b <RET>'.)(2)
1990
1991In the programming examples in later sections of this document, you
1992will see the function `set-buffer' more often than
1993`switch-to-buffer'. This is because of a difference between computer
1994programs and humans: humans have eyes and expect to see the buffer on
1995which they are working on their computer terminals. This is so
1996obvious, it almost goes without saying. However, programs do not
1997have eyes. When a computer program works on a buffer, that buffer
1998does not need to be visible on the screen.
1999
2000`switch-to-buffer' is designed for humans and does two different
2001things: it switches the buffer to which Emacs' attention is directed;
2002and it switches the buffer displayed in the window to the new buffer.
2003`set-buffer', on the other hand, does only one thing: it switches the
2004attention of the computer program to a different buffer. The buffer
2005on the screen remains unchanged (of course, normally nothing happens
2006there until the command finishes running).
2007
2008Also, we have just introduced another jargon term, the word "call".
2009When you evaluate a list in which the first symbol is a function, you
2010are calling that function. The use of the term comes from the notion
2011of the function as an entity that can do something for you if you
2012`call' it--just as a plumber is an entity who can fix a leak if you
2013call him or her.
2014
2015---------- Footnotes ----------
2016
2017(1) Or rather, to save typing, you probably typed just part of the
2018name, such as `*sc', and then pressed your `TAB' key to cause it to
2019expand to the full name; and then typed your `RET' key.
2020
2021(2) Remember, this expression will move you to your most recent other
2022buffer that you cannot see. If you really want to go to your most
2023recently selected buffer, even if you can still see it, you need to
2024evaluate the following more complex expression:
2025
2026 (switch-to-buffer (other-buffer (current-buffer) t))
2027
2028In this case, the first argument to `other-buffer' tells it which
2029buffer to skip--the current one--and the second argument tells
2030`other-buffer' it is OK to switch to a visible buffer. In regular
2031use, `switch-to-buffer' takes you to an invisible window since you
2032would most likely use `C-x o' (`other-window') to go to another
2033visible buffer.
2034
2035Buffer Size and the Location of Point
2036=====================================
2037
2038Finally, let's look at several rather simple functions,
2039`buffer-size', `point', `point-min', and `point-max'. These give
2040information about the size of a buffer and the location of point
2041within it.
2042
2043The function `buffer-size' tells you the size of the current buffer;
2044that is, the function returns a count of the number of characters in
2045the buffer.
2046
2047 (buffer-size)
2048
2049You can evaluate this in the usual way, by positioning the cursor
2050after the expression and typing `C-x C-e'.
2051
2052In Emacs, the current position of the cursor is called "point". The
2053expression `(point)' returns a number that tells you where the cursor
2054is located as a count of the number of characters from the beginning
2055of the buffer up to point.
2056
2057You can see the character count for point in this buffer by evaluating
2058the following expression in the usual way:
2059
2060 (point)
2061
2062As I write this, the value of `point' is 65724. The `point' function
2063is frequently used in some of the examples later in this book.
2064
2065The value of point depends, of course, on its location within the
2066buffer. If you evaluate point in this spot, the number will be
2067larger:
2068
2069 (point)
2070
2071For me, the value of point in this location is 66043, which means that
2072there are 319 characters (including spaces) between the two
2073expressions.
2074
2075The function `point-min' is somewhat similar to `point', but it
2076returns the value of the minimum permissible value of point in the
2077current buffer. This is the number 1 unless "narrowing" is in
2078effect. (Narrowing is a mechanism whereby you can restrict yourself,
2079or a program, to operations on just a part of a buffer. *Note
2080Narrowing and Widening: Narrowing & Widening.) Likewise, the
2081function `point-max' returns the value of the maximum permissible
2082value of point in the current buffer.
2083
2084Exercise
2085========
2086
2087Find a file with which you are working and move towards its middle.
2088Find its buffer name, file name, length, and your position in the
2089file.
2090
2091How To Write Function Definitions
2092*********************************
2093
2094When the Lisp interpreter evaluates a list, it looks to see whether
2095the first symbol on the list has a function definition attached to
2096it; or, put another way, whether the symbol points to a function
2097definition. If it does, the computer carries out the instructions in
2098the definition. A symbol that has a function definition is called,
2099simply, a function (although, properly speaking, the definition is
2100the function and the symbol refers to it.)
2101
2102An Aside about Primitive Functions
2103==================================
2104
2105All functions are defined in terms of other functions, except for a
2106few "primitive" functions that are written in the C programming
2107language. When you write functions' definitions, you will write them
2108in Emacs Lisp and use other functions as your building blocks. Some
2109of the functions you will use will themselves be written in Emacs
2110Lisp (perhaps by you) and some will be primitives written in C. The
2111primitive functions are used exactly like those written in Emacs Lisp
2112and behave like them. They are written in C so we can easily run GNU
2113Emacs on any computer that has sufficient power and can run C.
2114
2115Let me re-emphasize this: when you write code in Emacs Lisp, you do
2116not distinguish between the use of functions written in C and the use
2117of functions written in Emacs Lisp. The difference is irrelevant. I
2118mention the distinction only because it is interesting to know.
2119Indeed, unless you investigate, you won't know whether an
2120already-written function is written in Emacs Lisp or C.
2121
2122The `defun' Special Form
2123========================
2124
2125In Lisp, a symbol such as `mark-whole-buffer' has code attached to it
2126that tells the computer what to do when the function is called. This
2127code is called the "function definition" and is created by evaluating
2128a Lisp expression that starts with the symbol `defun' (which is an
2129abbreviation for _define function_). Because `defun' does not
2130evaluate its arguments in the usual way, it is called a "special
2131form".
2132
2133In subsequent sections, we will look at function definitions from the
2134Emacs source code, such as `mark-whole-buffer'. In this section, we
2135will describe a simple function definition so you can see how it
2136looks. This function definition uses arithmetic because it makes for
2137a simple example. Some people dislike examples using arithmetic;
2138however, if you are such a person, do not despair. Hardly any of the
2139code we will study in the remainder of this introduction involves
2140arithmetic or mathematics. The examples mostly involve text in one
2141way or another.
2142
2143A function definition has up to five parts following the word `defun':
2144
2145 1. The name of the symbol to which the function definition should be
2146 attached.
2147
2148 2. A list of the arguments that will be passed to the function. If
2149 no arguments will be passed to the function, this is an empty
2150 list, `()'.
2151
2152 3. Documentation describing the function. (Technically optional,
2153 but strongly recommended.)
2154
2155 4. Optionally, an expression to make the function interactive so
2156 you can use it by typing `M-x' and then the name of the
2157 function; or by typing an appropriate key or keychord.
2158
2159 5. The code that instructs the computer what to do: the "body" of
2160 the function definition.
2161
2162It is helpful to think of the five parts of a function definition as
2163being organized in a template, with slots for each part:
2164
2165 (defun FUNCTION-NAME (ARGUMENTS...)
2166 "OPTIONAL-DOCUMENTATION..."
2167 (interactive ARGUMENT-PASSING-INFO) ; optional
2168 BODY...)
2169
2170As an example, here is the code for a function that multiplies its
2171argument by 7. (This example is not interactive. *Note Making a
2172Function Interactive: Interactive, for that information.)
2173
2174 (defun multiply-by-seven (number)
2175 "Multiply NUMBER by seven."
2176 (* 7 number))
2177
2178This definition begins with a parenthesis and the symbol `defun',
2179followed by the name of the function.
2180
2181The name of the function is followed by a list that contains the
2182arguments that will be passed to the function. This list is called
2183the "argument list". In this example, the list has only one element,
2184the symbol, `number'. When the function is used, the symbol will be
2185bound to the value that is used as the argument to the function.
2186
2187Instead of choosing the word `number' for the name of the argument, I
2188could have picked any other name. For example, I could have chosen
2189the word `multiplicand'. I picked the word `number' because it tells
2190what kind of value is intended for this slot; but I could just as
2191well have chosen the word `multiplicand' to indicate the role that the
2192value placed in this slot will play in the workings of the function.
2193I could have called it `foogle', but that would have been a bad
2194choice because it would not tell humans what it means. The choice of
2195name is up to the programmer and should be chosen to make the meaning
2196of the function clear.
2197
2198Indeed, you can choose any name you wish for a symbol in an argument
2199list, even the name of a symbol used in some other function: the name
2200you use in an argument list is private to that particular definition.
2201In that definition, the name refers to a different entity than any use
2202of the same name outside the function definition. Suppose you have a
2203nick-name `Shorty' in your family; when your family members refer to
2204`Shorty', they mean you. But outside your family, in a movie, for
2205example, the name `Shorty' refers to someone else. Because a name in
2206an argument list is private to the function definition, you can
2207change the value of such a symbol inside the body of a function
2208without changing its value outside the function. The effect is
2209similar to that produced by a `let' expression. (*Note `let': let.)
2210
2211The argument list is followed by the documentation string that
2212describes the function. This is what you see when you type `C-h f'
2213and the name of a function. Incidentally, when you write a
2214documentation string like this, you should make the first line a
2215complete sentence since some commands, such as `apropos', print only
2216the first line of a multi-line documentation string. Also, you
2217should not indent the second line of a documentation string, if you
2218have one, because that looks odd when you use `C-h f'
2219(`describe-function'). The documentation string is optional, but it
2220is so useful, it should be included in almost every function you
2221write.
2222
2223The third line of the example consists of the body of the function
2224definition. (Most functions' definitions, of course, are longer than
2225this.) In this function, the body is the list, `(* 7 number)', which
2226says to multiply the value of NUMBER by 7. (In Emacs Lisp, `*' is
2227the function for multiplication, just as `+' is the function for
2228addition.)
2229
2230When you use the `multiply-by-seven' function, the argument `number'
2231evaluates to the actual number you want used. Here is an example
2232that shows how `multiply-by-seven' is used; but don't try to evaluate
2233this yet!
2234
2235 (multiply-by-seven 3)
2236
2237The symbol `number', specified in the function definition in the next
2238section, is given or "bound to" the value 3 in the actual use of the
2239function. Note that although `number' was inside parentheses in the
2240function definition, the argument passed to the `multiply-by-seven'
2241function is not in parentheses. The parentheses are written in the
2242function definition so the computer can figure out where the argument
2243list ends and the rest of the function definition begins.
2244
2245If you evaluate this example, you are likely to get an error message.
2246(Go ahead, try it!) This is because we have written the function
2247definition, but not yet told the computer about the definition--we
2248have not yet installed (or `loaded') the function definition in Emacs.
2249Installing a function is the process that tells the Lisp interpreter
2250the definition of the function. Installation is described in the next
2251section.
2252
2253Install a Function Definition
2254=============================
2255
2256If you are reading this inside of Info in Emacs, you can try out the
2257`multiply-by-seven' function by first evaluating the function
2258definition and then evaluating `(multiply-by-seven 3)'. A copy of
2259the function definition follows. Place the cursor after the last
2260parenthesis of the function definition and type `C-x C-e'. When you
2261do this, `multiply-by-seven' will appear in the echo area. (What
2262this means is that when a function definition is evaluated, the value
2263it returns is the name of the defined function.) At the same time,
2264this action installs the function definition.
2265
2266 (defun multiply-by-seven (number)
2267 "Multiply NUMBER by seven."
2268 (* 7 number))
2269
2270By evaluating this `defun', you have just installed
2271`multiply-by-seven' in Emacs. The function is now just as much a
2272part of Emacs as `forward-word' or any other editing function you
2273use. (`multiply-by-seven' will stay installed until you quit Emacs.
2274To reload code automatically whenever you start Emacs, see *Note
2275Installing Code Permanently: Permanent Installation.)
2276
2277The effect of installation
2278--------------------------
2279
2280You can see the effect of installing `multiply-by-seven' by
2281evaluating the following sample. Place the cursor after the following
2282expression and type `C-x C-e'. The number 21 will appear in the echo
2283area.
2284
2285 (multiply-by-seven 3)
2286
2287If you wish, you can read the documentation for the function by typing
2288`C-h f' (`describe-function') and then the name of the function,
2289`multiply-by-seven'. When you do this, a `*Help*' window will appear
2290on your screen that says:
2291
2292 multiply-by-seven:
2293 Multiply NUMBER by seven.
2294
2295(To return to a single window on your screen, type `C-x 1'.)
2296
2297Change a Function Definition
2298----------------------------
2299
2300If you want to change the code in `multiply-by-seven', just rewrite
2301it. To install the new version in place of the old one, evaluate the
2302function definition again. This is how you modify code in Emacs. It
2303is very simple.
2304
2305As an example, you can change the `multiply-by-seven' function to add
2306the number to itself seven times instead of multiplying the number by
2307seven. It produces the same answer, but by a different path. At the
2308same time, we will add a comment to the code; a comment is text that
2309the Lisp interpreter ignores, but that a human reader may find useful
2310or enlightening. The comment is that this is the "second version".
2311
2312 (defun multiply-by-seven (number) ; Second version.
2313 "Multiply NUMBER by seven."
2314 (+ number number number number number number number))
2315
2316The comment follows a semicolon, `;'. In Lisp, everything on a line
2317that follows a semicolon is a comment. The end of the line is the
2318end of the comment. To stretch a comment over two or more lines,
2319begin each line with a semicolon.
2320
2321*Note Beginning a `.emacs' File: Beginning a .emacs File, and *Note
2322Comments: (elisp)Comments, for more about comments.
2323
2324You can install this version of the `multiply-by-seven' function by
2325evaluating it in the same way you evaluated the first function: place
2326the cursor after the last parenthesis and type `C-x C-e'.
2327
2328In summary, this is how you write code in Emacs Lisp: you write a
2329function; install it; test it; and then make fixes or enhancements and
2330install it again.
2331
2332Make a Function Interactive
2333===========================
2334
2335You make a function interactive by placing a list that begins with
2336the special form `interactive' immediately after the documentation.
2337A user can invoke an interactive function by typing `M-x' and then
2338the name of the function; or by typing the keys to which it is bound,
2339for example, by typing `C-n' for `next-line' or `C-x h' for
2340`mark-whole-buffer'.
2341
2342Interestingly, when you call an interactive function interactively,
2343the value returned is not automatically displayed in the echo area.
2344This is because you often call an interactive function for its side
2345effects, such as moving forward by a word or line, and not for the
2346value returned. If the returned value were displayed in the echo area
2347each time you typed a key, it would be very distracting.
2348
2349An Interactive `multiply-by-seven', An Overview
2350-----------------------------------------------
2351
2352Both the use of the special form `interactive' and one way to display
2353a value in the echo area can be illustrated by creating an
2354interactive version of `multiply-by-seven'.
2355
2356Here is the code:
2357
2358 (defun multiply-by-seven (number) ; Interactive version.
2359 "Multiply NUMBER by seven."
2360 (interactive "p")
2361 (message "The result is %d" (* 7 number)))
2362
2363You can install this code by placing your cursor after it and typing
2364`C-x C-e'. The name of the function will appear in your echo area.
2365Then, you can use this code by typing `C-u' and a number and then
2366typing `M-x multiply-by-seven' and pressing <RET>. The phrase `The
2367result is ...' followed by the product will appear in the echo area.
2368
2369Speaking more generally, you invoke a function like this in either of
2370two ways:
2371
2372 1. By typing a prefix argument that contains the number to be
2373 passed, and then typing `M-x' and the name of the function, as
2374 with `C-u 3 M-x forward-sentence'; or,
2375
2376 2. By typing whatever key or keychord the function is bound to, as
2377 with `C-u 3 M-e'.
2378
2379Both the examples just mentioned work identically to move point
2380forward three sentences. (Since `multiply-by-seven' is not bound to
2381a key, it could not be used as an example of key binding.)
2382
2383(*Note Some Keybindings: Keybindings, to learn how to bind a command
2384to a key.)
2385
2386A prefix argument is passed to an interactive function by typing the
2387<META> key followed by a number, for example, `M-3 M-e', or by typing
2388`C-u' and then a number, for example, `C-u 3 M-e' (if you type `C-u'
2389without a number, it defaults to 4).
2390
2391An Interactive `multiply-by-seven'
2392----------------------------------
2393
2394Let's look at the use of the special form `interactive' and then at
2395the function `message' in the interactive version of
2396`multiply-by-seven'. You will recall that the function definition
2397looks like this:
2398
2399 (defun multiply-by-seven (number) ; Interactive version.
2400 "Multiply NUMBER by seven."
2401 (interactive "p")
2402 (message "The result is %d" (* 7 number)))
2403
2404In this function, the expression, `(interactive "p")', is a list of
2405two elements. The `"p"' tells Emacs to pass the prefix argument to
2406the function and use its value for the argument of the function.
2407
2408The argument will be a number. This means that the symbol `number'
2409will be bound to a number in the line:
2410
2411 (message "The result is %d" (* 7 number))
2412
2413For example, if your prefix argument is 5, the Lisp interpreter will
2414evaluate the line as if it were:
2415
2416 (message "The result is %d" (* 7 5))
2417
2418(If you are reading this in GNU Emacs, you can evaluate this
2419expression yourself.) First, the interpreter will evaluate the inner
2420list, which is `(* 7 5)'. This returns a value of 35. Next, it will
2421evaluate the outer list, passing the values of the second and
2422subsequent elements of the list to the function `message'.
2423
2424As we have seen, `message' is an Emacs Lisp function especially
2425designed for sending a one line message to a user. (*Note The
2426`message' function: message.) In summary, the `message' function
2427prints its first argument in the echo area as is, except for
2428occurrences of `%d', `%s', or `%c'. When it sees one of these
2429control sequences, the function looks to the second and subsequent
2430arguments and prints the value of the argument in the location in the
2431string where the control sequence is located.
2432
2433In the interactive `multiply-by-seven' function, the control string
2434is `%d', which requires a number, and the value returned by
2435evaluating `(* 7 5)' is the number 35. Consequently, the number 35
2436is printed in place of the `%d' and the message is `The result is 35'.
2437
2438(Note that when you call the function `multiply-by-seven', the
2439message is printed without quotes, but when you call `message', the
2440text is printed in double quotes. This is because the value returned
2441by `message' is what appears in the echo area when you evaluate an
2442expression whose first element is `message'; but when embedded in a
2443function, `message' prints the text as a side effect without quotes.)
2444
2445Different Options for `interactive'
2446===================================
2447
2448In the example, `multiply-by-seven' used `"p"' as the argument to
2449`interactive'. This argument told Emacs to interpret your typing
2450either `C-u' followed by a number or <META> followed by a number as a
2451command to pass that number to the function as its argument. Emacs
2452has more than twenty characters predefined for use with
2453`interactive'. In almost every case, one of these options will
2454enable you to pass the right information interactively to a function.
2455(*Note Code Characters for `interactive': (elisp)Interactive Codes.)
2456
2457For example, the character `r' causes Emacs to pass the beginning and
2458end of the region (the current values of point and mark) to the
2459function as two separate arguments. It is used as follows:
2460
2461 (interactive "r")
2462
2463On the other hand, a `B' tells Emacs to ask for the name of a buffer
2464that will be passed to the function. When it sees a `B', Emacs will
2465ask for the name by prompting the user in the minibuffer, using a
2466string that follows the `B', as in `"BAppend to buffer: "'. Not only
2467will Emacs prompt for the name, but Emacs will complete the name if
2468you type enough of it and press <TAB>.
2469
2470A function with two or more arguments can have information passed to
2471each argument by adding parts to the string that follows
2472`interactive'. When you do this, the information is passed to each
2473argument in the same order it is specified in the `interactive' list.
2474In the string, each part is separated from the next part by a `\n',
2475which is a newline. For example, you could follow `"BAppend to
2476buffer: "' with a `\n') and an `r'. This would cause Emacs to pass
2477the values of point and mark to the function as well as prompt you
2478for the buffer--three arguments in all.
2479
2480In this case, the function definition would look like the following,
2481where `buffer', `start', and `end' are the symbols to which
2482`interactive' binds the buffer and the current values of the
2483beginning and ending of the region:
2484
2485 (defun NAME-OF-FUNCTION (buffer start end)
2486 "DOCUMENTATION..."
2487 (interactive "BAppend to buffer: \nr")
2488 BODY-OF-FUNCTION...)
2489
2490(The space after the colon in the prompt makes it look better when you
2491are prompted. The `append-to-buffer' function looks exactly like
2492this. *Note The Definition of `append-to-buffer': append-to-buffer.)
2493
2494If a function does not have arguments, then `interactive' does not
2495require any. Such a function contains the simple expression
2496`(interactive)'. The `mark-whole-buffer' function is like this.
2497
2498Alternatively, if the special letter-codes are not right for your
2499application, you can pass your own arguments to `interactive' as a
2500list. *Note Using `Interactive': (elisp)interactive, for more
2501information about this advanced technique.
2502
2503Install Code Permanently
2504========================
2505
2506When you install a function definition by evaluating it, it will stay
2507installed until you quit Emacs. The next time you start a new session
2508of Emacs, the function will not be installed unless you evaluate the
2509function definition again.
2510
2511At some point, you may want to have code installed automatically
2512whenever you start a new session of Emacs. There are several ways of
2513doing this:
2514
2515 * If you have code that is just for yourself, you can put the code
2516 for the function definition in your `.emacs' initialization
2517 file. When you start Emacs, your `.emacs' file is automatically
2518 evaluated and all the function definitions within it are
2519 installed. *Note Your `.emacs' File: Emacs Initialization.
2520
2521 * Alternatively, you can put the function definitions that you want
2522 installed in one or more files of their own and use the `load'
2523 function to cause Emacs to evaluate and thereby install each of
2524 the functions in the files. *Note Loading Files: Loading Files.
2525
2526 * On the other hand, if you have code that your whole site will
2527 use, it is usual to put it in a file called `site-init.el' that
2528 is loaded when Emacs is built. This makes the code available to
2529 everyone who uses your machine. (See the `INSTALL' file that is
2530 part of the Emacs distribution.)
2531
2532Finally, if you have code that everyone who uses Emacs may want, you
2533can post it on a computer network or send a copy to the Free Software
2534Foundation. (When you do this, please license the code and its
2535documentation under a license that permits other people to run, copy,
2536study, modify, and redistribute the code and which protects you from
2537having your work taken from you.) If you send a copy of your code to
2538the Free Software Foundation, and properly protect yourself and
2539others, it may be included in the next release of Emacs. In large
2540part, this is how Emacs has grown over the past years, by donations.
2541
2542`let'
2543=====
2544
2545The `let' expression is a special form in Lisp that you will need to
2546use in most function definitions.
2547
2548`let' is used to attach or bind a symbol to a value in such a way
2549that the Lisp interpreter will not confuse the variable with a
2550variable of the same name that is not part of the function.
2551
2552To understand why the `let' special form is necessary, consider the
2553situation in which you own a home that you generally refer to as `the
2554house', as in the sentence, "The house needs painting." If you are
2555visiting a friend and your host refers to `the house', he is likely
2556to be referring to _his_ house, not yours, that is, to a different
2557house.
2558
2559If your friend is referring to his house and you think he is referring
2560to your house, you may be in for some confusion. The same thing could
2561happen in Lisp if a variable that is used inside of one function has
2562the same name as a variable that is used inside of another function,
2563and the two are not intended to refer to the same value. The `let'
2564special form prevents this kind of confusion.
2565
2566`let' Prevents Confusion
2567------------------------
2568
2569The `let' special form prevents confusion. `let' creates a name for
2570a "local variable" that overshadows any use of the same name outside
2571the `let' expression. This is like understanding that whenever your
2572host refers to `the house', he means his house, not yours. (Symbols
2573used in argument lists work the same way. *Note The `defun' Special
2574Form: defun.)
2575
2576Local variables created by a `let' expression retain their value
2577_only_ within the `let' expression itself (and within expressions
2578called within the `let' expression); the local variables have no
2579effect outside the `let' expression.
2580
2581Another way to think about `let' is that it is like a `setq' that is
2582temporary and local. The values set by `let' are automatically
2583undone when the `let' is finished. The setting only affects
2584expressions that are inside the bounds of the `let' expression. In
2585computer science jargon, we would say "the binding of a symbol is
2586visible only in functions called in the `let' form; in Emacs Lisp,
2587scoping is dynamic, not lexical."
2588
2589`let' can create more than one variable at once. Also, `let' gives
2590each variable it creates an initial value, either a value specified
2591by you, or `nil'. (In the jargon, this is called `binding the
2592variable to the value'.) After `let' has created and bound the
2593variables, it executes the code in the body of the `let', and returns
2594the value of the last expression in the body, as the value of the
2595whole `let' expression. (`Execute' is a jargon term that means to
2596evaluate a list; it comes from the use of the word meaning `to give
2597practical effect to' (`Oxford English Dictionary'). Since you
2598evaluate an expression to perform an action, `execute' has evolved as
2599a synonym to `evaluate'.)
2600
2601The Parts of a `let' Expression
2602-------------------------------
2603
2604A `let' expression is a list of three parts. The first part is the
2605symbol `let'. The second part is a list, called a "varlist", each
2606element of which is either a symbol by itself or a two-element list,
2607the first element of which is a symbol. The third part of the `let'
2608expression is the body of the `let'. The body usually consists of
2609one or more lists.
2610
2611A template for a `let' expression looks like this:
2612
2613 (let VARLIST BODY...)
2614
2615The symbols in the varlist are the variables that are given initial
2616values by the `let' special form. Symbols by themselves are given
2617the initial value of `nil'; and each symbol that is the first element
2618of a two-element list is bound to the value that is returned when the
2619Lisp interpreter evaluates the second element.
2620
2621Thus, a varlist might look like this: `(thread (needles 3))'. In
2622this case, in a `let' expression, Emacs binds the symbol `thread' to
2623an initial value of `nil', and binds the symbol `needles' to an
2624initial value of 3.
2625
2626When you write a `let' expression, what you do is put the appropriate
2627expressions in the slots of the `let' expression template.
2628
2629If the varlist is composed of two-element lists, as is often the case,
2630the template for the `let' expression looks like this:
2631
2632 (let ((VARIABLE VALUE)
2633 (VARIABLE VALUE)
2634 ...)
2635 BODY...)
2636
2637Sample `let' Expression
2638-----------------------
2639
2640The following expression creates and gives initial values to the two
2641variables `zebra' and `tiger'. The body of the `let' expression is a
2642list which calls the `message' function.
2643
2644 (let ((zebra 'stripes)
2645 (tiger 'fierce))
2646 (message "One kind of animal has %s and another is %s."
2647 zebra tiger))
2648
2649Here, the varlist is `((zebra 'stripes) (tiger 'fierce))'.
2650
2651The two variables are `zebra' and `tiger'. Each variable is the
2652first element of a two-element list and each value is the second
2653element of its two-element list. In the varlist, Emacs binds the
2654variable `zebra' to the value `stripes', and binds the variable
2655`tiger' to the value `fierce'. In this example, both values are
2656symbols preceded by a quote. The values could just as well have been
2657another list or a string. The body of the `let' follows after the
2658list holding the variables. In this example, the body is a list that
2659uses the `message' function to print a string in the echo area.
2660
2661You may evaluate the example in the usual fashion, by placing the
2662cursor after the last parenthesis and typing `C-x C-e'. When you do
2663this, the following will appear in the echo area:
2664
2665 "One kind of animal has stripes and another is fierce."
2666
2667As we have seen before, the `message' function prints its first
2668argument, except for `%s'. In this example, the value of the variable
2669`zebra' is printed at the location of the first `%s' and the value of
2670the variable `tiger' is printed at the location of the second `%s'.
2671
2672Uninitialized Variables in a `let' Statement
2673--------------------------------------------
2674
2675If you do not bind the variables in a `let' statement to specific
2676initial values, they will automatically be bound to an initial value
2677of `nil', as in the following expression:
2678
2679 (let ((birch 3)
2680 pine
2681 fir
2682 (oak 'some))
2683 (message
2684 "Here are %d variables with %s, %s, and %s value."
2685 birch pine fir oak))
2686
2687Here, the varlist is `((birch 3) pine fir (oak 'some))'.
2688
2689If you evaluate this expression in the usual way, the following will
2690appear in your echo area:
2691
2692 "Here are 3 variables with nil, nil, and some value."
2693
2694In this example, Emacs binds the symbol `birch' to the number 3,
2695binds the symbols `pine' and `fir' to `nil', and binds the symbol
2696`oak' to the value `some'.
2697
2698Note that in the first part of the `let', the variables `pine' and
2699`fir' stand alone as atoms that are not surrounded by parentheses;
2700this is because they are being bound to `nil', the empty list. But
2701`oak' is bound to `some' and so is a part of the list `(oak 'some)'.
2702Similarly, `birch' is bound to the number 3 and so is in a list with
2703that number. (Since a number evaluates to itself, the number does
2704not need to be quoted. Also, the number is printed in the message
2705using a `%d' rather than a `%s'.) The four variables as a group are
2706put into a list to delimit them from the body of the `let'.
2707
2708The `if' Special Form
2709=====================
2710
2711A third special form, in addition to `defun' and `let', is the
2712conditional `if'. This form is used to instruct the computer to make
2713decisions. You can write function definitions without using `if',
2714but it is used often enough, and is important enough, to be included
2715here. It is used, for example, in the code for the function
2716`beginning-of-buffer'.
2717
2718The basic idea behind an `if', is that "_if_ a test is true, _then_
2719an expression is evaluated." If the test is not true, the expression
2720is not evaluated. For example, you might make a decision such as,
2721"if it is warm and sunny, then go to the beach!"
2722
2723`if' in more detail
2724-------------------
2725
2726An `if' expression written in Lisp does not use the word `then'; the
2727test and the action are the second and third elements of the list
2728whose first element is `if'. Nonetheless, the test part of an `if'
2729expression is often called the "if-part" and the second argument is
2730often called the "then-part".
2731
2732Also, when an `if' expression is written, the true-or-false-test is
2733usually written on the same line as the symbol `if', but the action
2734to carry out if the test is true, the "then-part", is written on the
2735second and subsequent lines. This makes the `if' expression easier
2736to read.
2737
2738 (if TRUE-OR-FALSE-TEST
2739 ACTION-TO-CARRY-OUT-IF-TEST-IS-TRUE)
2740
2741The true-or-false-test will be an expression that is evaluated by the
2742Lisp interpreter.
2743
2744Here is an example that you can evaluate in the usual manner. The
2745test is whether the number 5 is greater than the number 4. Since it
2746is, the message `5 is greater than 4!' will be printed.
2747
2748 (if (> 5 4) ; if-part
2749 (message "5 is greater than 4!")) ; then-part
2750
2751(The function `>' tests whether its first argument is greater than
2752its second argument and returns true if it is.)
2753
2754Of course, in actual use, the test in an `if' expression will not be
2755fixed for all time as it is by the expression `(> 5 4)'. Instead, at
2756least one of the variables used in the test will be bound to a value
2757that is not known ahead of time. (If the value were known ahead of
2758time, we would not need to run the test!)
2759
2760For example, the value may be bound to an argument of a function
2761definition. In the following function definition, the character of
2762the animal is a value that is passed to the function. If the value
2763bound to `characteristic' is `fierce', then the message, `It's a
2764tiger!' will be printed; otherwise, `nil' will be returned.
2765
2766 (defun type-of-animal (characteristic)
2767 "Print message in echo area depending on CHARACTERISTIC.
2768 If the CHARACTERISTIC is the symbol `fierce',
2769 then warn of a tiger."
2770 (if (equal characteristic 'fierce)
2771 (message "It's a tiger!")))
2772
2773If you are reading this inside of GNU Emacs, you can evaluate the
2774function definition in the usual way to install it in Emacs, and then
2775you can evaluate the following two expressions to see the results:
2776
2777 (type-of-animal 'fierce)
2778
2779 (type-of-animal 'zebra)
2780
2781When you evaluate `(type-of-animal 'fierce)', you will see the
2782following message printed in the echo area: `"It's a tiger!"'; and
2783when you evaluate `(type-of-animal 'zebra)' you will see `nil'
2784printed in the echo area.
2785
2786The `type-of-animal' Function in Detail
2787---------------------------------------
2788
2789Let's look at the `type-of-animal' function in detail.
2790
2791The function definition for `type-of-animal' was written by filling
2792the slots of two templates, one for a function definition as a whole,
2793and a second for an `if' expression.
2794
2795The template for every function that is not interactive is:
2796
2797 (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
2798 "DOCUMENTATION..."
2799 BODY...)
2800
2801The parts of the function that match this template look like this:
2802
2803 (defun type-of-animal (characteristic)
2804 "Print message in echo area depending on CHARACTERISTIC.
2805 If the CHARACTERISTIC is the symbol `fierce',
2806 then warn of a tiger."
2807 BODY: THE `if' EXPRESSION)
2808
2809The name of function is `type-of-animal'; it is passed the value of
2810one argument. The argument list is followed by a multi-line
2811documentation string. The documentation string is included in the
2812example because it is a good habit to write documentation string for
2813every function definition. The body of the function definition
2814consists of the `if' expression.
2815
2816The template for an `if' expression looks like this:
2817
2818 (if TRUE-OR-FALSE-TEST
2819 ACTION-TO-CARRY-OUT-IF-THE-TEST-RETURNS-TRUE)
2820
2821In the `type-of-animal' function, the code for the `if' looks like
2822this:
2823
2824 (if (equal characteristic 'fierce)
2825 (message "It's a tiger!")))
2826
2827Here, the true-or-false-test is the expression:
2828
2829 (equal characteristic 'fierce)
2830
2831In Lisp, `equal' is a function that determines whether its first
2832argument is equal to its second argument. The second argument is the
2833quoted symbol `'fierce' and the first argument is the value of the
2834symbol `characteristic'--in other words, the argument passed to this
2835function.
2836
2837In the first exercise of `type-of-animal', the argument `fierce' is
2838passed to `type-of-animal'. Since `fierce' is equal to `fierce', the
2839expression, `(equal characteristic 'fierce)', returns a value of
2840true. When this happens, the `if' evaluates the second argument or
2841then-part of the `if': `(message "It's tiger!")'.
2842
2843On the other hand, in the second exercise of `type-of-animal', the
2844argument `zebra' is passed to `type-of-animal'. `zebra' is not equal
2845to `fierce', so the then-part is not evaluated and `nil' is returned
2846by the `if' expression.
2847
2848If-then-else Expressions
2849========================
2850
2851An `if' expression may have an optional third argument, called the
2852"else-part", for the case when the true-or-false-test returns false.
2853When this happens, the second argument or then-part of the overall
2854`if' expression is _not_ evaluated, but the third or else-part _is_
2855evaluated. You might think of this as the cloudy day alternative for
2856the decision `if it is warm and sunny, then go to the beach, else
2857read a book!".
2858
2859The word "else" is not written in the Lisp code; the else-part of an
2860`if' expression comes after the then-part. In the written Lisp, the
2861else-part is usually written to start on a line of its own and is
2862indented less than the then-part:
2863
2864 (if TRUE-OR-FALSE-TEST
2865 ACTION-TO-CARRY-OUT-IF-THE-TEST-RETURNS-TRUE
2866 ACTION-TO-CARRY-OUT-IF-THE-TEST-RETURNS-FALSE)
2867
2868For example, the following `if' expression prints the message `4 is
2869not greater than 5!' when you evaluate it in the usual way:
2870
2871 (if (> 4 5) ; if-part
2872 (message "5 is greater than 4!") ; then-part
2873 (message "4 is not greater than 5!")) ; else-part
2874
2875Note that the different levels of indentation make it easy to
2876distinguish the then-part from the else-part. (GNU Emacs has several
2877commands that automatically indent `if' expressions correctly. *Note
2878GNU Emacs Helps You Type Lists: Typing Lists.)
2879
2880We can extend the `type-of-animal' function to include an else-part
2881by simply incorporating an additional part to the `if' expression.
2882
2883You can see the consequences of doing this if you evaluate the
2884following version of the `type-of-animal' function definition to
2885install it and then evaluate the two subsequent expressions to pass
2886different arguments to the function.
2887
2888 (defun type-of-animal (characteristic) ; Second version.
2889 "Print message in echo area depending on CHARACTERISTIC.
2890 If the CHARACTERISTIC is the symbol `fierce',
2891 then warn of a tiger;
2892 else say it's not fierce."
2893 (if (equal characteristic 'fierce)
2894 (message "It's a tiger!")
2895 (message "It's not fierce!")))
2896
2897
2898 (type-of-animal 'fierce)
2899
2900 (type-of-animal 'zebra)
2901
2902When you evaluate `(type-of-animal 'fierce)', you will see the
2903following message printed in the echo area: `"It's a tiger!"'; but
2904when you evaluate `(type-of-animal 'zebra)', you will see `"It's not
2905fierce!"'.
2906
2907(Of course, if the CHARACTERISTIC were `ferocious', the message
2908`"It's not fierce!"' would be printed; and it would be misleading!
2909When you write code, you need to take into account the possibility
2910that some such argument will be tested by the `if' and write your
2911program accordingly.)
2912
2913Truth and Falsehood in Emacs Lisp
2914=================================
2915
2916There is an important aspect to the truth test in an `if' expression.
2917So far, we have spoken of `true' and `false' as values of predicates
2918as if they were new kinds of Emacs Lisp objects. In fact, `false' is
2919just our old friend `nil'. Anything else--anything at all--is `true'.
2920
2921The expression that tests for truth is interpreted as "true" if the
2922result of evaluating it is a value that is not `nil'. In other
2923words, the result of the test is considered true if the value
2924returned is a number such as 47, a string such as `"hello"', or a
2925symbol (other than `nil') such as `flowers', or a list, or even a
2926buffer!
2927
2928An explanation of `nil'
2929-----------------------
2930
2931Before illustrating a test for truth, we need an explanation of `nil'.
2932
2933In Emacs Lisp, the symbol `nil' has two meanings. First, it means the
2934empty list. Second, it means false and is the value returned when a
2935true-or-false-test tests false. `nil' can be written as an empty
2936list, `()', or as `nil'. As far as the Lisp interpreter is
2937concerned, `()' and `nil' are the same. Humans, however, tend to use
2938`nil' for false and `()' for the empty list.
2939
2940In Emacs Lisp, any value that is not `nil'--is not the empty list--is
2941considered true. This means that if an evaluation returns something
2942that is not an empty list, an `if' expression will test true. For
2943example, if a number is put in the slot for the test, it will be
2944evaluated and will return itself, since that is what numbers do when
2945evaluated. In this conditional, the `if' expression will test true.
2946The expression tests false only when `nil', an empty list, is
2947returned by evaluating the expression.
2948
2949You can see this by evaluating the two expressions in the following
2950examples.
2951
2952In the first example, the number 4 is evaluated as the test in the
2953`if' expression and returns itself; consequently, the then-part of
2954the expression is evaluated and returned: `true' appears in the echo
2955area. In the second example, the `nil' indicates false;
2956consequently, the else-part of the expression is evaluated and
2957returned: `false' appears in the echo area.
2958
2959 (if 4
2960 'true
2961 'false)
2962
2963 (if nil
2964 'true
2965 'false)
2966
2967Incidentally, if some other useful value is not available for a test
2968that returns true, then the Lisp interpreter will return the symbol
2969`t' for true. For example, the expression `(> 5 4)' returns `t' when
2970evaluated, as you can see by evaluating it in the usual way:
2971
2972 (> 5 4)
2973
2974On the other hand, this function returns `nil' if the test is false.
2975
2976 (> 4 5)
2977
2978`save-excursion'
2979================
2980
2981The `save-excursion' function is the fourth and final special form
2982that we will discuss in this chapter.
2983
2984In Emacs Lisp programs used for editing, the `save-excursion'
2985function is very common. It saves the location of point and mark,
2986executes the body of the function, and then restores point and mark to
2987their previous positions if their locations were changed. Its primary
2988purpose is to keep the user from being surprised and disturbed by
2989unexpected movement of point or mark.
2990
2991Point and Mark
2992--------------
2993
2994Before discussing `save-excursion', however, it may be useful first
2995to review what point and mark are in GNU Emacs. "Point" is the
2996current location of the cursor. Wherever the cursor is, that is
2997point. More precisely, on terminals where the cursor appears to be
2998on top of a character, point is immediately before the character. In
2999Emacs Lisp, point is an integer. The first character in a buffer is
3000number one, the second is number two, and so on. The function
3001`point' returns the current position of the cursor as a number. Each
3002buffer has its own value for point.
3003
3004The "mark" is another position in the buffer; its value can be set
3005with a command such as `C-<SPC>' (`set-mark-command'). If a mark has
3006been set, you can use the command `C-x C-x'
3007(`exchange-point-and-mark') to cause the cursor to jump to the mark
3008and set the mark to be the previous position of point. In addition,
3009if you set another mark, the position of the previous mark is saved
3010in the mark ring. Many mark positions can be saved this way. You
3011can jump the cursor to a saved mark by typing `C-u C-<SPC>' one or
3012more times.
3013
3014The part of the buffer between point and mark is called "the region".
3015Numerous commands work on the region, including `center-region',
3016`count-lines-region', `kill-region', and `print-region'.
3017
3018The `save-excursion' special form saves the locations of point and
3019mark and restores those positions after the code within the body of
3020the special form is evaluated by the Lisp interpreter. Thus, if
3021point were in the beginning of a piece of text and some code moved
3022point to the end of the buffer, the `save-excursion' would put point
3023back to where it was before, after the expressions in the body of the
3024function were evaluated.
3025
3026In Emacs, a function frequently moves point as part of its internal
3027workings even though a user would not expect this. For example,
3028`count-lines-region' moves point. To prevent the user from being
3029bothered by jumps that are both unexpected and (from the user's point
3030of view) unnecessary, `save-excursion' is often used to keep point and
3031mark in the location expected by the user. The use of
3032`save-excursion' is good housekeeping.
3033
3034To make sure the house stays clean, `save-excursion' restores the
3035values of point and mark even if something goes wrong in the code
3036inside of it (or, to be more precise and to use the proper jargon,
3037"in case of abnormal exit"). This feature is very helpful.
3038
3039In addition to recording the values of point and mark,
3040`save-excursion' keeps track of the current buffer, and restores it,
3041too. This means you can write code that will change the buffer and
3042have `save-excursion' switch you back to the original buffer. This
3043is how `save-excursion' is used in `append-to-buffer'. (*Note The
3044Definition of `append-to-buffer': append-to-buffer.)
3045
3046Template for a `save-excursion' Expression
3047------------------------------------------
3048
3049The template for code using `save-excursion' is simple:
3050
3051 (save-excursion
3052 BODY...)
3053
3054The body of the function is one or more expressions that will be
3055evaluated in sequence by the Lisp interpreter. If there is more than
3056one expression in the body, the value of the last one will be returned
3057as the value of the `save-excursion' function. The other expressions
3058in the body are evaluated only for their side effects; and
3059`save-excursion' itself is used only for its side effect (which is
3060restoring the positions of point and mark).
3061
3062In more detail, the template for a `save-excursion' expression looks
3063like this:
3064
3065 (save-excursion
3066 FIRST-EXPRESSION-IN-BODY
3067 SECOND-EXPRESSION-IN-BODY
3068 THIRD-EXPRESSION-IN-BODY
3069 ...
3070 LAST-EXPRESSION-IN-BODY)
3071
3072An expression, of course, may be a symbol on its own or a list.
3073
3074In Emacs Lisp code, a `save-excursion' expression often occurs within
3075the body of a `let' expression. It looks like this:
3076
3077 (let VARLIST
3078 (save-excursion
3079 BODY...))
3080
3081Review
3082======
3083
3084In the last few chapters we have introduced a fair number of functions
3085and special forms. Here they are described in brief, along with a few
3086similar functions that have not been mentioned yet.
3087
3088`eval-last-sexp'
3089 Evaluate the last symbolic expression before the current
3090 location of point. The value is printed in the echo area unless
3091 the function is invoked with an argument; in that case, the
3092 output is printed in the current buffer. This command is
3093 normally bound to `C-x C-e'.
3094
3095`defun'
3096 Define function. This special form has up to five parts: the
3097 name, a template for the arguments that will be passed to the
3098 function, documentation, an optional interactive declaration,
3099 and the body of the definition.
3100
3101 For example:
3102
3103 (defun back-to-indentation ()
3104 "Move point to first visible character on line."
3105 (interactive)
3106 (beginning-of-line 1)
3107 (skip-chars-forward " \t"))
3108
3109`interactive'
3110 Declare to the interpreter that the function can be used
3111 interactively. This special form may be followed by a string
3112 with one or more parts that pass the information to the
3113 arguments of the function, in sequence. These parts may also
3114 tell the interpreter to prompt for information. Parts of the
3115 string are separated by newlines, `\n'.
3116
3117 Common code characters are:
3118
3119 `b'
3120 The name of an existing buffer.
3121
3122 `f'
3123 The name of an existing file.
3124
3125 `p'
3126 The numeric prefix argument. (Note that this `p' is lower
3127 case.)
3128
3129 `r'
3130 Point and the mark, as two numeric arguments, smallest
3131 first. This is the only code letter that specifies two
3132 successive arguments rather than one.
3133
3134 *Note Code Characters for `interactive': (elisp)Interactive
3135 Codes, for a complete list of code characters.
3136
3137`let'
3138 Declare that a list of variables is for use within the body of
3139 the `let' and give them an initial value, either `nil' or a
3140 specified value; then evaluate the rest of the expressions in
3141 the body of the `let' and return the value of the last one.
3142 Inside the body of the `let', the Lisp interpreter does not see
3143 the values of the variables of the same names that are bound
3144 outside of the `let'.
3145
3146 For example,
3147
3148 (let ((foo (buffer-name))
3149 (bar (buffer-size)))
3150 (message
3151 "This buffer is %s and has %d characters."
3152 foo bar))
3153
3154`save-excursion'
3155 Record the values of point and mark and the current buffer before
3156 evaluating the body of this special form. Restore the values of
3157 point and mark and buffer afterward.
3158
3159 For example,
3160
3161 (message "We are %d characters into this buffer."
3162 (- (point)
3163 (save-excursion
3164 (goto-char (point-min)) (point))))
3165
3166`if'
3167 Evaluate the first argument to the function; if it is true,
3168 evaluate the second argument; else evaluate the third argument,
3169 if there is one.
3170
3171 The `if' special form is called a "conditional". There are
3172 other conditionals in Emacs Lisp, but `if' is perhaps the most
3173 commonly used.
3174
3175 For example,
3176
3177 (if (string-equal
3178 (number-to-string 21)
3179 (substring (emacs-version) 10 12))
3180 (message "This is version 21 Emacs")
3181 (message "This is not version 21 Emacs"))
3182
3183`equal'
3184`eq'
3185 Test whether two objects are the same. `equal' uses one meaning
3186 of the word `same' and `eq' uses another: `equal' returns true
3187 if the two objects have a similar structure and contents, such as
3188 two copies of the same book. On the other hand, `eq', returns
3189 true if both arguments are actually the same object.
3190
3191`<'
3192`>'
3193`<='
3194`>='
3195 The `<' function tests whether its first argument is smaller than
3196 its second argument. A corresponding function, `>', tests
3197 whether the first argument is greater than the second.
3198 Likewise, `<=' tests whether the first argument is less than or
3199 equal to the second and `>=' tests whether the first argument is
3200 greater than or equal to the second. In all cases, both
3201 arguments must be numbers or markers (markers indicate positions
3202 in buffers).
3203
3204`string<'
3205`string-lessp'
3206`string='
3207`string-equal'
3208 The `string-lessp' function tests whether its first argument is
3209 smaller than the second argument. A shorter, alternative name
3210 for the same function (a `defalias') is `string<'.
3211
3212 The arguments to `string-lessp' must be strings or symbols; the
3213 ordering is lexicographic, so case is significant. The print
3214 names of symbols are used instead of the symbols themselves.
3215
3216 An empty string, `""', a string with no characters in it, is
3217 smaller than any string of characters.
3218
3219 `string-equal' provides the corresponding test for equality. Its
3220 shorter, alternative name is `string='. There are no string test
3221 functions that correspond to >, `>=', or `<='.
3222
3223`message'
3224 Print a message in the echo area. The first argument is a string
3225 that can contain `%s', `%d', or `%c' to print the value of
3226 arguments that follow the string. The argument used by `%s' must
3227 be a string or a symbol; the argument used by `%d' must be a
3228 number. The argument used by `%c' must be an ascii code number;
3229 it will be printed as the character with that ASCII code.
3230
3231`setq'
3232`set'
3233 The `setq' function sets the value of its first argument to the
3234 value of the second argument. The first argument is
3235 automatically quoted by `setq'. It does the same for succeeding
3236 pairs of arguments. Another function, `set', takes only two
3237 arguments and evaluates both of them before setting the value
3238 returned by its first argument to the value returned by its
3239 second argument.
3240
3241`buffer-name'
3242 Without an argument, return the name of the buffer, as a string.
3243
3244`buffer-file-name'
3245 Without an argument, return the name of the file the buffer is
3246 visiting.
3247
3248`current-buffer'
3249 Return the buffer in which Emacs is active; it may not be the
3250 buffer that is visible on the screen.
3251
3252`other-buffer'
3253 Return the most recently selected buffer (other than the buffer
3254 passed to `other-buffer' as an argument and other than the
3255 current buffer).
3256
3257`switch-to-buffer'
3258 Select a buffer for Emacs to be active in and display it in the
3259 current window so users can look at it. Usually bound to `C-x
3260 b'.
3261
3262`set-buffer'
3263 Switch Emacs' attention to a buffer on which programs will run.
3264 Don't alter what the window is showing.
3265
3266`buffer-size'
3267 Return the number of characters in the current buffer.
3268
3269`point'
3270 Return the value of the current position of the cursor, as an
3271 integer counting the number of characters from the beginning of
3272 the buffer.
3273
3274`point-min'
3275 Return the minimum permissible value of point in the current
3276 buffer. This is 1, unless narrowing is in effect.
3277
3278`point-max'
3279 Return the value of the maximum permissible value of point in the
3280 current buffer. This is the end of the buffer, unless narrowing
3281 is in effect.
3282
3283Exercises
3284=========
3285
3286 * Write a non-interactive function that doubles the value of its
3287 argument, a number. Make that function interactive.
3288
3289 * Write a function that tests whether the current value of
3290 `fill-column' is greater than the argument passed to the
3291 function, and if so, prints an appropriate message.
3292
3293A Few Buffer-Related Functions
3294******************************
3295
3296In this chapter we study in detail several of the functions used in
3297GNU Emacs. This is called a "walk-through". These functions are
3298used as examples of Lisp code, but are not imaginary examples; with
3299the exception of the first, simplified function definition, these
3300functions show the actual code used in GNU Emacs. You can learn a
3301great deal from these definitions. The functions described here are
3302all related to buffers. Later, we will study other functions.
3303
3304Finding More Information
3305========================
3306
3307In this walk-through, I will describe each new function as we come to
3308it, sometimes in detail and sometimes briefly. If you are interested,
3309you can get the full documentation of any Emacs Lisp function at any
3310time by typing `C-h f' and then the name of the function (and then
3311<RET>). Similarly, you can get the full documentation for a variable
3312by typing `C-h v' and then the name of the variable (and then <RET>).
3313
3314In versions 20 and higher, when a function is written in Emacs Lisp,
3315`describe-function' will also tell you the location of the function
3316definition. If you move point over the file name and press the <RET>
3317key, which is this case means `help-follow' rather than `return' or
3318`enter', Emacs will take you directly to the function definition.
3319
3320More generally, if you want to see a function in its original source
3321file, you can use the `find-tags' function to jump to it.
3322`find-tags' works with a wide variety of languages, not just Lisp,
3323and C, and it works with non-programming text as well. For example,
3324`find-tags' will jump to the various nodes in the Texinfo source file
3325of this document.
3326
3327The `find-tags' function depends on `tags tables' that record the
3328locations of the functions, variables, and other items to which
3329`find-tags' jumps.
3330
3331To use the `find-tags' command, type `M-.' (i.e., type the <META>
3332key and the period key at the same time, or else type the <ESC> key
3333and then type the period key), and then, at the prompt, type in the
3334name of the function whose source code you want to see, such as
3335`mark-whole-buffer', and then type <RET>. Emacs will switch buffers
3336and display the source code for the function on your screen. To
3337switch back to your current buffer, type `C-x b <RET>'. (On some
3338keyboards, the <META> key is labelled <ALT>.)
3339
3340Depending on how the initial default values of your copy of Emacs are
3341set, you may also need to specify the location of your `tags table',
3342which is a file called `TAGS'. For example, if you are interested in
3343Emacs sources, the tags table you will most likely want, if it has
3344already been created for you, will be in a subdirectory of the
3345`/usr/local/share/emacs/' directory; thus you would use the `M-x
3346visit-tags-table' command and specify a pathname such as
3347`/usr/local/share/emacs/21.0.100/lisp/TAGS' or
3348`/usr/local/src/emacs/lisp/TAGS'. If the tags table has not already
3349been created, you will have to create it yourself.
3350
3351To create a `TAGS' file in a specific directory, switch to that
3352directory in Emacs using `M-x cd' command, or list the directory with
3353`C-x d' (`dired'). Then run the compile command, with `etags *.el'
3354as the command to execute
3355
3356 M-x compile RET etags *.el RET
3357
3358For more information, see *Note Create Your Own `TAGS' File: etags.
3359
3360After you become more familiar with Emacs Lisp, you will find that
3361you will frequently use `find-tags' to navigate your way around
3362source code; and you will create your own `TAGS' tables.
3363
3364Incidentally, the files that contain Lisp code are conventionally
3365called "libraries". The metaphor is derived from that of a
3366specialized library, such as a law library or an engineering library,
3367rather than a general library. Each library, or file, contains
3368functions that relate to a particular topic or activity, such as
3369`abbrev.el' for handling abbreviations and other typing shortcuts,
3370and `help.el' for on-line help. (Sometimes several libraries provide
3371code for a single activity, as the various `rmail...' files provide
3372code for reading electronic mail.) In `The GNU Emacs Manual', you
3373will see sentences such as "The `C-h p' command lets you search the
3374standard Emacs Lisp libraries by topic keywords."
3375
3376A Simplified `beginning-of-buffer' Definition
3377=============================================
3378
3379The `beginning-of-buffer' command is a good function to start with
3380since you are likely to be familiar with it and it is easy to
3381understand. Used as an interactive command, `beginning-of-buffer'
3382moves the cursor to the beginning of the buffer, leaving the mark at
3383the previous position. It is generally bound to `M-<'.
3384
3385In this section, we will discuss a shortened version of the function
3386that shows how it is most frequently used. This shortened function
3387works as written, but it does not contain the code for a complex
3388option. In another section, we will describe the entire function.
3389(*Note Complete Definition of `beginning-of-buffer':
3390beginning-of-buffer.)
3391
3392Before looking at the code, let's consider what the function
3393definition has to contain: it must include an expression that makes
3394the function interactive so it can be called by typing `M-x
3395beginning-of-buffer' or by typing a keychord such as `M-<'; it must
3396include code to leave a mark at the original position in the buffer;
3397and it must include code to move the cursor to the beginning of the
3398buffer.
3399
3400Here is the complete text of the shortened version of the function:
3401
3402 (defun simplified-beginning-of-buffer ()
3403 "Move point to the beginning of the buffer;
3404 leave mark at previous position."
3405 (interactive)
3406 (push-mark)
3407 (goto-char (point-min)))
3408
3409Like all function definitions, this definition has five parts
3410following the special form `defun':
3411
3412 1. The name: in this example, `simplified-beginning-of-buffer'.
3413
3414 2. A list of the arguments: in this example, an empty list, `()',
3415
3416 3. The documentation string.
3417
3418 4. The interactive expression.
3419
3420 5. The body.
3421
3422In this function definition, the argument list is empty; this means
3423that this function does not require any arguments. (When we look at
3424the definition for the complete function, we will see that it may be
3425passed an optional argument.)
3426
3427The interactive expression tells Emacs that the function is intended
3428to be used interactively. In this example, `interactive' does not
3429have an argument because `simplified-beginning-of-buffer' does not
3430require one.
3431
3432The body of the function consists of the two lines:
3433
3434 (push-mark)
3435 (goto-char (point-min))
3436
3437The first of these lines is the expression, `(push-mark)'. When this
3438expression is evaluated by the Lisp interpreter, it sets a mark at
3439the current position of the cursor, wherever that may be. The
3440position of this mark is saved in the mark ring.
3441
3442The next line is `(goto-char (point-min))'. This expression jumps
3443the cursor to the minimum point in the buffer, that is, to the
3444beginning of the buffer (or to the beginning of the accessible portion
3445of the buffer if it is narrowed. *Note Narrowing and Widening:
3446Narrowing & Widening.)
3447
3448The `push-mark' command sets a mark at the place where the cursor was
3449located before it was moved to the beginning of the buffer by the
3450`(goto-char (point-min))' expression. Consequently, you can, if you
3451wish, go back to where you were originally by typing `C-x C-x'.
3452
3453That is all there is to the function definition!
3454
3455When you are reading code such as this and come upon an unfamiliar
3456function, such as `goto-char', you can find out what it does by using
3457the `describe-function' command. To use this command, type `C-h f'
3458and then type in the name of the function and press <RET>. The
3459`describe-function' command will print the function's documentation
3460string in a `*Help*' window. For example, the documentation for
3461`goto-char' is:
3462
3463 One arg, a number. Set point to that number.
3464 Beginning of buffer is position (point-min),
3465 end is (point-max).
3466
3467(The prompt for `describe-function' will offer you the symbol under
3468or preceding the cursor, so you can save typing by positioning the
3469cursor right over or after the function and then typing `C-h f
3470<RET>'.)
3471
3472The `end-of-buffer' function definition is written in the same way as
3473the `beginning-of-buffer' definition except that the body of the
3474function contains the expression `(goto-char (point-max))' in place
3475of `(goto-char (point-min))'.
3476
3477The Definition of `mark-whole-buffer'
3478=====================================
3479
3480The `mark-whole-buffer' function is no harder to understand than the
3481`simplified-beginning-of-buffer' function. In this case, however, we
3482will look at the complete function, not a shortened version.
3483
3484The `mark-whole-buffer' function is not as commonly used as the
3485`beginning-of-buffer' function, but is useful nonetheless: it marks a
3486whole buffer as a region by putting point at the beginning and a mark
3487at the end of the buffer. It is generally bound to `C-x h'.
3488
3489An overview of `mark-whole-buffer'
3490----------------------------------
3491
3492In GNU Emacs 20, the code for the complete function looks like this:
3493
3494 (defun mark-whole-buffer ()
3495 "Put point at beginning and mark at end of buffer."
3496 (interactive)
3497 (push-mark (point))
3498 (push-mark (point-max))
3499 (goto-char (point-min)))
3500
3501Like all other functions, the `mark-whole-buffer' function fits into
3502the template for a function definition. The template looks like this:
3503
3504 (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
3505 "DOCUMENTATION..."
3506 (INTERACTIVE-EXPRESSION...)
3507 BODY...)
3508
3509Here is how the function works: the name of the function is
3510`mark-whole-buffer'; it is followed by an empty argument list, `()',
3511which means that the function does not require arguments. The
3512documentation comes next.
3513
3514The next line is an `(interactive)' expression that tells Emacs that
3515the function will be used interactively. These details are similar
3516to the `simplified-beginning-of-buffer' function described in the
3517previous section.
3518
3519Body of `mark-whole-buffer'
3520---------------------------
3521
3522The body of the `mark-whole-buffer' function consists of three lines
3523of code:
3524
3525 (push-mark (point))
3526 (push-mark (point-max))
3527 (goto-char (point-min))
3528
3529The first of these lines is the expression, `(push-mark (point))'.
3530
3531This line does exactly the same job as the first line of the body of
3532the `simplified-beginning-of-buffer' function, which is written
3533`(push-mark)'. In both cases, the Lisp interpreter sets a mark at
3534the current position of the cursor.
3535
3536I don't know why the expression in `mark-whole-buffer' is written
3537`(push-mark (point))' and the expression in `beginning-of-buffer' is
3538written `(push-mark)'. Perhaps whoever wrote the code did not know
3539that the arguments for `push-mark' are optional and that if
3540`push-mark' is not passed an argument, the function automatically
3541sets mark at the location of point by default. Or perhaps the
3542expression was written so as to parallel the structure of the next
3543line. In any case, the line causes Emacs to determine the position
3544of point and set a mark there.
3545
3546The next line of `mark-whole-buffer' is `(push-mark (point-max)'.
3547This expression sets a mark at the point in the buffer that has the
3548highest number. This will be the end of the buffer (or, if the
3549buffer is narrowed, the end of the accessible portion of the buffer.
3550*Note Narrowing and Widening: Narrowing & Widening, for more about
3551narrowing.) After this mark has been set, the previous mark, the one
3552set at point, is no longer set, but Emacs remembers its position,
3553just as all other recent marks are always remembered. This means
3554that you can, if you wish, go back to that position by typing `C-u
3555C-<SPC>' twice.
3556
3557(In GNU Emacs 21, the `(push-mark (point-max)' is slightly more
3558complicated than shown here. The line reads
3559
3560 (push-mark (point-max) nil t)
3561
3562(The expression works nearly the same as before. It sets a mark at
3563the highest numbered place in the buffer that it can. However, in
3564this version, `push-mark' has two additional arguments. The second
3565argument to `push-mark' is `nil'. This tells the function it
3566_should_ display a message that says `Mark set' when it pushes the
3567mark. The third argument is `t'. This tells `push-mark' to activate
3568the mark when Transient Mark mode is turned on. Transient Mark mode
3569highlights the currently active region. It is usually turned off.)
3570
3571Finally, the last line of the function is `(goto-char (point-min)))'.
3572This is written exactly the same way as it is written in
3573`beginning-of-buffer'. The expression moves the cursor to the
3574minimum point in the buffer, that is, to the beginning of the buffer
3575(or to the beginning of the accessible portion of the buffer). As a
3576result of this, point is placed at the beginning of the buffer and
3577mark is set at the end of the buffer. The whole buffer is,
3578therefore, the region.
3579
3580The Definition of `append-to-buffer'
3581====================================
3582
3583The `append-to-buffer' command is very nearly as simple as the
3584`mark-whole-buffer' command. What it does is copy the region (that
3585is, the part of the buffer between point and mark) from the current
3586buffer to a specified buffer.
3587
3588An Overview of `append-to-buffer'
3589---------------------------------
3590
3591The `append-to-buffer' command uses the `insert-buffer-substring'
3592function to copy the region. `insert-buffer-substring' is described
3593by its name: it takes a string of characters from part of a buffer, a
3594"substring", and inserts them into another buffer. Most of
3595`append-to-buffer' is concerned with setting up the conditions for
3596`insert-buffer-substring' to work: the code must specify both the
3597buffer to which the text will go and the region that will be copied.
3598Here is the complete text of the function:
3599
3600 (defun append-to-buffer (buffer start end)
3601 "Append to specified buffer the text of the region.
3602 It is inserted into that buffer before its point.
3603
3604 When calling from a program, give three arguments:
3605 a buffer or the name of one, and two character numbers
3606 specifying the portion of the current buffer to be copied."
3607 (interactive "BAppend to buffer: \nr")
3608 (let ((oldbuf (current-buffer)))
3609 (save-excursion
3610 (set-buffer (get-buffer-create buffer))
3611 (insert-buffer-substring oldbuf start end))))
3612
3613The function can be understood by looking at it as a series of
3614filled-in templates.
3615
3616The outermost template is for the function definition. In this
3617function, it looks like this (with several slots filled in):
3618
3619 (defun append-to-buffer (buffer start end)
3620 "DOCUMENTATION..."
3621 (interactive "BAppend to buffer: \nr")
3622 BODY...)
3623
3624The first line of the function includes its name and three arguments.
3625The arguments are the `buffer' to which the text will be copied, and
3626the `start' and `end' of the region in the current buffer that will
3627be copied.
3628
3629The next part of the function is the documentation, which is clear and
3630complete.
3631
3632The `append-to-buffer' Interactive Expression
3633---------------------------------------------
3634
3635Since the `append-to-buffer' function will be used interactively, the
3636function must have an `interactive' expression. (For a review of
3637`interactive', see *Note Making a Function Interactive: Interactive.)
3638The expression reads as follows:
3639
3640 (interactive "BAppend to buffer: \nr")
3641
3642This expression has an argument inside of quotation marks and that
3643argument has two parts, separated by `\n'.
3644
3645The first part is `BAppend to buffer: '. Here, the `B' tells Emacs
3646to ask for the name of the buffer that will be passed to the
3647function. Emacs will ask for the name by prompting the user in the
3648minibuffer, using the string following the `B', which is the string
3649`Append to buffer: '. Emacs then binds the variable `buffer' in the
3650function's argument list to the specified buffer.
3651
3652The newline, `\n', separates the first part of the argument from the
3653second part. It is followed by an `r' that tells Emacs to bind the
3654two arguments that follow the symbol `buffer' in the function's
3655argument list (that is, `start' and `end') to the values of point and
3656mark.
3657
3658The Body of `append-to-buffer'
3659------------------------------
3660
3661The body of the `append-to-buffer' function begins with `let'.
3662
3663As we have seen before (*note `let': let.), the purpose of a `let'
3664expression is to create and give initial values to one or more
3665variables that will only be used within the body of the `let'. This
3666means that such a variable will not be confused with any variable of
3667the same name outside the `let' expression.
3668
3669We can see how the `let' expression fits into the function as a whole
3670by showing a template for `append-to-buffer' with the `let'
3671expression in outline:
3672
3673 (defun append-to-buffer (buffer start end)
3674 "DOCUMENTATION..."
3675 (interactive "BAppend to buffer: \nr")
3676 (let ((VARIABLE VALUE))
3677 BODY...)
3678
3679The `let' expression has three elements:
3680
3681 1. The symbol `let';
3682
3683 2. A varlist containing, in this case, a single two-element list,
3684 `(VARIABLE VALUE)';
3685
3686 3. The body of the `let' expression.
3687
3688In the `append-to-buffer' function, the varlist looks like this:
3689
3690 (oldbuf (current-buffer))
3691
3692In this part of the `let' expression, the one variable, `oldbuf', is
3693bound to the value returned by the `(current-buffer)' expression.
3694The variable, `oldbuf', is used to keep track of the buffer in which
3695you are working and from which you will copy.
3696
3697The element or elements of a varlist are surrounded by a set of
3698parentheses so the Lisp interpreter can distinguish the varlist from
3699the body of the `let'. As a consequence, the two-element list within
3700the varlist is surrounded by a circumscribing set of parentheses.
3701The line looks like this:
3702
3703 (let ((oldbuf (current-buffer)))
3704 ... )
3705
3706The two parentheses before `oldbuf' might surprise you if you did not
3707realize that the first parenthesis before `oldbuf' marks the boundary
3708of the varlist and the second parenthesis marks the beginning of the
3709two-element list, `(oldbuf (current-buffer))'.
3710
3711`save-excursion' in `append-to-buffer'
3712--------------------------------------
3713
3714The body of the `let' expression in `append-to-buffer' consists of a
3715`save-excursion' expression.
3716
3717The `save-excursion' function saves the locations of point and mark,
3718and restores them to those positions after the expressions in the
3719body of the `save-excursion' complete execution. In addition,
3720`save-excursion' keeps track of the original buffer, and restores it.
3721This is how `save-excursion' is used in `append-to-buffer'.
3722
3723Incidentally, it is worth noting here that a Lisp function is normally
3724formatted so that everything that is enclosed in a multi-line spread
3725is indented more to the right than the first symbol. In this function
3726definition, the `let' is indented more than the `defun', and the
3727`save-excursion' is indented more than the `let', like this:
3728
3729 (defun ...
3730 ...
3731 ...
3732 (let...
3733 (save-excursion
3734 ...
3735
3736This formatting convention makes it easy to see that the two lines in
3737the body of the `save-excursion' are enclosed by the parentheses
3738associated with `save-excursion', just as the `save-excursion' itself
3739is enclosed by the parentheses associated with the `let':
3740
3741 (let ((oldbuf (current-buffer)))
3742 (save-excursion
3743 (set-buffer (get-buffer-create buffer))
3744 (insert-buffer-substring oldbuf start end))))
3745
3746The use of the `save-excursion' function can be viewed as a process
3747of filling in the slots of a template:
3748
3749 (save-excursion
3750 FIRST-EXPRESSION-IN-BODY
3751 SECOND-EXPRESSION-IN-BODY
3752 ...
3753 LAST-EXPRESSION-IN-BODY)
3754
3755In this function, the body of the `save-excursion' contains only two
3756expressions. The body looks like this:
3757
3758 (set-buffer (get-buffer-create buffer))
3759 (insert-buffer-substring oldbuf start end)
3760
3761When the `append-to-buffer' function is evaluated, the two
3762expressions in the body of the `save-excursion' are evaluated in
3763sequence. The value of the last expression is returned as the value
3764of the `save-excursion' function; the other expression is evaluated
3765only for its side effects.
3766
3767The first line in the body of the `save-excursion' uses the
3768`set-buffer' function to change the current buffer to the one
3769specified in the first argument to `append-to-buffer'. (Changing the
3770buffer is the side effect; as we have said before, in Lisp, a side
3771effect is often the primary thing we want.) The second line does the
3772primary work of the function.
3773
3774The `set-buffer' function changes Emacs' attention to the buffer to
3775which the text will be copied and from which `save-excursion' will
3776return.
3777
3778The line looks like this:
3779
3780 (set-buffer (get-buffer-create buffer))
3781
3782The innermost expression of this list is `(get-buffer-create
3783buffer)'. This expression uses the `get-buffer-create' function,
3784which either gets the named buffer, or if it does not exist, creates
3785one with the given name. This means you can use `append-to-buffer' to
3786put text into a buffer that did not previously exist.
3787
3788`get-buffer-create' also keeps `set-buffer' from getting an
3789unnecessary error: `set-buffer' needs a buffer to go to; if you were
3790to specify a buffer that does not exist, Emacs would baulk. Since
3791`get-buffer-create' will create a buffer if none exists, `set-buffer'
3792is always provided with a buffer.
3793
3794The last line of `append-to-buffer' does the work of appending the
3795text:
3796
3797 (insert-buffer-substring oldbuf start end)
3798
3799The `insert-buffer-substring' function copies a string _from_ the
3800buffer specified as its first argument and inserts the string into
3801the present buffer. In this case, the argument to
3802`insert-buffer-substring' is the value of the variable created and
3803bound by the `let', namely the value of `oldbuf', which was the
3804current buffer when you gave the `append-to-buffer' command.
3805
3806After `insert-buffer-substring' has done its work, `save-excursion'
3807will restore the action to the original buffer and `append-to-buffer'
3808will have done its job.
3809
3810Written in skeletal form, the workings of the body look like this:
3811
3812 (let (BIND-`oldbuf'-TO-VALUE-OF-`current-buffer')
3813 (save-excursion ; Keep track of buffer.
3814 CHANGE-BUFFER
3815 INSERT-SUBSTRING-FROM-`oldbuf'-INTO-BUFFER)
3816
3817 CHANGE-BACK-TO-ORIGINAL-BUFFER-WHEN-FINISHED
3818 LET-THE-LOCAL-MEANING-OF-`oldbuf'-DISAPPEAR-WHEN-FINISHED
3819
3820In summary, `append-to-buffer' works as follows: it saves the value
3821of the current buffer in the variable called `oldbuf'. It gets the
3822new buffer, creating one if need be, and switches Emacs to it. Using
3823the value of `oldbuf', it inserts the region of text from the old
3824buffer into the new buffer; and then using `save-excursion', it
3825brings you back to your original buffer.
3826
3827In looking at `append-to-buffer', you have explored a fairly complex
3828function. It shows how to use `let' and `save-excursion', and how to
3829change to and come back from another buffer. Many function
3830definitions use `let', `save-excursion', and `set-buffer' this way.
3831
3832Review
3833======
3834
3835Here is a brief summary of the various functions discussed in this
3836chapter.
3837
3838`describe-function'
3839`describe-variable'
3840 Print the documentation for a function or variable.
3841 Conventionally bound to `C-h f' and `C-h v'.
3842
3843`find-tag'
3844 Find the file containing the source for a function or variable
3845 and switch buffers to it, positioning point at the beginning of
3846 the item. Conventionally bound to `M-.' (that's a period
3847 following the <META> key).
3848
3849`save-excursion'
3850 Save the location of point and mark and restore their values
3851 after the arguments to `save-excursion' have been evaluated.
3852 Also, remember the current buffer and return to it.
3853
3854`push-mark'
3855 Set mark at a location and record the value of the previous mark
3856 on the mark ring. The mark is a location in the buffer that
3857 will keep its relative position even if text is added to or
3858 removed from the buffer.
3859
3860`goto-char'
3861 Set point to the location specified by the value of the
3862 argument, which can be a number, a marker, or an expression
3863 that returns the number of a position, such as `(point-min)'.
3864
3865`insert-buffer-substring'
3866 Copy a region of text from a buffer that is passed to the
3867 function as an argument and insert the region into the current
3868 buffer.
3869
3870`mark-whole-buffer'
3871 Mark the whole buffer as a region. Normally bound to `C-x h'.
3872
3873`set-buffer'
3874 Switch the attention of Emacs to another buffer, but do not
3875 change the window being displayed. Used when the program rather
3876 than a human is to work on a different buffer.
3877
3878`get-buffer-create'
3879`get-buffer'
3880 Find a named buffer or create one if a buffer of that name does
3881 not exist. The `get-buffer' function returns `nil' if the named
3882 buffer does not exist.
3883
3884Exercises
3885=========
3886
3887 * Write your own `simplified-end-of-buffer' function definition;
3888 then test it to see whether it works.
3889
3890 * Use `if' and `get-buffer' to write a function that prints a
3891 message telling you whether a buffer exists.
3892
3893 * Using `find-tag', find the source for the `copy-to-buffer'
3894 function.
3895
3896A Few More Complex Functions
3897****************************
3898
3899In this chapter, we build on what we have learned in previous chapters
3900by looking at more complex functions. The `copy-to-buffer' function
3901illustrates use of two `save-excursion' expressions in one
3902definition, while the `insert-buffer' function illustrates use of an
3903asterisk in an `interactive' expression, use of `or', and the
3904important distinction between a name and the object to which the name
3905refers.
3906
3907The Definition of `copy-to-buffer'
3908==================================
3909
3910After understanding how `append-to-buffer' works, it is easy to
3911understand `copy-to-buffer'. This function copies text into a
3912buffer, but instead of adding to the second buffer, it replaces the
3913previous text in the second buffer. The code for the
3914`copy-to-buffer' function is almost the same as the code for
3915`append-to-buffer', except that `erase-buffer' and a second
3916`save-excursion' are used. (*Note The Definition of
3917`append-to-buffer': append-to-buffer, for the description of
3918`append-to-buffer'.)
3919
3920The body of `copy-to-buffer' looks like this
3921
3922 ...
3923 (interactive "BCopy to buffer: \nr")
3924 (let ((oldbuf (current-buffer)))
3925 (save-excursion
3926 (set-buffer (get-buffer-create buffer))
3927 (erase-buffer)
3928 (save-excursion
3929 (insert-buffer-substring oldbuf start end)))))
3930
3931This code is similar to the code in `append-to-buffer': it is only
3932after changing to the buffer to which the text will be copied that
3933the definition for this function diverges from the definition for
3934`append-to-buffer': the `copy-to-buffer' function erases the buffer's
3935former contents. (This is what is meant by `replacement'; to replace
3936text, Emacs erases the previous text and then inserts new text.)
3937After erasing the previous contents of the buffer, `save-excursion'
3938is used for a second time and the new text is inserted.
3939
3940Why is `save-excursion' used twice? Consider again what the function
3941does.
3942
3943In outline, the body of `copy-to-buffer' looks like this:
3944
3945 (let (BIND-`oldbuf'-TO-VALUE-OF-`current-buffer')
3946 (save-excursion ; First use of `save-excursion'.
3947 CHANGE-BUFFER
3948 (erase-buffer)
3949 (save-excursion ; Second use of `save-excursion'.
3950 INSERT-SUBSTRING-FROM-`oldbuf'-INTO-BUFFER)))
3951
3952The first use of `save-excursion' returns Emacs to the buffer from
3953which the text is being copied. That is clear, and is just like its
3954use in `append-to-buffer'. Why the second use? The reason is that
3955`insert-buffer-substring' always leaves point at the _end_ of the
3956region being inserted. The second `save-excursion' causes Emacs to
3957leave point at the beginning of the text being inserted. In most
3958circumstances, users prefer to find point at the beginning of
3959inserted text. (Of course, the `copy-to-buffer' function returns the
3960user to the original buffer when done--but if the user _then_
3961switches to the copied-to buffer, point will go to the beginning of
3962the text. Thus, this use of a second `save-excursion' is a little
3963nicety.)
3964
3965The Definition of `insert-buffer'
3966=================================
3967
3968`insert-buffer' is yet another buffer-related function. This command
3969copies another buffer _into_ the current buffer. It is the reverse
3970of `append-to-buffer' or `copy-to-buffer', since they copy a region
3971of text _from_ the current buffer to another buffer.
3972
3973In addition, this code illustrates the use of `interactive' with a
3974buffer that might be "read-only" and the important distinction
3975between the name of an object and the object actually referred to.
3976
3977The Code for `insert-buffer'
3978----------------------------
3979
3980Here is the code:
3981
3982 (defun insert-buffer (buffer)
3983 "Insert after point the contents of BUFFER.
3984 Puts mark after the inserted text.
3985 BUFFER may be a buffer or a buffer name."
3986 (interactive "*bInsert buffer: ")
3987 (or (bufferp buffer)
3988 (setq buffer (get-buffer buffer)))
3989 (let (start end newmark)
3990 (save-excursion
3991 (save-excursion
3992 (set-buffer buffer)
3993 (setq start (point-min) end (point-max)))
3994 (insert-buffer-substring buffer start end)
3995 (setq newmark (point)))
3996 (push-mark newmark)))
3997
3998As with other function definitions, you can use a template to see an
3999outline of the function:
4000
4001 (defun insert-buffer (buffer)
4002 "DOCUMENTATION..."
4003 (interactive "*bInsert buffer: ")
4004 BODY...)
4005
4006The Interactive Expression in `insert-buffer'
4007---------------------------------------------
4008
4009In `insert-buffer', the argument to the `interactive' declaration has
4010two parts, an asterisk, `*', and `bInsert buffer: '.
4011
4012A Read-only Buffer
4013..................
4014
4015The asterisk is for the situation when the current buffer is a
4016read-only buffer--a buffer that cannot be modified. If
4017`insert-buffer' is called when the current buffer is read-only, a
4018message to this effect is printed in the echo area and the terminal
4019may beep or blink at you; you will not be permitted to insert anything
4020into current buffer. The asterisk does not need to be followed by a
4021newline to separate it from the next argument.
4022
4023`b' in an Interactive Expression
4024................................
4025
4026The next argument in the interactive expression starts with a lower
4027case `b'. (This is different from the code for `append-to-buffer',
4028which uses an upper-case `B'. *Note The Definition of
4029`append-to-buffer': append-to-buffer.) The lower-case `b' tells the
4030Lisp interpreter that the argument for `insert-buffer' should be an
4031existing buffer or else its name. (The upper-case `B' option
4032provides for the possibility that the buffer does not exist.) Emacs
4033will prompt you for the name of the buffer, offering you a default
4034buffer, with name completion enabled. If the buffer does not exist,
4035you receive a message that says "No match"; your terminal may beep at
4036you as well.
4037
4038The Body of the `insert-buffer' Function
4039----------------------------------------
4040
4041The body of the `insert-buffer' function has two major parts: an `or'
4042expression and a `let' expression. The purpose of the `or'
4043expression is to ensure that the argument `buffer' is bound to a
4044buffer and not just the name of a buffer. The body of the `let'
4045expression contains the code which copies the other buffer into the
4046current buffer.
4047
4048In outline, the two expressions fit into the `insert-buffer' function
4049like this:
4050
4051 (defun insert-buffer (buffer)
4052 "DOCUMENTATION..."
4053 (interactive "*bInsert buffer: ")
4054 (or ...
4055 ...
4056 (let (VARLIST)
4057 BODY-OF-`let'... )
4058
4059To understand how the `or' expression ensures that the argument
4060`buffer' is bound to a buffer and not to the name of a buffer, it is
4061first necessary to understand the `or' function.
4062
4063Before doing this, let me rewrite this part of the function using
4064`if' so that you can see what is done in a manner that will be
4065familiar.
4066
4067`insert-buffer' With an `if' Instead of an `or'
4068-----------------------------------------------
4069
4070The job to be done is to make sure the value of `buffer' is a buffer
4071itself and not the name of a buffer. If the value is the name, then
4072the buffer itself must be got.
4073
4074You can imagine yourself at a conference where an usher is wandering
4075around holding a list with your name on it and looking for you: the
4076usher is "bound" to your name, not to you; but when the usher finds
4077you and takes your arm, the usher becomes "bound" to you.
4078
4079In Lisp, you might describe this situation like this:
4080
4081 (if (not (holding-on-to-guest))
4082 (find-and-take-arm-of-guest))
4083
4084We want to do the same thing with a buffer--if we do not have the
4085buffer itself, we want to get it.
4086
4087Using a predicate called `bufferp' that tells us whether we have a
4088buffer (rather than its name), we can write the code like this:
4089
4090 (if (not (bufferp buffer)) ; if-part
4091 (setq buffer (get-buffer buffer))) ; then-part
4092
4093Here, the true-or-false-test of the `if' expression is
4094`(not (bufferp buffer))'; and the then-part is the expression
4095`(setq buffer (get-buffer buffer))'.
4096
4097In the test, the function `bufferp' returns true if its argument is a
4098buffer--but false if its argument is the name of the buffer. (The
4099last character of the function name `bufferp' is the character `p';
4100as we saw earlier, such use of `p' is a convention that indicates
4101that the function is a predicate, which is a term that means that the
4102function will determine whether some property is true or false.
4103*Note Using the Wrong Type Object as an Argument: Wrong Type of
4104Argument.)
4105
4106The function `not' precedes the expression `(bufferp buffer)', so the
4107true-or-false-test looks like this:
4108
4109 (not (bufferp buffer))
4110
4111`not' is a function that returns true if its argument is false and
4112false if its argument is true. So if `(bufferp buffer)' returns
4113true, the `not' expression returns false and vice-versa: what is "not
4114true" is false and what is "not false" is true.
4115
4116Using this test, the `if' expression works as follows: when the value
4117of the variable `buffer' is actually a buffer rather then its name,
4118the true-or-false-test returns false and the `if' expression does not
4119evaluate the then-part. This is fine, since we do not need to do
4120anything to the variable `buffer' if it really is a buffer.
4121
4122On the other hand, when the value of `buffer' is not a buffer itself,
4123but the name of a buffer, the true-or-false-test returns true and the
4124then-part of the expression is evaluated. In this case, the
4125then-part is `(setq buffer (get-buffer buffer))'. This expression
4126uses the `get-buffer' function to return an actual buffer itself,
4127given its name. The `setq' then sets the variable `buffer' to the
4128value of the buffer itself, replacing its previous value (which was
4129the name of the buffer).
4130
4131The `or' in the Body
4132--------------------
4133
4134The purpose of the `or' expression in the `insert-buffer' function is
4135to ensure that the argument `buffer' is bound to a buffer and not
4136just to the name of a buffer. The previous section shows how the job
4137could have been done using an `if' expression. However, the
4138`insert-buffer' function actually uses `or'. To understand this, it
4139is necessary to understand how `or' works.
4140
4141An `or' function can have any number of arguments. It evaluates each
4142argument in turn and returns the value of the first of its arguments
4143that is not `nil'. Also, and this is a crucial feature of `or', it
4144does not evaluate any subsequent arguments after returning the first
4145non-`nil' value.
4146
4147The `or' expression looks like this:
4148
4149 (or (bufferp buffer)
4150 (setq buffer (get-buffer buffer)))
4151
4152The first argument to `or' is the expression `(bufferp buffer)'.
4153This expression returns true (a non-`nil' value) if the buffer is
4154actually a buffer, and not just the name of a buffer. In the `or'
4155expression, if this is the case, the `or' expression returns this
4156true value and does not evaluate the next expression--and this is fine
4157with us, since we do not want to do anything to the value of `buffer'
4158if it really is a buffer.
4159
4160On the other hand, if the value of `(bufferp buffer)' is `nil', which
4161it will be if the value of `buffer' is the name of a buffer, the Lisp
4162interpreter evaluates the next element of the `or' expression. This
4163is the expression `(setq buffer (get-buffer buffer))'. This
4164expression returns a non-`nil' value, which is the value to which it
4165sets the variable `buffer'--and this value is a buffer itself, not
4166the name of a buffer.
4167
4168The result of all this is that the symbol `buffer' is always bound to
4169a buffer itself rather than to the name of a buffer. All this is
4170necessary because the `set-buffer' function in a following line only
4171works with a buffer itself, not with the name to a buffer.
4172
4173Incidentally, using `or', the situation with the usher would be
4174written like this:
4175
4176 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
4177
4178The `let' Expression in `insert-buffer'
4179---------------------------------------
4180
4181After ensuring that the variable `buffer' refers to a buffer itself
4182and not just to the name of a buffer, the `insert-buffer function'
4183continues with a `let' expression. This specifies three local
4184variables, `start', `end', and `newmark' and binds them to the
4185initial value `nil'. These variables are used inside the remainder
4186of the `let' and temporarily hide any other occurrence of variables
4187of the same name in Emacs until the end of the `let'.
4188
4189The body of the `let' contains two `save-excursion' expressions.
4190First, we will look at the inner `save-excursion' expression in
4191detail. The expression looks like this:
4192
4193 (save-excursion
4194 (set-buffer buffer)
4195 (setq start (point-min) end (point-max)))
4196
4197The expression `(set-buffer buffer)' changes Emacs' attention from
4198the current buffer to the one from which the text will copied. In
4199that buffer, the variables `start' and `end' are set to the beginning
4200and end of the buffer, using the commands `point-min' and
4201`point-max'. Note that we have here an illustration of how `setq' is
4202able to set two variables in the same expression. The first argument
4203of `setq' is set to the value of its second, and its third argument
4204is set to the value of its fourth.
4205
4206After the body of the inner `save-excursion' is evaluated, the
4207`save-excursion' restores the original buffer, but `start' and `end'
4208remain set to the values of the beginning and end of the buffer from
4209which the text will be copied.
4210
4211The outer `save-excursion' expression looks like this:
4212
4213 (save-excursion
4214 (INNER-`save-excursion'-EXPRESSION
4215 (GO-TO-NEW-BUFFER-AND-SET-`start'-AND-`end')
4216 (insert-buffer-substring buffer start end)
4217 (setq newmark (point)))
4218
4219The `insert-buffer-substring' function copies the text _into_ the
4220current buffer _from_ the region indicated by `start' and `end' in
4221`buffer'. Since the whole of the second buffer lies between `start'
4222and `end', the whole of the second buffer is copied into the buffer
4223you are editing. Next, the value of point, which will be at the end
4224of the inserted text, is recorded in the variable `newmark'.
4225
4226After the body of the outer `save-excursion' is evaluated, point and
4227mark are relocated to their original places.
4228
4229However, it is convenient to locate a mark at the end of the newly
4230inserted text and locate point at its beginning. The `newmark'
4231variable records the end of the inserted text. In the last line of
4232the `let' expression, the `(push-mark newmark)' expression function
4233sets a mark to this location. (The previous location of the mark is
4234still accessible; it is recorded on the mark ring and you can go back
4235to it with `C-u C-<SPC>'.) Meanwhile, point is located at the
4236beginning of the inserted text, which is where it was before you
4237called the insert function.
4238
4239The whole `let' expression looks like this:
4240
4241 (let (start end newmark)
4242 (save-excursion
4243 (save-excursion
4244 (set-buffer buffer)
4245 (setq start (point-min) end (point-max)))
4246 (insert-buffer-substring buffer start end)
4247 (setq newmark (point)))
4248 (push-mark newmark))
4249
4250Like the `append-to-buffer' function, the `insert-buffer' function
4251uses `let', `save-excursion', and `set-buffer'. In addition, the
4252function illustrates one way to use `or'. All these functions are
4253building blocks that we will find and use again and again.
4254
4255Complete Definition of `beginning-of-buffer'
4256============================================
4257
4258The basic structure of the `beginning-of-buffer' function has already
4259been discussed. (*Note A Simplified `beginning-of-buffer'
4260Definition: simplified-beginning-of-buffer.) This section describes
4261the complex part of the definition.
4262
4263As previously described, when invoked without an argument,
4264`beginning-of-buffer' moves the cursor to the beginning of the
4265buffer, leaving the mark at the previous position. However, when the
4266command is invoked with a number between one and ten, the function
4267considers that number to be a fraction of the length of the buffer,
4268measured in tenths, and Emacs moves the cursor that fraction of the
4269way from the beginning of the buffer. Thus, you can either call this
4270function with the key command `M-<', which will move the cursor to
4271the beginning of the buffer, or with a key command such as `C-u 7
4272M-<' which will move the cursor to a point 70% of the way through the
4273buffer. If a number bigger than ten is used for the argument, it
4274moves to the end of the buffer.
4275
4276The `beginning-of-buffer' function can be called with or without an
4277argument. The use of the argument is optional.
4278
4279Optional Arguments
4280------------------
4281
4282Unless told otherwise, Lisp expects that a function with an argument
4283in its function definition will be called with a value for that
4284argument. If that does not happen, you get an error and a message
4285that says `Wrong number of arguments'.
4286
4287However, optional arguments are a feature of Lisp: a "keyword" may be
4288used to tell the Lisp interpreter that an argument is optional. The
4289keyword is `&optional'. (The `&' in front of `optional' is part of
4290the keyword.) In a function definition, if an argument follows the
4291keyword `&optional', a value does not need to be passed to that
4292argument when the function is called.
4293
4294The first line of the function definition of `beginning-of-buffer'
4295therefore looks like this:
4296
4297 (defun beginning-of-buffer (&optional arg)
4298
4299In outline, the whole function looks like this:
4300
4301 (defun beginning-of-buffer (&optional arg)
4302 "DOCUMENTATION..."
4303 (interactive "P")
4304 (push-mark)
4305 (goto-char
4306 (IF-THERE-IS-AN-ARGUMENT
4307 FIGURE-OUT-WHERE-TO-GO
4308 ELSE-GO-TO
4309 (point-min))))
4310
4311The function is similar to the `simplified-beginning-of-buffer'
4312function except that the `interactive' expression has `"P"' as an
4313argument and the `goto-char' function is followed by an if-then-else
4314expression that figures out where to put the cursor if there is an
4315argument.
4316
4317The `"P"' in the `interactive' expression tells Emacs to pass a
4318prefix argument, if there is one, to the function. A prefix argument
4319is made by typing the <META> key followed by a number, or by typing
4320`C-u' and then a number (if you don't type a number, `C-u' defaults
4321to 4).
4322
4323The true-or-false-test of the `if' expression is simple: it is simply
4324the argument `arg'. If `arg' has a value that is not `nil', which
4325will be the case if `beginning-of-buffer' is called with an argument,
4326then this true-or-false-test will return true and the then-part of
4327the `if' expression will be evaluated. On the other hand, if
4328`beginning-of-buffer' is not called with an argument, the value of
4329`arg' will be `nil' and the else-part of the `if' expression will be
4330evaluated. The else-part is simply `point-min', and when this is the
4331outcome, the whole `goto-char' expression is `(goto-char
4332(point-min))', which is how we saw the `beginning-of-buffer' function
4333in its simplified form.
4334
4335`beginning-of-buffer' with an Argument
4336--------------------------------------
4337
4338When `beginning-of-buffer' is called with an argument, an expression
4339is evaluated which calculates what value to pass to `goto-char'.
4340This expression is rather complicated at first sight. It includes an
4341inner `if' expression and much arithmetic. It looks like this:
4342
4343 (if (> (buffer-size) 10000)
4344 ;; Avoid overflow for large buffer sizes!
4345 (* (prefix-numeric-value arg) (/ (buffer-size) 10))
4346 (/
4347 (+ 10
4348 (*
4349 (buffer-size) (prefix-numeric-value arg))) 10))
4350
4351Disentangle `beginning-of-buffer'
4352.................................
4353
4354Like other complex-looking expressions, the conditional expression
4355within `beginning-of-buffer' can be disentangled by looking at it as
4356parts of a template, in this case, the template for an if-then-else
4357expression. In skeletal form, the expression looks like this:
4358
4359 (if (BUFFER-IS-LARGE
4360 DIVIDE-BUFFER-SIZE-BY-10-AND-MULTIPLY-BY-ARG
4361 ELSE-USE-ALTERNATE-CALCULATION
4362
4363The true-or-false-test of this inner `if' expression checks the size
4364of the buffer. The reason for this is that the old Version 18 Emacs
4365used numbers that are no bigger than eight million or so and in the
4366computation that followed, the programmer feared that Emacs might try
4367to use over-large numbers if the buffer were large. The term
4368`overflow', mentioned in the comment, means numbers that are over
4369large. Version 21 Emacs uses larger numbers, but this code has not
4370been touched, if only because people now look at buffers that are far,
4371far larger than ever before.
4372
4373There are two cases: if the buffer is large and if it is not.
4374
4375What happens in a large buffer
4376..............................
4377
4378In `beginning-of-buffer', the inner `if' expression tests whether the
4379size of the buffer is greater than 10,000 characters. To do this, it
4380uses the `>' function and the `buffer-size' function.
4381
4382The line looks like this:
4383
4384 (if (> (buffer-size) 10000)
4385
4386When the buffer is large, the then-part of the `if' expression is
4387evaluated. It reads like this (after formatting for easy reading):
4388
4389 (*
4390 (prefix-numeric-value arg)
4391 (/ (buffer-size) 10))
4392
4393This expression is a multiplication, with two arguments to the
4394function `*'.
4395
4396The first argument is `(prefix-numeric-value arg)'. When `"P"' is
4397used as the argument for `interactive', the value passed to the
4398function as its argument is passed a "raw prefix argument", and not a
4399number. (It is a number in a list.) To perform the arithmetic, a
4400conversion is necessary, and `prefix-numeric-value' does the job.
4401
4402The second argument is `(/ (buffer-size) 10)'. This expression
4403divides the numeric value of the buffer by ten. This produces a
4404number that tells how many characters make up one tenth of the buffer
4405size. (In Lisp, `/' is used for division, just as `*' is used for
4406multiplication.)
4407
4408In the multiplication expression as a whole, this amount is multiplied
4409by the value of the prefix argument--the multiplication looks like
4410this:
4411
4412 (* NUMERIC-VALUE-OF-PREFIX-ARG
4413 NUMBER-OF-CHARACTERS-IN-ONE-TENTH-OF-THE-BUFFER)
4414
4415If, for example, the prefix argument is `7', the one-tenth value will
4416be multiplied by 7 to give a position 70% of the way through the
4417buffer.
4418
4419The result of all this is that if the buffer is large, the
4420`goto-char' expression reads like this:
4421
4422 (goto-char (* (prefix-numeric-value arg)
4423 (/ (buffer-size) 10)))
4424
4425This puts the cursor where we want it.
4426
4427What happens in a small buffer
4428..............................
4429
4430If the buffer contains fewer than 10,000 characters, a slightly
4431different computation is performed. You might think this is not
4432necessary, since the first computation could do the job. However, in
4433a small buffer, the first method may not put the cursor on exactly the
4434desired line; the second method does a better job.
4435
4436The code looks like this:
4437
4438 (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
4439
4440This is code in which you figure out what happens by discovering how
4441the functions are embedded in parentheses. It is easier to read if
4442you reformat it with each expression indented more deeply than its
4443enclosing expression:
4444
4445 (/
4446 (+ 10
4447 (*
4448 (buffer-size)
4449 (prefix-numeric-value arg)))
4450 10))
4451
4452Looking at parentheses, we see that the innermost operation is
4453`(prefix-numeric-value arg)', which converts the raw argument to a
4454number. This number is multiplied by the buffer size in the following
4455expression:
4456
4457 (* (buffer-size) (prefix-numeric-value arg)
4458
4459This multiplication creates a number that may be larger than the size
4460of the buffer--seven times larger if the argument is 7, for example.
4461Ten is then added to this number and finally the large number is
4462divided by ten to provide a value that is one character larger than
4463the percentage position in the buffer.
4464
4465The number that results from all this is passed to `goto-char' and
4466the cursor is moved to that point.
4467
4468The Complete `beginning-of-buffer'
4469----------------------------------
4470
4471Here is the complete text of the `beginning-of-buffer' function:
4472
4473 (defun beginning-of-buffer (&optional arg)
4474 "Move point to the beginning of the buffer;
4475 leave mark at previous position.
4476 With arg N, put point N/10 of the way
4477 from the true beginning.
4478 Don't use this in Lisp programs!
4479 \(goto-char (point-min)) is faster
4480 and does not set the mark."
4481 (interactive "P")
4482 (push-mark)
4483 (goto-char
4484 (if arg
4485 (if (> (buffer-size) 10000)
4486 ;; Avoid overflow for large buffer sizes!
4487 (* (prefix-numeric-value arg)
4488 (/ (buffer-size) 10))
4489 (/ (+ 10 (* (buffer-size)
4490 (prefix-numeric-value arg)))
4491 10))
4492 (point-min)))
4493 (if arg (forward-line 1)))
4494
4495Except for two small points, the previous discussion shows how this
4496function works. The first point deals with a detail in the
4497documentation string, and the second point concerns the last line of
4498the function.
4499
4500In the documentation string, there is reference to an expression:
4501
4502 \(goto-char (point-min))
4503
4504A `\' is used before the first parenthesis of this expression. This
4505`\' tells the Lisp interpreter that the expression should be printed
4506as shown in the documentation rather than evaluated as a symbolic
4507expression, which is what it looks like.
4508
4509Finally, the last line of the `beginning-of-buffer' command says to
4510move point to the beginning of the next line if the command is
4511invoked with an argument:
4512
4513 (if arg (forward-line 1)))
4514
4515This puts the cursor at the beginning of the first line after the
4516appropriate tenths position in the buffer. This is a flourish that
4517means that the cursor is always located _at least_ the requested
4518tenths of the way through the buffer, which is a nicety that is,
4519perhaps, not necessary, but which, if it did not occur, would be sure
4520to draw complaints.
4521
4522Review
4523======
4524
4525Here is a brief summary of some of the topics covered in this chapter.
4526
4527`or'
4528 Evaluate each argument in sequence, and return the value of the
4529 first argument that is not `nil'; if none return a value that is
4530 not `nil', return `nil'. In brief, return the first true value
4531 of the arguments; return a true value if one _or_ any of the
4532 other are true.
4533
4534`and'
4535 Evaluate each argument in sequence, and if any are `nil', return
4536 `nil'; if none are `nil', return the value of the last argument.
4537 In brief, return a true value only if all the arguments are
4538 true; return a true value if one _and_ each of the others is
4539 true.
4540
4541`&optional'
4542 A keyword used to indicate that an argument to a function
4543 definition is optional; this means that the function can be
4544 evaluated without the argument, if desired.
4545
4546`prefix-numeric-value'
4547 Convert the `raw prefix argument' produced by `(interactive
4548 "P")' to a numeric value.
4549
4550`forward-line'
4551 Move point forward to the beginning of the next line, or if the
4552 argument is greater than one, forward that many lines. If it
4553 can't move as far forward as it is supposed to, `forward-line'
4554 goes forward as far as it can and then returns a count of the
4555 number of additional lines it was supposed to move but couldn't.
4556
4557`erase-buffer'
4558 Delete the entire contents of the current buffer.
4559
4560`bufferp'
4561 Return `t' if its argument is a buffer; otherwise return `nil'.
4562
4563`optional' Argument Exercise
4564============================
4565
4566Write an interactive function with an optional argument that tests
4567whether its argument, a number, is greater or less than the value of
4568`fill-column', and tells you which, in a message. However, if you do
4569not pass an argument to the function, use 56 as a default value.
4570
4571Narrowing and Widening
4572**********************
4573
4574Narrowing is a feature of Emacs that makes it possible for you to
4575focus on a specific part of a buffer, and work without accidentally
4576changing other parts. Narrowing is normally disabled since it can
4577confuse novices.
4578
4579The Advantages of Narrowing
4580===========================
4581
4582With narrowing, the rest of a buffer is made invisible, as if it
4583weren't there. This is an advantage if, for example, you want to
4584replace a word in one part of a buffer but not in another: you narrow
4585to the part you want and the replacement is carried out only in that
4586section, not in the rest of the buffer. Searches will only work
4587within a narrowed region, not outside of one, so if you are fixing a
4588part of a document, you can keep yourself from accidentally finding
4589parts you do not need to fix by narrowing just to the region you want.
4590(The key binding for `narrow-to-region' is `C-x n n'.)
4591
4592However, narrowing does make the rest of the buffer invisible, which
4593can scare people who inadvertently invoke narrowing and think they
4594have deleted a part of their file. Moreover, the `undo' command
4595(which is usually bound to `C-x u') does not turn off narrowing (nor
4596should it), so people can become quite desperate if they do not know
4597that they can return the rest of a buffer to visibility with the
4598`widen' command. (The key binding for `widen' is `C-x n w'.)
4599
4600Narrowing is just as useful to the Lisp interpreter as to a human.
4601Often, an Emacs Lisp function is designed to work on just part of a
4602buffer; or conversely, an Emacs Lisp function needs to work on all of
4603a buffer that has been narrowed. The `what-line' function, for
4604example, removes the narrowing from a buffer, if it has any narrowing
4605and when it has finished its job, restores the narrowing to what it
4606was. On the other hand, the `count-lines' function, which is called
4607by `what-line', uses narrowing to restrict itself to just that portion
4608of the buffer in which it is interested and then restores the previous
4609situation.
4610
4611The `save-restriction' Special Form
4612===================================
4613
4614In Emacs Lisp, you can use the `save-restriction' special form to
4615keep track of whatever narrowing is in effect, if any. When the Lisp
4616interpreter meets with `save-restriction', it executes the code in
4617the body of the `save-restriction' expression, and then undoes any
4618changes to narrowing that the code caused. If, for example, the
4619buffer is narrowed and the code that follows `save-restriction' gets
4620rid of the narrowing, `save-restriction' returns the buffer to its
4621narrowed region afterwards. In the `what-line' command, any
4622narrowing the buffer may have is undone by the `widen' command that
4623immediately follows the `save-restriction' command. Any original
4624narrowing is restored just before the completion of the function.
4625
4626The template for a `save-restriction' expression is simple:
4627
4628 (save-restriction
4629 BODY... )
4630
4631The body of the `save-restriction' is one or more expressions that
4632will be evaluated in sequence by the Lisp interpreter.
4633
4634Finally, a point to note: when you use both `save-excursion' and
4635`save-restriction', one right after the other, you should use
4636`save-excursion' outermost. If you write them in reverse order, you
4637may fail to record narrowing in the buffer to which Emacs switches
4638after calling `save-excursion'. Thus, when written together,
4639`save-excursion' and `save-restriction' should be written like this:
4640
4641 (save-excursion
4642 (save-restriction
4643 BODY...))
4644
4645In other circumstances, when not written together, the
4646`save-excursion' and `save-restriction' special forms must be written
4647in the order appropriate to the function.
4648
4649For example,
4650
4651 (save-restriction
4652 (widen)
4653 (save-excursion
4654 BODY...))
4655
4656`what-line'
4657===========
4658
4659The `what-line' command tells you the number of the line in which the
4660cursor is located. The function illustrates the use of the
4661`save-restriction' and `save-excursion' commands. Here is the text
4662of the function in full:
4663
4664 (defun what-line ()
4665 "Print the current line number (in the buffer) of point."
4666 (interactive)
4667 (save-restriction
4668 (widen)
4669 (save-excursion
4670 (beginning-of-line)
4671 (message "Line %d"
4672 (1+ (count-lines 1 (point)))))))
4673
4674The function has a documentation line and is interactive, as you would
4675expect. The next two lines use the functions `save-restriction' and
4676`widen'.
4677
4678The `save-restriction' special form notes whatever narrowing is in
4679effect, if any, in the current buffer and restores that narrowing
4680after the code in the body of the `save-restriction' has been
4681evaluated.
4682
4683The `save-restriction' special form is followed by `widen'. This
4684function undoes any narrowing the current buffer may have had when
4685`what-line' was called. (The narrowing that was there is the
4686narrowing that `save-restriction' remembers.) This widening makes it
4687possible for the line counting commands to count from the beginning
4688of the buffer. Otherwise, they would have been limited to counting
4689within the accessible region. Any original narrowing is restored
4690just before the completion of the function by the `save-restriction'
4691special form.
4692
4693The call to `widen' is followed by `save-excursion', which saves the
4694location of the cursor (i.e., of point) and of the mark, and restores
4695them after the code in the body of the `save-excursion' uses the
4696`beginning-of-line' function to move point.
4697
4698(Note that the `(widen)' expression comes between the
4699`save-restriction' and `save-excursion' special forms. When you
4700write the two `save- ...' expressions in sequence, write
4701`save-excursion' outermost.)
4702
4703The last two lines of the `what-line' function are functions to count
4704the number of lines in the buffer and then print the number in the
4705echo area.
4706
4707 (message "Line %d"
4708 (1+ (count-lines 1 (point)))))))
4709
4710The `message' function prints a one-line message at the bottom of the
4711Emacs screen. The first argument is inside of quotation marks and is
4712printed as a string of characters. However, it may contain `%d',
4713`%s', or `%c' to print arguments that follow the string. `%d' prints
4714the argument as a decimal, so the message will say something such as
4715`Line 243'.
4716
4717The number that is printed in place of the `%d' is computed by the
4718last line of the function:
4719
4720 (1+ (count-lines 1 (point)))
4721
4722What this does is count the lines from the first position of the
4723buffer, indicated by the `1', up to `(point)', and then add one to
4724that number. (The `1+' function adds one to its argument.) We add
4725one to it because line 2 has only one line before it, and
4726`count-lines' counts only the lines _before_ the current line.
4727
4728After `count-lines' has done its job, and the message has been
4729printed in the echo area, the `save-excursion' restores point and
4730mark to their original positions; and `save-restriction' restores the
4731original narrowing, if any.
4732
4733Exercise with Narrowing
4734=======================
4735
4736Write a function that will display the first 60 characters of the
4737current buffer, even if you have narrowed the buffer to its latter
4738half so that the first line is inaccessible. Restore point, mark,
4739and narrowing. For this exercise, you need to use
4740`save-restriction', `widen', `goto-char', `point-min',
4741`buffer-substring', `message', and other functions, a whole potpourri.
4742
4743`car', `cdr', `cons': Fundamental Functions
4744*******************************************
4745
4746In Lisp, `car', `cdr', and `cons' are fundamental functions. The
4747`cons' function is used to construct lists, and the `car' and `cdr'
4748functions are used to take them apart.
4749
4750In the walk through of the `copy-region-as-kill' function, we will
4751see `cons' as well as two variants on `cdr', namely, `setcdr' and
4752`nthcdr'. (*Note copy-region-as-kill::.)
4753
4754Strange Names
4755=============
4756
4757The name of the `cons' function is not unreasonable: it is an
4758abbreviation of the word `construct'. The origins of the names for
4759`car' and `cdr', on the other hand, are esoteric: `car' is an acronym
4760from the phrase `Contents of the Address part of the Register'; and
4761`cdr' (pronounced `could-er') is an acronym from the phrase `Contents
4762of the Decrement part of the Register'. These phrases refer to
4763specific pieces of hardware on the very early computer on which the
4764original Lisp was developed. Besides being obsolete, the phrases
4765have been completely irrelevant for more than 25 years to anyone
4766thinking about Lisp. Nonetheless, although a few brave scholars have
4767begun to use more reasonable names for these functions, the old terms
4768are still in use. In particular, since the terms are used in the
4769Emacs Lisp source code, we will use them in this introduction.
4770
4771`car' and `cdr'
4772===============
4773
4774The CAR of a list is, quite simply, the first item in the list. Thus
4775the CAR of the list `(rose violet daisy buttercup)' is `rose'.
4776
4777If you are reading this in Info in GNU Emacs, you can see this by
4778evaluating the following:
4779
4780 (car '(rose violet daisy buttercup))
4781
4782After evaluating the expression, `rose' will appear in the echo area.
4783
4784Clearly, a more reasonable name for the `car' function would be
4785`first' and this is often suggested.
4786
4787`car' does not remove the first item from the list; it only reports
4788what it is. After `car' has been applied to a list, the list is
4789still the same as it was. In the jargon, `car' is `non-destructive'.
4790This feature turns out to be important.
4791
4792The CDR of a list is the rest of the list, that is, the `cdr'
4793function returns the part of the list that follows the first item.
4794Thus, while the CAR of the list `'(rose violet daisy buttercup)' is
4795`rose', the rest of the list, the value returned by the `cdr'
4796function, is `(violet daisy buttercup)'.
4797
4798You can see this by evaluating the following in the usual way:
4799
4800 (cdr '(rose violet daisy buttercup))
4801
4802When you evaluate this, `(violet daisy buttercup)' will appear in the
4803echo area.
4804
4805Like `car', `cdr' does not remove any elements from the list--it just
4806returns a report of what the second and subsequent elements are.
4807
4808Incidentally, in the example, the list of flowers is quoted. If it
4809were not, the Lisp interpreter would try to evaluate the list by
4810calling `rose' as a function. In this example, we do not want to do
4811that.
4812
4813Clearly, a more reasonable name for `cdr' would be `rest'.
4814
4815(There is a lesson here: when you name new functions, consider very
4816carefully what you are doing, since you may be stuck with the names
4817for far longer than you expect. The reason this document perpetuates
4818these names is that the Emacs Lisp source code uses them, and if I did
4819not use them, you would have a hard time reading the code; but do,
4820please, try to avoid using these terms yourself. The people who come
4821after you will be grateful to you.)
4822
4823When `car' and `cdr' are applied to a list made up of symbols, such
4824as the list `(pine fir oak maple)', the element of the list returned
4825by the function `car' is the symbol `pine' without any parentheses
4826around it. `pine' is the first element in the list. However, the
4827CDR of the list is a list itself, `(fir oak maple)', as you can see
4828by evaluating the following expressions in the usual way:
4829
4830 (car '(pine fir oak maple))
4831
4832 (cdr '(pine fir oak maple))
4833
4834On the other hand, in a list of lists, the first element is itself a
4835list. `car' returns this first element as a list. For example, the
4836following list contains three sub-lists, a list of carnivores, a list
4837of herbivores and a list of sea mammals:
4838
4839 (car '((lion tiger cheetah)
4840 (gazelle antelope zebra)
4841 (whale dolphin seal)))
4842
4843In this example, the first element or CAR of the list is the list of
4844carnivores, `(lion tiger cheetah)', and the rest of the list is
4845`((gazelle antelope zebra) (whale dolphin seal))'.
4846
4847 (cdr '((lion tiger cheetah)
4848 (gazelle antelope zebra)
4849 (whale dolphin seal)))
4850
4851It is worth saying again that `car' and `cdr' are
4852non-destructive--that is, they do not modify or change lists to which
4853they are applied. This is very important for how they are used.
4854
4855Also, in the first chapter, in the discussion about atoms, I said that
4856in Lisp, "certain kinds of atom, such as an array, can be separated
4857into parts; but the mechanism for doing this is different from the
4858mechanism for splitting a list. As far as Lisp is concerned, the
4859atoms of a list are unsplittable." (*Note Lisp Atoms::.) The `car'
4860and `cdr' functions are used for splitting lists and are considered
4861fundamental to Lisp. Since they cannot split or gain access to the
4862parts of an array, an array is considered an atom. Conversely, the
4863other fundamental function, `cons', can put together or construct a
4864list, but not an array. (Arrays are handled by array-specific
4865functions. *Note Arrays: (elisp)Arrays.)
4866
4867`cons'
4868======
4869
4870The `cons' function constructs lists; it is the inverse of `car' and
4871`cdr'. For example, `cons' can be used to make a four element list
4872from the three element list, `(fir oak maple)':
4873
4874 (cons 'pine '(fir oak maple))
4875
4876After evaluating this list, you will see
4877
4878 (pine fir oak maple)
4879
4880appear in the echo area. `cons' causes the creation of a new list in
4881which the element is followed by the elements of the original list.
4882
4883We often say that ``cons' puts a new element at the beginning of a
4884list; it attaches or pushes elements onto the list', but this
4885phrasing can be misleading, since `cons' does not change an existing
4886list, but creates a new one.
4887
4888Like `car' and `cdr', `cons' is non-destructive.
4889
4890Build a list
4891------------
4892
4893`cons' must have a list to attach to.(1) You cannot start from
4894absolutely nothing. If you are building a list, you need to provide
4895at least an empty list at the beginning. Here is a series of `cons'
4896expressions that build up a list of flowers. If you are reading this
4897in Info in GNU Emacs, you can evaluate each of the expressions in the
4898usual way; the value is printed in this text after `=>', which you
4899may read as `evaluates to'.
4900
4901 (cons 'buttercup ())
4902 => (buttercup)
4903
4904 (cons 'daisy '(buttercup))
4905 => (daisy buttercup)
4906
4907 (cons 'violet '(daisy buttercup))
4908 => (violet daisy buttercup)
4909
4910 (cons 'rose '(violet daisy buttercup))
4911 => (rose violet daisy buttercup)
4912
4913In the first example, the empty list is shown as `()' and a list made
4914up of `buttercup' followed by the empty list is constructed. As you
4915can see, the empty list is not shown in the list that was
4916constructed. All that you see is `(buttercup)'. The empty list is
4917not counted as an element of a list because there is nothing in an
4918empty list. Generally speaking, an empty list is invisible.
4919
4920The second example, `(cons 'daisy '(buttercup))' constructs a new,
4921two element list by putting `daisy' in front of `buttercup'; and the
4922third example constructs a three element list by putting `violet' in
4923front of `daisy' and `buttercup'.
4924
4925---------- Footnotes ----------
4926
4927(1) Actually, you can `cons' an element to an atom to produce a
4928dotted pair. Dotted pairs are not discussed here; see *Note Dotted
4929Pair Notation: (elisp)Dotted Pair Notation.
4930
4931Find the Length of a List: `length'
4932-----------------------------------
4933
4934You can find out how many elements there are in a list by using the
4935Lisp function `length', as in the following examples:
4936
4937 (length '(buttercup))
4938 => 1
4939
4940 (length '(daisy buttercup))
4941 => 2
4942
4943 (length (cons 'violet '(daisy buttercup)))
4944 => 3
4945
4946In the third example, the `cons' function is used to construct a
4947three element list which is then passed to the `length' function as
4948its argument.
4949
4950We can also use `length' to count the number of elements in an empty
4951list:
4952
4953 (length ())
4954 => 0
4955
4956As you would expect, the number of elements in an empty list is zero.
4957
4958An interesting experiment is to find out what happens if you try to
4959find the length of no list at all; that is, if you try to call
4960`length' without giving it an argument, not even an empty list:
4961
4962 (length )
4963
4964What you see, if you evaluate this, is the error message
4965
4966 Wrong number of arguments: #<subr length>, 0
4967
4968This means that the function receives the wrong number of arguments,
4969zero, when it expects some other number of arguments. In this case,
4970one argument is expected, the argument being a list whose length the
4971function is measuring. (Note that _one_ list is _one_ argument, even
4972if the list has many elements inside it.)
4973
4974The part of the error message that says `#<subr length>' is the name
4975of the function. This is written with a special notation, `#<subr',
4976that indicates that the function `length' is one of the primitive
4977functions written in C rather than in Emacs Lisp. (`subr' is an
4978abbreviation for `subroutine'.) *Note What Is a Function?:
4979(elisp)What Is a Function, for more about subroutines.
4980
4981`nthcdr'
4982========
4983
4984The `nthcdr' function is associated with the `cdr' function. What it
4985does is take the CDR of a list repeatedly.
4986
4987If you take the CDR of the list `(pine fir oak maple)', you will be
4988returned the list `(fir oak maple)'. If you repeat this on what was
4989returned, you will be returned the list `(oak maple)'. (Of course,
4990repeated CDRing on the original list will just give you the original
4991CDR since the function does not change the list. You need to
4992evaluate the CDR of the CDR and so on.) If you continue this,
4993eventually you will be returned an empty list, which in this case,
4994instead of being shown as `()' is shown as `nil'.
4995
4996For review, here is a series of repeated CDRs, the text following the
4997`=>' shows what is returned.
4998
4999 (cdr '(pine fir oak maple))
5000 =>(fir oak maple)
5001
5002 (cdr '(fir oak maple))
5003 => (oak maple)
5004
5005 (cdr '(oak maple))
5006 =>(maple)
5007
5008 (cdr '(maple))
5009 => nil
5010
5011 (cdr 'nil)
5012 => nil
5013
5014 (cdr ())
5015 => nil
5016
5017You can also do several CDRs without printing the values in between,
5018like this:
5019
5020 (cdr (cdr '(pine fir oak maple)))
5021 => (oak maple)
5022
5023In this example, the Lisp interpreter evaluates the innermost list
5024first. The innermost list is quoted, so it just passes the list as
5025it is to the innermost `cdr'. This `cdr' passes a list made up of the
5026second and subsequent elements of the list to the outermost `cdr',
5027which produces a list composed of the third and subsequent elements of
5028the original list. In this example, the `cdr' function is repeated
5029and returns a list that consists of the original list without its
5030first two elements.
5031
5032The `nthcdr' function does the same as repeating the call to `cdr'.
5033In the following example, the argument 2 is passed to the function
5034`nthcdr', along with the list, and the value returned is the list
5035without its first two items, which is exactly the same as repeating
5036`cdr' twice on the list:
5037
5038 (nthcdr 2 '(pine fir oak maple))
5039 => (oak maple)
5040
5041Using the original four element list, we can see what happens when
5042various numeric arguments are passed to `nthcdr', including 0, 1, and
50435:
5044
5045 ;; Leave the list as it was.
5046 (nthcdr 0 '(pine fir oak maple))
5047 => (pine fir oak maple)
5048
5049 ;; Return a copy without the first element.
5050 (nthcdr 1 '(pine fir oak maple))
5051 => (fir oak maple)
5052
5053 ;; Return a copy of the list without three elements.
5054 (nthcdr 3 '(pine fir oak maple))
5055 => (maple)
5056
5057 ;; Return a copy lacking all four elements.
5058 (nthcdr 4 '(pine fir oak maple))
5059 => nil
5060
5061 ;; Return a copy lacking all elements.
5062 (nthcdr 5 '(pine fir oak maple))
5063 => nil
5064
5065`nth'
5066=====
5067
5068The `nthcdr' function takes the CDR of a list repeatedly. The `nth'
5069function takes the CAR of the result returned by `nthcdr'. It
5070returns the Nth element of the list.
5071
5072Thus, if it were not defined in C for speed, the definition of `nth'
5073would be:
5074
5075 (defun nth (n list)
5076 "Returns the Nth element of LIST.
5077 N counts from zero. If LIST is not that long, nil is returned."
5078 (car (nthcdr n list)))
5079
5080(Originally, `nth' was defined in Emacs Lisp in `subr.el', but its
5081definition was redone in C in the 1980s.)
5082
5083The `nth' function returns a single element of a list. This can be
5084very convenient.
5085
5086Note that the elements are numbered from zero, not one. That is to
5087say, the first element of a list, its CAR is the zeroth element.
5088This is called `zero-based' counting and often bothers people who are
5089accustomed to the first element in a list being number one, which is
5090`one-based'.
5091
5092For example:
5093
5094 (nth 0 '("one" "two" "three"))
5095 => "one"
5096
5097 (nth 1 '("one" "two" "three"))
5098 => "two"
5099
5100It is worth mentioning that `nth', like `nthcdr' and `cdr', does not
5101change the original list--the function is non-destructive. This is
5102in sharp contrast to the `setcar' and `setcdr' functions.
5103
5104`setcar'
5105========
5106
5107As you might guess from their names, the `setcar' and `setcdr'
5108functions set the CAR or the CDR of a list to a new value. They
5109actually change the original list, unlike `car' and `cdr' which leave
5110the original list as it was. One way to find out how this works is
5111to experiment. We will start with the `setcar' function.
5112
5113First, we can make a list and then set the value of a variable to the
5114list, using the `setq' function. Here is a list of animals:
5115
5116 (setq animals '(antelope giraffe lion tiger))
5117
5118If you are reading this in Info inside of GNU Emacs, you can evaluate
5119this expression in the usual fashion, by positioning the cursor after
5120the expression and typing `C-x C-e'. (I'm doing this right here as I
5121write this. This is one of the advantages of having the interpreter
5122built into the computing environment.)
5123
5124When we evaluate the variable `animals', we see that it is bound to
5125the list `(antelope giraffe lion tiger)':
5126
5127 animals
5128 => (antelope giraffe lion tiger)
5129
5130Put another way, the variable `animals' points to the list `(antelope
5131giraffe lion tiger)'.
5132
5133Next, evaluate the function `setcar' while passing it two arguments,
5134the variable `animals' and the quoted symbol `hippopotamus'; this is
5135done by writing the three element list `(setcar animals
5136'hippopotamus)' and then evaluating it in the usual fashion:
5137
5138 (setcar animals 'hippopotamus)
5139
5140After evaluating this expression, evaluate the variable `animals'
5141again. You will see that the list of animals has changed:
5142
5143 animals
5144 => (hippopotamus giraffe lion tiger)
5145
5146The first element on the list, `antelope' is replaced by
5147`hippopotamus'.
5148
5149So we can see that `setcar' did not add a new element to the list as
5150`cons' would have; it replaced `giraffe' with `hippopotamus'; it
5151_changed_ the list.
5152
5153`setcdr'
5154========
5155
5156The `setcdr' function is similar to the `setcar' function, except
5157that the function replaces the second and subsequent elements of a
5158list rather than the first element.
5159
5160To see how this works, set the value of the variable to a list of
5161domesticated animals by evaluating the following expression:
5162
5163 (setq domesticated-animals '(horse cow sheep goat))
5164
5165If you now evaluate the list, you will be returned the list `(horse
5166cow sheep goat)':
5167
5168 domesticated-animals
5169 => (horse cow sheep goat)
5170
5171Next, evaluate `setcdr' with two arguments, the name of the variable
5172which has a list as its value, and the list to which the CDR of the
5173first list will be set;
5174
5175 (setcdr domesticated-animals '(cat dog))
5176
5177If you evaluate this expression, the list `(cat dog)' will appear in
5178the echo area. This is the value returned by the function. The
5179result we are interested in is the "side effect", which we can see by
5180evaluating the variable `domesticated-animals':
5181
5182 domesticated-animals
5183 => (horse cat dog)
5184
5185Indeed, the list is changed from `(horse cow sheep goat)' to `(horse
5186cat dog)'. The CDR of the list is changed from `(cow sheep goat)' to
5187`(cat dog)'.
5188
5189Exercise
5190========
5191
5192Construct a list of four birds by evaluating several expressions with
5193`cons'. Find out what happens when you `cons' a list onto itself.
5194Replace the first element of the list of four birds with a fish.
5195Replace the rest of that list with a list of other fish.
5196
5197Cutting and Storing Text
5198************************
5199
5200Whenever you cut or clip text out of a buffer with a `kill' command in
5201GNU Emacs, it is stored in a list and you can bring it back with a
5202`yank' command.
5203
5204(The use of the word `kill' in Emacs for processes which specifically
5205_do not_ destroy the values of the entities is an unfortunate
5206historical accident. A much more appropriate word would be `clip'
5207since that is what the kill commands do; they clip text out of a
5208buffer and put it into storage from which it can be brought back. I
5209have often been tempted to replace globally all occurrences of `kill'
5210in the Emacs sources with `clip' and all occurrences of `killed' with
5211`clipped'.)
5212
5213Storing Text in a List
5214======================
5215
5216When text is cut out of a buffer, it is stored on a list. Successive
5217pieces of text are stored on the list successively, so the list might
5218look like this:
5219
5220 ("a piece of text" "previous piece")
5221
5222The function `cons' can be used to to create a new list from a piece
5223of text (an `atom', to use the jargon) and an existing list, like
5224this:
5225
5226 (cons "another piece"
5227 '("a piece of text" "previous piece"))
5228
5229If you evaluate this expression, a list of three elements will appear
5230in the echo area:
5231
5232 ("another piece" "a piece of text" "previous piece")
5233
5234With the `car' and `nthcdr' functions, you can retrieve whichever
5235piece of text you want. For example, in the following code, `nthcdr
52361 ...' returns the list with the first item removed; and the `car'
5237returns the first element of that remainder--the second element of
5238the original list:
5239
5240 (car (nthcdr 1 '("another piece"
5241 "a piece of text"
5242 "previous piece")))
5243 => "a piece of text"
5244
5245The actual functions in Emacs are more complex than this, of course.
5246The code for cutting and retrieving text has to be written so that
5247Emacs can figure out which element in the list you want--the first,
5248second, third, or whatever. In addition, when you get to the end of
5249the list, Emacs should give you the first element of the list, rather
5250than nothing at all.
5251
5252The list that holds the pieces of text is called the "kill ring".
5253This chapter leads up to a description of the kill ring and how it is
5254used by first tracing how the `zap-to-char' function works. This
5255function uses (or `calls') a function that invokes a function that
5256manipulates the kill ring. Thus, before reaching the mountains, we
5257climb the foothills.
5258
5259A subsequent chapter describes how text that is cut from the buffer is
5260retrieved. *Note Yanking Text Back: Yanking.
5261
5262`zap-to-char'
5263=============
5264
5265The `zap-to-char' function barely changed between GNU Emacs version
526619 and GNU Emacs version 21. However, `zap-to-char' calls another
5267function, `kill-region', which enjoyed a major rewrite on the way to
5268version 21.
5269
5270The `kill-region' function in Emacs 19 is complex, but does not use
5271code that is important at this time. We will skip it.
5272
5273The `kill-region' function in Emacs 21 is easier to read than the
5274same function in Emacs 19 and introduces a very important concept,
5275that of error handling. We will walk through the function.
5276
5277But first, let us look at the interactive `zap-to-char' function.
5278
5279The Complete `zap-to-char' Implementation
5280-----------------------------------------
5281
5282The GNU Emacs version 19 and version 21 implementations of the
5283`zap-to-char' function are nearly identical in form, and they work
5284alike. The function removes the text in the region between the
5285location of the cursor (i.e., of point) up to and including the next
5286occurrence of a specified character. The text that `zap-to-char'
5287removes is put in the kill ring; and it can be retrieved from the kill
5288ring by typing `C-y' (`yank'). If the command is given an argument,
5289it removes text through that number of occurrences. Thus, if the
5290cursor were at the beginning of this sentence and the character were
5291`s', `Thus' would be removed. If the argument were two, `Thus, if
5292the curs' would be removed, up to and including the `s' in `cursor'.
5293
5294If the specified character is not found, `zap-to-char' will say
5295"Search failed", tell you the character you typed, and not remove any
5296text.
5297
5298In order to determine how much text to remove, `zap-to-char' uses a
5299search function. Searches are used extensively in code that
5300manipulates text, and we will focus attention on them as well as on
5301the deletion command.
5302
5303Here is the complete text of the version 19 implementation of the
5304function:
5305
5306 (defun zap-to-char (arg char) ; version 19 implementation
5307 "Kill up to and including ARG'th occurrence of CHAR.
5308 Goes backward if ARG is negative; error if CHAR not found."
5309 (interactive "*p\ncZap to char: ")
5310 (kill-region (point)
5311 (progn
5312 (search-forward
5313 (char-to-string char) nil nil arg)
5314 (point))))
5315
5316The `interactive' Expression
5317----------------------------
5318
5319The interactive expression in the `zap-to-char' command looks like
5320this:
5321
5322 (interactive "*p\ncZap to char: ")
5323
5324The part within quotation marks, `"*p\ncZap to char: "', specifies
5325three different things. First, and most simply, the asterisk, `*',
5326causes an error to be signalled if the buffer is read-only. This
5327means that if you try `zap-to-char' in a read-only buffer you will
5328not be able to remove text, and you will receive a message that says
5329"Buffer is read-only"; your terminal may beep at you as well.
5330
5331The version 21 implementation does not have the asterisk, `*'. The
5332function works the same as in version 19: in both cases, it cannot
5333remove text from a read-only buffer but the function does copy the
5334text that would have been removed to the kill ring. Also, in both
5335cases, you see an error message.
5336
5337However, the version 19 implementation copies text from a read-only
5338buffer only because of a mistake in the implementation of
5339`interactive'. According to the documentation for `interactive', the
5340asterisk, `*', should prevent the `zap-to-char' function from doing
5341anything at all when the buffer is read only. The function should
5342not copy the text to the kill ring. It is a bug that it does.
5343
5344In version 21, `interactive' is implemented correctly. So the
5345asterisk, `*', had to be removed from the interactive specification.
5346If you insert an `*' and evaluate the function definition, then the
5347next time you run the `zap-to-char' function on a read-only buffer,
5348you will not copy any text.
5349
5350That change aside, and a change to the documentation, the two versions
5351of the `zap-to-char' function are identical.
5352
5353Let us continue with the interactive specification.
5354
5355The second part of `"*p\ncZap to char: "' is the `p'. This part is
5356separated from the next part by a newline, `\n'. The `p' means that
5357the first argument to the function will be passed the value of a
5358`processed prefix'. The prefix argument is passed by typing `C-u'
5359and a number, or `M-' and a number. If the function is called
5360interactively without a prefix, 1 is passed to this argument.
5361
5362The third part of `"*p\ncZap to char: "' is `cZap to char: '. In
5363this part, the lower case `c' indicates that `interactive' expects a
5364prompt and that the argument will be a character. The prompt follows
5365the `c' and is the string `Zap to char: ' (with a space after the
5366colon to make it look good).
5367
5368What all this does is prepare the arguments to `zap-to-char' so they
5369are of the right type, and give the user a prompt.
5370
5371The Body of `zap-to-char'
5372-------------------------
5373
5374The body of the `zap-to-char' function contains the code that kills
5375(that is, removes) the text in the region from the current position
5376of the cursor up to and including the specified character. The first
5377part of the code looks like this:
5378
5379 (kill-region (point) ...
5380
5381`(point)' is the current position of the cursor.
5382
5383The next part of the code is an expression using `progn'. The body
5384of the `progn' consists of calls to `search-forward' and `point'.
5385
5386It is easier to understand how `progn' works after learning about
5387`search-forward', so we will look at `search-forward' and then at
5388`progn'.
5389
5390The `search-forward' Function
5391-----------------------------
5392
5393The `search-forward' function is used to locate the
5394zapped-for-character in `zap-to-char'. If the search is successful,
5395`search-forward' leaves point immediately after the last character in
5396the target string. (In `zap-to-char', the target string is just one
5397character long.) If the search is backwards, `search-forward' leaves
5398point just before the first character in the target. Also,
5399`search-forward' returns `t' for true. (Moving point is therefore a
5400`side effect'.)
5401
5402In `zap-to-char', the `search-forward' function looks like this:
5403
5404 (search-forward (char-to-string char) nil nil arg)
5405
5406The `search-forward' function takes four arguments:
5407
5408 1. The first argument is the target, what is searched for. This
5409 must be a string, such as `"z"'.
5410
5411 As it happens, the argument passed to `zap-to-char' is a single
5412 character. Because of the way computers are built, the Lisp
5413 interpreter may treat a single character as being different from
5414 a string of characters. Inside the computer, a single character
5415 has a different electronic format than a string of one
5416 character. (A single character can often be recorded in the
5417 computer using exactly one byte; but a string may be longer, and
5418 the computer needs to be ready for this.) Since the
5419 `search-forward' function searches for a string, the character
5420 that the `zap-to-char' function receives as its argument must be
5421 converted inside the computer from one format to the other;
5422 otherwise the `search-forward' function will fail. The
5423 `char-to-string' function is used to make this conversion.
5424
5425 2. The second argument bounds the search; it is specified as a
5426 position in the buffer. In this case, the search can go to the
5427 end of the buffer, so no bound is set and the second argument is
5428 `nil'.
5429
5430 3. The third argument tells the function what it should do if the
5431 search fails--it can signal an error (and print a message) or it
5432 can return `nil'. A `nil' as the third argument causes the
5433 function to signal an error when the search fails.
5434
5435 4. The fourth argument to `search-forward' is the repeat count--how
5436 many occurrences of the string to look for. This argument is
5437 optional and if the function is called without a repeat count,
5438 this argument is passed the value 1. If this argument is
5439 negative, the search goes backwards.
5440
5441In template form, a `search-forward' expression looks like this:
5442
5443 (search-forward "TARGET-STRING"
5444 LIMIT-OF-SEARCH
5445 WHAT-TO-DO-IF-SEARCH-FAILS
5446 REPEAT-COUNT)
5447
5448We will look at `progn' next.
5449
5450The `progn' Special Form
5451------------------------
5452
5453`progn' is a special form that causes each of its arguments to be
5454evaluated in sequence and then returns the value of the last one. The
5455preceding expressions are evaluated only for the side effects they
5456perform. The values produced by them are discarded.
5457
5458The template for a `progn' expression is very simple:
5459
5460 (progn
5461 BODY...)
5462
5463In `zap-to-char', the `progn' expression has to do two things: put
5464point in exactly the right position; and return the location of point
5465so that `kill-region' will know how far to kill to.
5466
5467The first argument to the `progn' is `search-forward'. When
5468`search-forward' finds the string, the function leaves point
5469immediately after the last character in the target string. (In this
5470case the target string is just one character long.) If the search is
5471backwards, `search-forward' leaves point just before the first
5472character in the target. The movement of point is a side effect.
5473
5474The second and last argument to `progn' is the expression `(point)'.
5475This expression returns the value of point, which in this case will
5476be the location to which it has been moved by `search-forward'. This
5477value is returned by the `progn' expression and is passed to
5478`kill-region' as `kill-region''s second argument.
5479
5480Summing up `zap-to-char'
5481------------------------
5482
5483Now that we have seen how `search-forward' and `progn' work, we can
5484see how the `zap-to-char' function works as a whole.
5485
5486The first argument to `kill-region' is the position of the cursor
5487when the `zap-to-char' command is given--the value of point at that
5488time. Within the `progn', the search function then moves point to
5489just after the zapped-to-character and `point' returns the value of
5490this location. The `kill-region' function puts together these two
5491values of point, the first one as the beginning of the region and the
5492second one as the end of the region, and removes the region.
5493
5494The `progn' special form is necessary because the `kill-region'
5495command takes two arguments; and it would fail if `search-forward'
5496and `point' expressions were written in sequence as two additional
5497arguments. The `progn' expression is a single argument to
5498`kill-region' and returns the one value that `kill-region' needs for
5499its second argument.
5500
5501`kill-region'
5502=============
5503
5504The `zap-to-char' function uses the `kill-region' function. This
5505function clips text from a region and copies that text to the kill
5506ring, from which it may be retrieved.
5507
5508The Emacs 21 version of that function uses `condition-case' and
5509`copy-region-as-kill', both of which we will explain.
5510`condition-case' is an important special form.
5511
5512In essence, the `kill-region' function calls `condition-case', which
5513takes three arguments. In this function, the first argument does
5514nothing. The second argument contains the code that does the work
5515when all goes well. The third argument contains the code that is
5516called in the event of an error.
5517
5518The Complete `kill-region' Definition
5519-------------------------------------
5520
5521We will go through the `condition-case' code in a moment. First, let
5522us look at the complete definition of `kill-region', with comments
5523added:
5524
5525 (defun kill-region (beg end)
5526 "Kill between point and mark.
5527 The text is deleted but saved in the kill ring."
5528 (interactive "r")
5529
5530 ;; 1. `condition-case' takes three arguments.
5531 ;; If the first argument is nil, as it is here,
5532 ;; information about the error signal is not
5533 ;; stored for use by another function.
5534 (condition-case nil
5535
5536 ;; 2. The second argument to `condition-case'
5537 ;; tells the Lisp interpreter what to do when all goes well.
5538
5539 ;; The `delete-and-extract-region' function usually does the
5540 ;; work. If the beginning and ending of the region are both
5541 ;; the same, then the variable `string' will be empty, or nil
5542 (let ((string (delete-and-extract-region beg end)))
5543
5544 ;; `when' is an `if' clause that cannot take an `else-part'.
5545 ;; Emacs normally sets the value of `last-command' to the
5546 ;; previous command.
5547 ;; `kill-append' concatenates the new string and the old.
5548 ;; `kill-new' inserts text into a new item in the kill ring.
5549 (when string
5550 (if (eq last-command 'kill-region)
5551 ;; if true, prepend string
5552 (kill-append string (< end beg))
5553 (kill-new string)))
5554 (setq this-command 'kill-region))
5555
5556 ;; 3. The third argument to `condition-case' tells the interpreter
5557 ;; what to do with an error.
5558 ;; The third argument has a conditions part and a body part.
5559 ;; If the conditions are met (in this case,
5560 ;; if text or buffer is read-only)
5561 ;; then the body is executed.
5562 ((buffer-read-only text-read-only) ;; this is the if-part
5563 ;; then...
5564 (copy-region-as-kill beg end)
5565 (if kill-read-only-ok ;; usually this variable is nil
5566 (message "Read only text copied to kill ring")
5567 ;; or else, signal an error if the buffer is read-only;
5568 (barf-if-buffer-read-only)
5569 ;; and, in any case, signal that the text is read-only.
5570 (signal 'text-read-only (list (current-buffer)))))))
5571
5572`condition-case'
5573----------------
5574
5575As we have seen earlier (*note Generate an Error Message: Making
5576Errors.), when the Emacs Lisp interpreter has trouble evaluating an
5577expression, it provides you with help; in the jargon, this is called
5578"signaling an error". Usually, the computer stops the program and
5579shows you a message.
5580
5581However, some programs undertake complicated actions. They should not
5582simply stop on an error. In the `kill-region' function, the most
5583likely error is that you will try to kill text that is read-only and
5584cannot be removed. So the `kill-region' function contains code to
5585handle this circumstance. This code, which makes up the body of the
5586`kill-region' function, is inside of a `condition-case' special form.
5587
5588The template for `condition-case' looks like this:
5589
5590 (condition-case
5591 VAR
5592 BODYFORM
5593 ERROR-HANDLER...)
5594
5595The second argument, BODYFORM, is straightforward. The
5596`condition-case' special form causes the Lisp interpreter to evaluate
5597the code in BODYFORM. If no error occurs, the special form returns
5598the code's value and produces the side-effects, if any.
5599
5600In short, the BODYFORM part of a `condition-case' expression
5601determines what should happen when everything works correctly.
5602
5603However, if an error occurs, among its other actions, the function
5604generating the error signal will define one or more error condition
5605names.
5606
5607An error handler is the third argument to `condition case'. An error
5608handler has two parts, a CONDITION-NAME and a BODY. If the
5609CONDITION-NAME part of an error handler matches a condition name
5610generated by an error, then the BODY part of the error handler is run.
5611
5612As you will expect, the CONDITION-NAME part of an error handler may
5613be either a single condition name or a list of condition names.
5614
5615Also, a complete `condition-case' expression may contain more than
5616one error handler. When an error occurs, the first applicable
5617handler is run.
5618
5619Lastly, the first argument to the `condition-case' expression, the
5620VAR argument, is sometimes bound to a variable that contains
5621information about the error. However, if that argument is nil, as is
5622the case in `kill-region', that information is discarded.
5623
5624In brief, in the `kill-region' function, the code `condition-case'
5625works like this:
5626
5627 IF NO ERRORS, RUN ONLY THIS CODE
5628 BUT, IF ERRORS, RUN THIS OTHER CODE.
5629
5630`delete-and-extract-region'
5631---------------------------
5632
5633A `condition-case' expression has two parts, a part that is evaluated
5634in the expectation that all will go well, but which may generate an
5635error; and a part that is evaluated when there is an error.
5636
5637First, let us look at the code in `kill-region' that is run in the
5638expectation that all goes well. This is the core of the function.
5639The code looks like this:
5640
5641 (let ((string (delete-and-extract-region beg end)))
5642 (when string
5643 (if (eq last-command 'kill-region)
5644 (kill-append string (< end beg))
5645 (kill-new string)))
5646 (setq this-command 'kill-region))
5647
5648It looks complicated because we have the new functions
5649`delete-and-extract-region', `kill-append', and `kill-new' as well as
5650the new variables, `last-command' and `this-command'.
5651
5652The `delete-and-extract-region' function is straightforward. It is a
5653built-in function that deletes the text in a region (a side effect)
5654and also returns that text. This is the function that actually
5655removes the text. (And if it cannot do that, it signals the error.)
5656
5657In this `let' expression, the text that `delete-and-extract-region'
5658returns is placed in the local variable called `string'. This is the
5659text that is removed from the buffer. (To be more precise, the
5660variable is set to point to the address of the extracted text; to say
5661it is `placed in' the variable is simply a shorthand.)
5662
5663If the variable `string' does point to text, that text is added to
5664the kill ring. The variable will have a `nil' value if no text was
5665removed.
5666
5667The code uses `when' to determine whether the variable `string'
5668points to text. A `when' statement is simply a programmers'
5669convenience. A `when' statement is an `if' statement without the
5670possibility of an else clause. In your mind, you can replace `when'
5671with `if' and understand what goes on. That is what the Lisp
5672interpreter does.
5673
5674Technically speaking, `when' is a Lisp macro. A Lisp "macro" enables
5675you to define new control constructs and other language features. It
5676tells the interpreter how to compute another Lisp expression which
5677will in turn compute the value. In this case, the `other expression'
5678is an `if' expression. For more about Lisp macros, see *Note Macros:
5679(elisp)Macros. The C programming language also provides macros.
5680These are different, but also useful. We will briefly look at C
5681macros in *Note Digression into C::.
5682
5683If the string has content, then another conditional expression is
5684executed. This is an `if' with both a then-part and an else-part.
5685
5686 (if (eq last-command 'kill-region)
5687 (kill-append string (< end beg))
5688 (kill-new string)))
5689
5690The then-part is evaluated if the previous command was another call to
5691`kill-region'; if not, the else-part is evaluated.
5692
5693`last-command' is a variable that comes with Emacs that we have not
5694seen before. Normally, whenever a function is executed, Emacs sets
5695the value of `last-command' to the previous command.
5696
5697In this segment of the definition, the `if' expression checks whether
5698the previous command was `kill-region'. If it was,
5699
5700 (kill-append string (< end beg))
5701
5702concatenates a copy of the newly clipped text to the just previously
5703clipped text in the kill ring. (If the `(< end beg))' expression is
5704true, `kill-append' prepends the string to the just previously
5705clipped text. For a detailed discussion, see *Note The `kill-append'
5706function: kill-append function.)
5707
5708If you then yank back the text, i.e., `paste' it, you get both pieces
5709of text at once. That way, if you delete two words in a row, and
5710then yank them back, you get both words, in their proper order, with
5711one yank. (The `(< end beg))' expression makes sure the order is
5712correct.)
5713
5714On the other hand, if the previous command is not `kill-region', then
5715the `kill-new' function is called, which adds the text to the kill
5716ring as the latest item, and sets the `kill-ring-yank-pointer'
5717variable to point to it.
5718
5719Digression into C
5720=================
5721
5722The `zap-to-char' command uses the `delete-and-extract-region'
5723function, which in turn uses two other functions,
5724`copy-region-as-kill' and `del_range_1'. The `copy-region-as-kill'
5725function will be described in a following section; it puts a copy of
5726the region in the kill ring so it can be yanked back. (*Note
5727`copy-region-as-kill': copy-region-as-kill.)
5728
5729The `delete-and-extract-region' function removes the contents of a
5730region and you cannot get them back.
5731
5732Unlike the other code discussed here, `delete-and-extract-region' is
5733not written in Emacs Lisp; it is written in C and is one of the
5734primitives of the GNU Emacs system. Since it is very simple, I will
5735digress briefly from Lisp and describe it here.
5736
5737Like many of the other Emacs primitives, `delete-and-extract-region'
5738is written as an instance of a C macro, a macro being a template for
5739code. The complete macro looks like this:
5740
5741 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
5742 Sdelete_and_extract_region, 2, 2, 0,
5743 "Delete the text between START and END and return it.")
5744 (start, end)
5745 Lisp_Object start, end;
5746 {
5747 validate_region (&start, &end);
5748 return del_range_1 (XINT (start), XINT (end), 1, 1);
5749 }
5750
5751Without going into the details of the macro writing process, let me
5752point out that this macro starts with the word `DEFUN'. The word
5753`DEFUN' was chosen since the code serves the same purpose as `defun'
5754does in Lisp. The word `DEFUN' is followed by seven parts inside of
5755parentheses:
5756
5757 * The first part is the name given to the function in Lisp,
5758 `delete-and-extract-region'.
5759
5760 * The second part is the name of the function in C,
5761 `Fdelete_and_extract_region'. By convention, it starts with
5762 `F'. Since C does not use hyphens in names, underscores are used
5763 instead.
5764
5765 * The third part is the name for the C constant structure that
5766 records information on this function for internal use. It is
5767 the name of the function in C but begins with an `S' instead of
5768 an `F'.
5769
5770 * The fourth and fifth parts specify the minimum and maximum
5771 number of arguments the function can have. This function
5772 demands exactly 2 arguments.
5773
5774 * The sixth part is nearly like the argument that follows the
5775 `interactive' declaration in a function written in Lisp: a letter
5776 followed, perhaps, by a prompt. The only difference from the
5777 Lisp is when the macro is called with no arguments. Then you
5778 write a `0' (which is a `null string'), as in this macro.
5779
5780 If you were to specify arguments, you would place them between
5781 quotation marks. The C macro for `goto-char' includes `"NGoto
5782 char: "' in this position to indicate that the function expects
5783 a raw prefix, in this case, a numerical location in a buffer,
5784 and provides a prompt.
5785
5786 * The seventh part is a documentation string, just like the one
5787 for a function written in Emacs Lisp, except that every newline
5788 must be written explicitly as `\n' followed by a backslash and
5789 carriage return.
5790
5791 Thus, the first two lines of documentation for `goto-char' are
5792 written like this:
5793
5794 "Set point to POSITION, a number or marker.\n\
5795 Beginning of buffer is position (point-min), end is (point-max).
5796
5797In a C macro, the formal parameters come next, with a statement of
5798what kind of object they are, followed by what might be called the
5799`body' of the macro. For `delete-and-extract-region' the `body'
5800consists of the following two lines:
5801
5802 validate_region (&start, &end);
5803 return del_range_1 (XINT (start), XINT (end), 1, 1);
5804
5805The first function, `validate_region' checks whether the values
5806passed as the beginning and end of the region are the proper type and
5807are within range. The second function, `del_range_1', actually
5808deletes the text.
5809
5810`del_range_1' is a complex function we will not look into. It
5811updates the buffer and does other things.
5812
5813However, it is worth looking at the two arguments passed to
5814`del_range'. These are `XINT (start)' and `XINT (end)'.
5815
5816As far as the C language is concerned, `start' and `end' are two
5817integers that mark the beginning and end of the region to be
5818deleted(1).
5819
5820In early versions of Emacs, these two numbers were thirty-two bits
5821long, but the code is slowly being generalized to handle other
5822lengths. Three of the available bits are used to specify the type of
5823information and a fourth bit is used for handling the computer's
5824memory; the remaining bits are used as `content'.
5825
5826`XINT' is a C macro that extracts the relevant number from the longer
5827collection of bits; the four other bits are discarded.
5828
5829The command in `delete-and-extract-region' looks like this:
5830
5831 del_range_1 (XINT (start), XINT (end), 1, 1);
5832
5833It deletes the region between the beginning position, `start', and
5834the ending position, `end'.
5835
5836From the point of view of the person writing Lisp, Emacs is all very
5837simple; but hidden underneath is a great deal of complexity to make it
5838all work.
5839
5840---------- Footnotes ----------
5841
5842(1) More precisely, and requiring more expert knowledge to
5843understand, the two integers are of type `Lisp_Object', which can
5844also be a C union instead of an integer type.
5845
5846Initializing a Variable with `defvar'
5847=====================================
5848
5849Unlike the `delete-and-extract-region' function, the
5850`copy-region-as-kill' function is written in Emacs Lisp. Two
5851functions within it, `kill-append' and `kill-new', copy a region in a
5852buffer and save it in a variable called the `kill-ring'. This
5853section describes how the `kill-ring' variable is created and
5854initialized using the `defvar' special form.
5855
5856(Again we note that the term `kill-ring' is a misnomer. The text
5857that is clipped out of the buffer can be brought back; it is not a
5858ring of corpses, but a ring of resurrectable text.)
5859
5860In Emacs Lisp, a variable such as the `kill-ring' is created and
5861given an initial value by using the `defvar' special form. The name
5862comes from "define variable".
5863
5864The `defvar' special form is similar to `setq' in that it sets the
5865value of a variable. It is unlike `setq' in two ways: first, it only
5866sets the value of the variable if the variable does not already have
5867a value. If the variable already has a value, `defvar' does not
5868override the existing value. Second, `defvar' has a documentation
5869string.
5870
5871(Another special form, `defcustom', is designed for variables that
5872people customize. It has more features than `defvar'. (*Note
5873Setting Variables with `defcustom': defcustom.)
5874
5875Seeing the Current Value of a Variable
5876--------------------------------------
5877
5878You can see the current value of a variable, any variable, by using
5879the `describe-variable' function, which is usually invoked by typing
5880`C-h v'. If you type `C-h v' and then `kill-ring' (followed by
5881<RET>) when prompted, you will see what is in your current kill
5882ring--this may be quite a lot! Conversely, if you have been doing
5883nothing this Emacs session except read this document, you may have
5884nothing in it. Also, you will see the documentation for `kill-ring':
5885
5886 Documentation:
5887 List of killed text sequences.
5888 Since the kill ring is supposed to interact nicely with cut-and-paste
5889 facilities offered by window systems, use of this variable should
5890 interact nicely with `interprogram-cut-function' and
5891 `interprogram-paste-function'. The functions `kill-new',
5892 `kill-append', and `current-kill' are supposed to implement this
5893 interaction; you may want to use them instead of manipulating the kill
5894 ring directly.
5895
5896The kill ring is defined by a `defvar' in the following way:
5897
5898 (defvar kill-ring nil
5899 "List of killed text sequences.
5900 ...")
5901
5902In this variable definition, the variable is given an initial value of
5903`nil', which makes sense, since if you have saved nothing, you want
5904nothing back if you give a `yank' command. The documentation string
5905is written just like the documentation string of a `defun'. As with
5906the documentation string of the `defun', the first line of the
5907documentation should be a complete sentence, since some commands,
5908like `apropos', print only the first line of documentation.
5909Succeeding lines should not be indented; otherwise they look odd when
5910you use `C-h v' (`describe-variable').
5911
5912`defvar' and an asterisk
5913------------------------
5914
5915In the past, Emacs used the `defvar' special form both for internal
5916variables that you would not expect a user to change and for
5917variables that you do expect a user to change. Although you can still
5918use `defvar' for user customizable variables, please use `defcustom'
5919instead, since that special form provides a path into the
5920Customization commands. (*Note Setting Variables with `defcustom':
5921defcustom.)
5922
5923When you specified a variable using the `defvar' special form, you
5924could distinguish a readily settable variable from others by typing
5925an asterisk, `*', in the first column of its documentation string.
5926For example:
5927
5928 (defvar shell-command-default-error-buffer nil
5929 "*Buffer name for `shell-command' ... error output.
5930 ... ")
5931
5932This means that you could (and still can) use the `edit-options'
5933command to change the value of `shell-command-default-error-buffer'
5934temporarily.
5935
5936However, options set using `edit-options' are set only for the
5937duration of your editing session. The new values are not saved
5938between sessions. Each time Emacs starts, it reads the original
5939value, unless you change the value within your `.emacs' file, either
5940by setting it manually or by using `customize'. *Note Your `.emacs'
5941File: Emacs Initialization.
5942
5943For me, the major use of the `edit-options' command is to suggest
5944variables that I might want to set in my `.emacs' file. I urge you
5945to look through the list. (*Note Editing Variable Values:
5946(emacs)Edit Options.)
5947
5948`copy-region-as-kill'
5949=====================
5950
5951The `copy-region-as-kill' function copies a region of text from a
5952buffer and (via either `kill-append' or `kill-new') saves it in the
5953`kill-ring'.
5954
5955If you call `copy-region-as-kill' immediately after a `kill-region'
5956command, Emacs appends the newly copied text to the previously copied
5957text. This means that if you yank back the text, you get it all,
5958from both this and the previous operation. On the other hand, if
5959some other command precedes the `copy-region-as-kill', the function
5960copies the text into a separate entry in the kill ring.
5961
5962The complete `copy-region-as-kill' function definition
5963------------------------------------------------------
5964
5965Here is the complete text of the version 21 `copy-region-as-kill'
5966function:
5967
5968 (defun copy-region-as-kill (beg end)
5969 "Save the region as if killed, but don't kill it.
5970 In Transient Mark mode, deactivate the mark.
5971 If `interprogram-cut-function' is non-nil, also save
5972 the text for a window system cut and paste."
5973 (interactive "r")
5974 (if (eq last-command 'kill-region)
5975 (kill-append (buffer-substring beg end) (< end beg))
5976 (kill-new (buffer-substring beg end)))
5977 (if transient-mark-mode
5978 (setq deactivate-mark t))
5979 nil)
5980
5981As usual, this function can be divided into its component parts:
5982
5983 (defun copy-region-as-kill (ARGUMENT-LIST)
5984 "DOCUMENTATION..."
5985 (interactive "r")
5986 BODY...)
5987
5988The arguments are `beg' and `end' and the function is interactive
5989with `"r"', so the two arguments must refer to the beginning and end
5990of the region. If you have been reading though this document from
5991the beginning, understanding these parts of a function is almost
5992becoming routine.
5993
5994The documentation is somewhat confusing unless you remember that the
5995word `kill' has a meaning different from its usual meaning. The
5996`Transient Mark' and `interprogram-cut-function' comments explain
5997certain side-effects.
5998
5999After you once set a mark, a buffer always contains a region. If you
6000wish, you can use Transient Mark mode to highlight the region
6001temporarily. (No one wants to highlight the region all the time, so
6002Transient Mark mode highlights it only at appropriate times. Many
6003people turn off Transient Mark mode, so the region is never
6004highlighted.)
6005
6006Also, a windowing system allows you to copy, cut, and paste among
6007different programs. In the X windowing system, for example, the
6008`interprogram-cut-function' function is `x-select-text', which works
6009with the windowing system's equivalent of the Emacs kill ring.
6010
6011The body of the `copy-region-as-kill' function starts with an `if'
6012clause. What this clause does is distinguish between two different
6013situations: whether or not this command is executed immediately after
6014a previous `kill-region' command. In the first case, the new region
6015is appended to the previously copied text. Otherwise, it is inserted
6016into the beginning of the kill ring as a separate piece of text from
6017the previous piece.
6018
6019The last two lines of the function prevent the region from lighting up
6020if Transient Mark mode is turned on.
6021
6022The body of `copy-region-as-kill' merits discussion in detail.
6023
6024The Body of `copy-region-as-kill'
6025---------------------------------
6026
6027The `copy-region-as-kill' function works in much the same way as the
6028`kill-region' function (*note `kill-region': kill-region.). Both are
6029written so that two or more kills in a row combine their text into a
6030single entry. If you yank back the text from the kill ring, you get
6031it all in one piece. Moreover, kills that kill forward from the
6032current position of the cursor are added to the end of the previously
6033copied text and commands that copy text backwards add it to the
6034beginning of the previously copied text. This way, the words in the
6035text stay in the proper order.
6036
6037Like `kill-region', the `copy-region-as-kill' function makes use of
6038the `last-command' variable that keeps track of the previous Emacs
6039command.
6040
6041`last-command' and `this-command'
6042.................................
6043
6044Normally, whenever a function is executed, Emacs sets the value of
6045`this-command' to the function being executed (which in this case
6046would be `copy-region-as-kill'). At the same time, Emacs sets the
6047value of `last-command' to the previous value of `this-command'.
6048
6049In the first part of the body of the `copy-region-as-kill' function,
6050an `if' expression determines whether the value of `last-command' is
6051`kill-region'. If so, the then-part of the `if' expression is
6052evaluated; it uses the `kill-append' function to concatenate the text
6053copied at this call to the function with the text already in the
6054first element (the CAR) of the kill ring. On the other hand, if the
6055value of `last-command' is not `kill-region', then the
6056`copy-region-as-kill' function attaches a new element to the kill
6057ring using the `kill-new' function.
6058
6059The `if' expression reads as follows; it uses `eq', which is a
6060function we have not yet seen:
6061
6062 (if (eq last-command 'kill-region)
6063 ;; then-part
6064 (kill-append (buffer-substring beg end) (< end beg))
6065 ;; else-part
6066 (kill-new (buffer-substring beg end)))
6067
6068The `eq' function tests whether its first argument is the same Lisp
6069object as its second argument. The `eq' function is similar to the
6070`equal' function in that it is used to test for equality, but differs
6071in that it determines whether two representations are actually the
6072same object inside the computer, but with different names. `equal'
6073determines whether the structure and contents of two expressions are
6074the same.
6075
6076If the previous command was `kill-region', then the Emacs Lisp
6077interpreter calls the `kill-append' function
6078
6079The `kill-append' function
6080..........................
6081
6082The `kill-append' function looks like this:
6083
6084 (defun kill-append (string before-p)
6085 "Append STRING to the end of the latest kill in the kill ring.
6086 If BEFORE-P is non-nil, prepend STRING to the kill.
6087 If `interprogram-cut-function' is set, pass the resulting kill to
6088 it."
6089 (kill-new (if before-p
6090 (concat string (car kill-ring))
6091 (concat (car kill-ring) string))
6092 t))
6093
6094The `kill-append' function is fairly straightforward. It uses the
6095`kill-new' function, which we will discuss in more detail in a moment.
6096
6097First, let us look at the conditional that is one of the two arguments
6098to `kill-new'. It uses `concat' to concatenate the new text to the
6099CAR of the kill ring. Whether it prepends or appends the text
6100depends on the results of an `if' expression:
6101
6102 (if before-p ; if-part
6103 (concat string (car kill-ring)) ; then-part
6104 (concat (car kill-ring) string)) ; else-part
6105
6106If the region being killed is before the region that was killed in the
6107last command, then it should be prepended before the material that was
6108saved in the previous kill; and conversely, if the killed text follows
6109what was just killed, it should be appended after the previous text.
6110The `if' expression depends on the predicate `before-p' to decide
6111whether the newly saved text should be put before or after the
6112previously saved text.
6113
6114The symbol `before-p' is the name of one of the arguments to
6115`kill-append'. When the `kill-append' function is evaluated, it is
6116bound to the value returned by evaluating the actual argument. In
6117this case, this is the expression `(< end beg)'. This expression
6118does not directly determine whether the killed text in this command
6119is located before or after the kill text of the last command; what is
6120does is determine whether the value of the variable `end' is less
6121than the value of the variable `beg'. If it is, it means that the
6122user is most likely heading towards the beginning of the buffer.
6123Also, the result of evaluating the predicate expression, `(< end
6124beg)', will be true and the text will be prepended before the
6125previous text. On the other hand, if the value of the variable `end'
6126is greater than the value of the variable `beg', the text will be
6127appended after the previous text.
6128
6129When the newly saved text will be prepended, then the string with the
6130new text will be concatenated before the old text:
6131
6132 (concat string (car kill-ring))
6133
6134But if the text will be appended, it will be concatenated after the
6135old text:
6136
6137 (concat (car kill-ring) string))
6138
6139To understand how this works, we first need to review the `concat'
6140function. The `concat' function links together or unites two strings
6141of text. The result is a string. For example:
6142
6143 (concat "abc" "def")
6144 => "abcdef"
6145
6146 (concat "new "
6147 (car '("first element" "second element")))
6148 => "new first element"
6149
6150 (concat (car
6151 '("first element" "second element")) " modified")
6152 => "first element modified"
6153
6154We can now make sense of `kill-append': it modifies the contents of
6155the kill ring. The kill ring is a list, each element of which is
6156saved text. The `kill-append' function uses the `kill-new' function
6157which in turn uses the `setcar' function.
6158
6159The `kill-new' function
6160.......................
6161
6162The `kill-new' function looks like this:
6163
6164 (defun kill-new (string &optional replace)
6165 "Make STRING the latest kill in the kill ring.
6166 Set the kill-ring-yank pointer to point to it.
6167 If `interprogram-cut-function' is non-nil, apply it to STRING.
6168 Optional second argument REPLACE non-nil means that STRING will replace
6169 the front of the kill ring, rather than being added to the list."
6170 (and (fboundp 'menu-bar-update-yank-menu)
6171 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
6172 (if (and replace kill-ring)
6173 (setcar kill-ring string)
6174 (setq kill-ring (cons string kill-ring))
6175 (if (> (length kill-ring) kill-ring-max)
6176 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
6177 (setq kill-ring-yank-pointer kill-ring)
6178 (if interprogram-cut-function
6179 (funcall interprogram-cut-function string (not replace))))
6180
6181As usual, we can look at this function in parts.
6182
6183The first line of the documentation makes sense:
6184
6185 Make STRING the latest kill in the kill ring.
6186
6187Let's skip over the rest of the documentation for the moment.
6188
6189Also, let's skip over the first two lines of code, those involving
6190`menu-bar-update-yank-menu'. We will explain them below.
6191
6192The critical lines are these:
6193
6194 (if (and replace kill-ring)
6195 ;; then
6196 (setcar kill-ring string)
6197 ;; else
6198 (setq kill-ring (cons string kill-ring))
6199 (if (> (length kill-ring) kill-ring-max)
6200 ;; avoid overly long kill ring
6201 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
6202 (setq kill-ring-yank-pointer kill-ring)
6203 (if interprogram-cut-function
6204 (funcall interprogram-cut-function string (not replace))))
6205
6206The conditional test is `(and replace kill-ring)'. This will be true
6207when two conditions are met: the kill ring has something in it, and
6208the `replace' variable is true.
6209
6210The `kill-append' function sets `replace' to be true; then, when the
6211kill ring has at least one item in it, the `setcar' expression is
6212executed:
6213
6214 (setcar kill-ring string)
6215
6216The `setcar' function actually changes the first element of the
6217`kill-ring' list to the value of `string'. It replaces the first
6218element.
6219
6220On the other hand, if the kill ring is empty, or replace is false, the
6221else-part of the condition is executed:
6222
6223 (setq kill-ring (cons string kill-ring))
6224 (if (> (length kill-ring) kill-ring-max)
6225 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
6226
6227This expression first constructs a new version of the kill ring by
6228prepending `string' to the existing kill ring as a new element. Then
6229it executes a second `if' clause. This second `if' clause keeps the
6230kill ring from growing too long.
6231
6232Let's look at these two expressions in order.
6233
6234The `setq' line of the else-part sets the new value of the kill ring
6235to what results from adding the string being killed to the old kill
6236ring.
6237
6238We can see how this works with an example:
6239
6240 (setq example-list '("here is a clause" "another clause"))
6241
6242After evaluating this expression with `C-x C-e', you can evaluate
6243`example-list' and see what it returns:
6244
6245 example-list
6246 => ("here is a clause" "another clause")
6247
6248Now, we can add a new element on to this list by evaluating the
6249following expression:
6250
6251 (setq example-list (cons "a third clause" example-list))
6252
6253When we evaluate `example-list', we find its value is:
6254
6255 example-list
6256 => ("a third clause" "here is a clause" "another clause")
6257
6258Thus, the third clause was added to the list by `cons'.
6259
6260This is exactly similar to what the `setq' and `cons' do in the
6261function. Here is the line again:
6262
6263 (setq kill-ring (cons string kill-ring))
6264
6265Now for the second part of the `if' clause. This expression keeps
6266the kill ring from growing too long. It looks like this:
6267
6268 (if (> (length kill-ring) kill-ring-max)
6269 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
6270
6271The code checks whether the length of the kill ring is greater than
6272the maximum permitted length. This is the value of `kill-ring-max'
6273(which is 60, by default). If the length of the kill ring is too
6274long, then this code sets the last element of the kill ring to `nil'.
6275It does this by using two functions, `nthcdr' and `setcdr'.
6276
6277We looked at `setcdr' earlier (*note `setcdr': setcdr.). It sets the
6278CDR of a list, just as `setcar' sets the CAR of a list. In this
6279case, however, `setcdr' will not be setting the CDR of the whole kill
6280ring; the `nthcdr' function is used to cause it to set the CDR of the
6281next to last element of the kill ring--this means that since the CDR
6282of the next to last element is the last element of the kill ring, it
6283will set the last element of the kill ring.
6284
6285The `nthcdr' function works by repeatedly taking the CDR of a
6286list--it takes the CDR of the CDR of the CDR ... It does this N
6287times and returns the results.
6288
6289Thus, if we had a four element list that was supposed to be three
6290elements long, we could set the CDR of the next to last element to
6291`nil', and thereby shorten the list.
6292
6293You can see this by evaluating the following three expressions in
6294turn. First set the value of `trees' to `(maple oak pine birch)',
6295then set the CDR of its second CDR to `nil' and then find the value
6296of `trees':
6297
6298 (setq trees '(maple oak pine birch))
6299 => (maple oak pine birch)
6300
6301 (setcdr (nthcdr 2 trees) nil)
6302 => nil
6303
6304 trees
6305 => (maple oak pine)
6306
6307(The value returned by the `setcdr' expression is `nil' since that is
6308what the CDR is set to.)
6309
6310To repeat, in `kill-new', the `nthcdr' function takes the CDR a
6311number of times that is one less than the maximum permitted size of
6312the kill ring and sets the CDR of that element (which will be the
6313rest of the elements in the kill ring) to `nil'. This prevents the
6314kill ring from growing too long.
6315
6316The next to last expression in the `kill-new' function is
6317
6318 (setq kill-ring-yank-pointer kill-ring)
6319
6320The `kill-ring-yank-pointer' is a global variable that is set to be
6321the `kill-ring'.
6322
6323Even though the `kill-ring-yank-pointer' is called a `pointer', it is
6324a variable just like the kill ring. However, the name has been
6325chosen to help humans understand how the variable is used. The
6326variable is used in functions such as `yank' and `yank-pop' (*note
6327Yanking Text Back: Yanking.).
6328
6329Now, to return to the first two lines in the body of the function:
6330
6331 (and (fboundp 'menu-bar-update-yank-menu)
6332 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
6333
6334This is an expression whose first element is the function `and'.
6335
6336The `and' special form evaluates each of its arguments until one of
6337the arguments returns a value of `nil', in which case the `and'
6338expression returns `nil'; however, if none of the arguments returns a
6339value of `nil', the value resulting from evaluating the last argument
6340is returned. (Since such a value is not `nil', it is considered true
6341in Emacs Lisp.) In other words, an `and' expression returns a true
6342value only if all its arguments are true.
6343
6344In this case, the expression tests first to see whether
6345`menu-bar-update-yank-menu' exists as a function, and if so, calls
6346it. The `fboundp' function returns true if the symbol it is testing
6347has a function definition that `is not void'. If the symbol's
6348function definition were void, we would receive an error message, as
6349we did when we created errors intentionally (*note Generate an Error
6350Message: Making Errors.).
6351
6352Essentially, the `and' is an `if' expression that reads like this:
6353
6354 if THE-MENU-BAR-FUNCTION-EXISTS
6355 then EXECUTE-IT
6356
6357`menu-bar-update-yank-menu' is one of the functions that make it
6358possible to use the `Select and Paste' menu in the Edit item of a menu
6359bar; using a mouse, you can look at the various pieces of text you
6360have saved and select one piece to paste.
6361
6362Finally, the last expression in the `kill-new' function adds the
6363newly copied string to whatever facility exists for copying and
6364pasting among different programs running in a windowing system. In
6365the X Windowing system, for example, the `x-select-text' function
6366takes the string and stores it in memory operated by X. You can paste
6367the string in another program, such as an Xterm.
6368
6369The expression looks like this:
6370
6371 (if interprogram-cut-function
6372 (funcall interprogram-cut-function string (not replace))))
6373
6374If an `interprogram-cut-function' exists, then Emacs executes
6375`funcall', which in turn calls its first argument as a function and
6376passes the remaining arguments to it. (Incidentally, as far as I can
6377see, this `if' expression could be replaced by an `and' expression
6378similar to the one in the first part of the function.)
6379
6380We are not going to discuss windowing systems and other programs
6381further, but merely note that this is a mechanism that enables GNU
6382Emacs to work easily and well with other programs.
6383
6384This code for placing text in the kill ring, either concatenated with
6385an existing element or as a new element, leads us to the code for
6386bringing back text that has been cut out of the buffer--the yank
6387commands. However, before discussing the yank commands, it is better
6388to learn how lists are implemented in a computer. This will make
6389clear such mysteries as the use of the term `pointer'.
6390
6391Review
6392======
6393
6394Here is a brief summary of some recently introduced functions.
6395
6396`car'
6397`cdr'
6398 `car' returns the first element of a list; `cdr' returns the
6399 second and subsequent elements of a list.
6400
6401 For example:
6402
6403 (car '(1 2 3 4 5 6 7))
6404 => 1
6405 (cdr '(1 2 3 4 5 6 7))
6406 => (2 3 4 5 6 7)
6407
6408`cons'
6409 `cons' constructs a list by prepending its first argument to its
6410 second argument.
6411
6412 For example:
6413
6414 (cons 1 '(2 3 4))
6415 => (1 2 3 4)
6416
6417`nthcdr'
6418 Return the result of taking CDR `n' times on a list. The `rest
6419 of the rest', as it were.
6420
6421 For example:
6422
6423 (nthcdr 3 '(1 2 3 4 5 6 7))
6424 => (4 5 6 7)
6425
6426`setcar'
6427`setcdr'
6428 `setcar' changes the first element of a list; `setcdr' changes
6429 the second and subsequent elements of a list.
6430
6431 For example:
6432
6433 (setq triple '(1 2 3))
6434
6435 (setcar triple '37)
6436
6437 triple
6438 => (37 2 3)
6439
6440 (setcdr triple '("foo" "bar"))
6441
6442 triple
6443 => (37 "foo" "bar")
6444
6445`progn'
6446 Evaluate each argument in sequence and then return the value of
6447 the last.
6448
6449 For example:
6450
6451 (progn 1 2 3 4)
6452 => 4
6453
6454`save-restriction'
6455 Record whatever narrowing is in effect in the current buffer, if
6456 any, and restore that narrowing after evaluating the arguments.
6457
6458`search-forward'
6459 Search for a string, and if the string is found, move point.
6460
6461 Takes four arguments:
6462
6463 1. The string to search for.
6464
6465 2. Optionally, the limit of the search.
6466
6467 3. Optionally, what to do if the search fails, return `nil' or
6468 an error message.
6469
6470 4. Optionally, how many times to repeat the search; if
6471 negative, the search goes backwards.
6472
6473`kill-region'
6474`delete-region'
6475`copy-region-as-kill'
6476 `kill-region' cuts the text between point and mark from the
6477 buffer and stores that text in the kill ring, so you can get it
6478 back by yanking.
6479
6480 `delete-and-extract-region' removes the text between point and
6481 mark from the buffer and throws it away. You cannot get it back.
6482
6483 `copy-region-as-kill' copies the text between point and mark into
6484 the kill ring, from which you can get it by yanking. The
6485 function does not cut or remove the text from the buffer.
6486
6487Searching Exercises
6488===================
6489
6490 * Write an interactive function that searches for a string. If the
6491 search finds the string, leave point after it and display a
6492 message that says "Found!". (Do not use `search-forward' for
6493 the name of this function; if you do, you will overwrite the
6494 existing version of `search-forward' that comes with Emacs. Use
6495 a name such as `test-search' instead.)
6496
6497 * Write a function that prints the third element of the kill ring
6498 in the echo area, if any; if the kill ring does not contain a
6499 third element, print an appropriate message.
6500
6501How Lists are Implemented
6502*************************
6503
6504In Lisp, atoms are recorded in a straightforward fashion; if the
6505implementation is not straightforward in practice, it is, nonetheless,
6506straightforward in theory. The atom `rose', for example, is recorded
6507as the four contiguous letters `r', `o', `s', `e'. A list, on the
6508other hand, is kept differently. The mechanism is equally simple,
6509but it takes a moment to get used to the idea. A list is kept using
6510a series of pairs of pointers. In the series, the first pointer in
6511each pair points to an atom or to another list, and the second
6512pointer in each pair points to the next pair, or to the symbol `nil',
6513which marks the end of the list.
6514
6515A pointer itself is quite simply the electronic address of what is
6516pointed to. Hence, a list is kept as a series of electronic
6517addresses.
6518
6519Lists diagrammed
6520================
6521
6522For example, the list `(rose violet buttercup)' has three elements,
6523`rose', `violet', and `buttercup'. In the computer, the electronic
6524address of `rose' is recorded in a segment of computer memory along
6525with the address that gives the electronic address of where the atom
6526`violet' is located; and that address (the one that tells where
6527`violet' is located) is kept along with an address that tells where
6528the address for the atom `buttercup' is located.
6529
6530This sounds more complicated than it is and is easier seen in a
6531diagram:
6532
6533 ___ ___ ___ ___ ___ ___
6534 |___|___|--> |___|___|--> |___|___|--> nil
6535 | | |
6536 | | |
6537 --> rose --> violet --> buttercup
6538
6539
6540
6541In the diagram, each box represents a word of computer memory that
6542holds a Lisp object, usually in the form of a memory address. The
6543boxes, i.e. the addresses, are in pairs. Each arrow points to what
6544the address is the address of, either an atom or another pair of
6545addresses. The first box is the electronic address of `rose' and the
6546arrow points to `rose'; the second box is the address of the next
6547pair of boxes, the first part of which is the address of `violet' and
6548the second part of which is the address of the next pair. The very
6549last box points to the symbol `nil', which marks the end of the list.
6550
6551When a variable is set to a list with a function such as `setq', it
6552stores the address of the first box in the variable. Thus,
6553evaluation of the expression
6554
6555 (setq bouquet '(rose violet buttercup))
6556
6557creates a situation like this:
6558
6559 bouquet
6560 |
6561 | ___ ___ ___ ___ ___ ___
6562 --> |___|___|--> |___|___|--> |___|___|--> nil
6563 | | |
6564 | | |
6565 --> rose --> violet --> buttercup
6566
6567
6568
6569In this example, the symbol `bouquet' holds the address of the first
6570pair of boxes.
6571
6572This same list can be illustrated in a different sort of box notation
6573like this:
6574
6575 bouquet
6576 |
6577 | -------------- --------------- ----------------
6578 | | car | cdr | | car | cdr | | car | cdr |
6579 -->| rose | o------->| violet | o------->| butter- | nil |
6580 | | | | | | | cup | |
6581 -------------- --------------- ----------------
6582
6583
6584
6585(Symbols consist of more than pairs of addresses, but the structure of
6586a symbol is made up of addresses. Indeed, the symbol `bouquet'
6587consists of a group of address-boxes, one of which is the address of
6588the printed word `bouquet', a second of which is the address of a
6589function definition attached to the symbol, if any, a third of which
6590is the address of the first pair of address-boxes for the list `(rose
6591violet buttercup)', and so on. Here we are showing that the symbol's
6592third address-box points to the first pair of address-boxes for the
6593list.)
6594
6595If a symbol is set to the CDR of a list, the list itself is not
6596changed; the symbol simply has an address further down the list. (In
6597the jargon, CAR and CDR are `non-destructive'.) Thus, evaluation of
6598the following expression
6599
6600 (setq flowers (cdr bouquet))
6601
6602produces this:
6603
6604
6605 bouquet flowers
6606 | |
6607 | ___ ___ | ___ ___ ___ ___
6608 --> | | | --> | | | | | |
6609 |___|___|----> |___|___|--> |___|___|--> nil
6610 | | |
6611 | | |
6612 --> rose --> violet --> buttercup
6613
6614
6615
6616
6617The value of `flowers' is `(violet buttercup)', which is to say, the
6618symbol `flowers' holds the address of the pair of address-boxes, the
6619first of which holds the address of `violet', and the second of which
6620holds the address of `buttercup'.
6621
6622A pair of address-boxes is called a "cons cell" or "dotted pair".
6623*Note List Type: (elisp)List Type, and *Note Dotted Pair Notation:
6624(elisp)Dotted Pair Notation, for more information about cons cells
6625and dotted pairs.
6626
6627The function `cons' adds a new pair of addresses to the front of a
6628series of addresses like that shown above. For example, evaluating
6629the expression
6630
6631 (setq bouquet (cons 'lily bouquet))
6632
6633produces:
6634
6635
6636 bouquet flowers
6637 | |
6638 | ___ ___ ___ ___ | ___ ___ ___ ___
6639 --> | | | | | | --> | | | | | |
6640 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
6641 | | | |
6642 | | | |
6643 --> lily --> rose --> violet --> buttercup
6644
6645
6646
6647
6648However, this does not change the value of the symbol `flowers', as
6649you can see by evaluating the following,
6650
6651 (eq (cdr (cdr bouquet)) flowers)
6652
6653which returns `t' for true.
6654
6655Until it is reset, `flowers' still has the value `(violet
6656buttercup)'; that is, it has the address of the cons cell whose first
6657address is of `violet'. Also, this does not alter any of the
6658pre-existing cons cells; they are all still there.
6659
6660Thus, in Lisp, to get the CDR of a list, you just get the address of
6661the next cons cell in the series; to get the CAR of a list, you get
6662the address of the first element of the list; to `cons' a new element
6663on a list, you add a new cons cell to the front of the list. That is
6664all there is to it! The underlying structure of Lisp is brilliantly
6665simple!
6666
6667And what does the last address in a series of cons cells refer to? It
6668is the address of the empty list, of `nil'.
6669
6670In summary, when a Lisp variable is set to a value, it is provided
6671with the address of the list to which the variable refers.
6672
6673Symbols as a Chest of Drawers
6674=============================
6675
6676In an earlier section, I suggested that you might imagine a symbol as
6677being a chest of drawers. The function definition is put in one
6678drawer, the value in another, and so on. What is put in the drawer
6679holding the value can be changed without affecting the contents of the
6680drawer holding the function definition, and vice-versa.
6681
6682Actually, what is put in each drawer is the address of the value or
6683function definition. It is as if you found an old chest in the attic,
6684and in one of its drawers you found a map giving you directions to
6685where the buried treasure lies.
6686
6687(In addition to its name, symbol definition, and variable value, a
6688symbol has a `drawer' for a "property list" which can be used to
6689record other information. Property lists are not discussed here; see
6690*Note Property Lists: (elisp)Property Lists.)
6691
6692Here is a fanciful representation:
6693
6694
6695 Chest of Drawers Contents of Drawers
6696
6697 __ o0O0o __
6698 / \
6699 ---------------------
6700 | directions to | [map to]
6701 | symbol name | bouquet
6702 | |
6703 +---------------------+
6704 | directions to |
6705 | symbol definition | [none]
6706 | |
6707 +---------------------+
6708 | directions to | [map to]
6709 | variable value | (rose violet buttercup)
6710 | |
6711 +---------------------+
6712 | directions to |
6713 | property list | [not described here]
6714 | |
6715 +---------------------+
6716 |/ \|
6717
6718
6719
6720
6721Exercise
6722========
6723
6724Set `flowers' to `violet' and `buttercup'. Cons two more flowers on
6725to this list and set this new list to `more-flowers'. Set the CAR of
6726`flowers' to a fish. What does the `more-flowers' list now contain?
6727
6728Yanking Text Back
6729*****************
6730
6731Whenever you cut text out of a buffer with a `kill' command in GNU
6732Emacs, you can bring it back with a `yank' command. The text that is
6733cut out of the buffer is put in the kill ring and the yank commands
6734insert the appropriate contents of the kill ring back into a buffer
6735(not necessarily the original buffer).
6736
6737A simple `C-y' (`yank') command inserts the first item from the kill
6738ring into the current buffer. If the `C-y' command is followed
6739immediately by `M-y', the first element is replaced by the second
6740element. Successive `M-y' commands replace the second element with
6741the third, fourth, or fifth element, and so on. When the last
6742element in the kill ring is reached, it is replaced by the first
6743element and the cycle is repeated. (Thus the kill ring is called a
6744`ring' rather than just a `list'. However, the actual data structure
6745that holds the text is a list. *Note Handling the Kill Ring: Kill
6746Ring, for the details of how the list is handled as a ring.)
6747
6748Kill Ring Overview
6749==================
6750
6751The kill ring is a list of textual strings. This is what it looks
6752like:
6753
6754 ("some text" "a different piece of text" "yet more text")
6755
6756If this were the contents of my kill ring and I pressed `C-y', the
6757string of characters saying `some text' would be inserted in this
6758buffer where my cursor is located.
6759
6760The `yank' command is also used for duplicating text by copying it.
6761The copied text is not cut from the buffer, but a copy of it is put
6762on the kill ring and is inserted by yanking it back.
6763
6764Three functions are used for bringing text back from the kill ring:
6765`yank', which is usually bound to `C-y'; `yank-pop', which is usually
6766bound to `M-y'; and `rotate-yank-pointer', which is used by the two
6767other functions.
6768
6769These functions refer to the kill ring through a variable called the
6770`kill-ring-yank-pointer'. Indeed, the insertion code for both the
6771`yank' and `yank-pop' functions is:
6772
6773 (insert (car kill-ring-yank-pointer))
6774
6775To begin to understand how `yank' and `yank-pop' work, it is first
6776necessary to look at the `kill-ring-yank-pointer' variable and the
6777`rotate-yank-pointer' function.
6778
6779The `kill-ring-yank-pointer' Variable
6780=====================================
6781
6782`kill-ring-yank-pointer' is a variable, just as `kill-ring' is a
6783variable. It points to something by being bound to the value of what
6784it points to, like any other Lisp variable.
6785
6786Thus, if the value of the kill ring is:
6787
6788 ("some text" "a different piece of text" "yet more text")
6789
6790and the `kill-ring-yank-pointer' points to the second clause, the
6791value of `kill-ring-yank-pointer' is:
6792
6793 ("a different piece of text" "yet more text")
6794
6795As explained in the previous chapter (*note List Implementation::),
6796the computer does not keep two different copies of the text being
6797pointed to by both the `kill-ring' and the `kill-ring-yank-pointer'.
6798The words "a different piece of text" and "yet more text" are not
6799duplicated. Instead, the two Lisp variables point to the same pieces
6800of text. Here is a diagram:
6801
6802 kill-ring kill-ring-yank-pointer
6803 | |
6804 | ___ ___ | ___ ___ ___ ___
6805 ---> | | | --> | | | | | |
6806 |___|___|----> |___|___|--> |___|___|--> nil
6807 | | |
6808 | | |
6809 | | --> "yet more text"
6810 | |
6811 | --> "a different piece of text
6812 |
6813 --> "some text"
6814
6815
6816
6817
6818Both the variable `kill-ring' and the variable
6819`kill-ring-yank-pointer' are pointers. But the kill ring itself is
6820usually described as if it were actually what it is composed of. The
6821`kill-ring' is spoken of as if it were the list rather than that it
6822points to the list. Conversely, the `kill-ring-yank-pointer' is
6823spoken of as pointing to a list.
6824
6825These two ways of talking about the same thing sound confusing at
6826first but make sense on reflection. The kill ring is generally
6827thought of as the complete structure of data that holds the
6828information of what has recently been cut out of the Emacs buffers.
6829The `kill-ring-yank-pointer' on the other hand, serves to
6830indicate--that is, to `point to'--that part of the kill ring of which
6831the first element (the CAR) will be inserted.
6832
6833The `rotate-yank-pointer' function changes the element in the kill
6834ring to which the `kill-ring-yank-pointer' points; when the pointer
6835is set to point to the next element beyond the end of the kill ring,
6836it automatically sets it to point to the first element of the kill
6837ring. This is how the list is transformed into a ring. The
6838`rotate-yank-pointer' function itself is not difficult, but contains
6839many details. It and the much simpler `yank' and `yank-pop'
6840functions are described in an appendix. *Note Handling the Kill
6841Ring: Kill Ring.
6842
6843Exercises with `yank' and `nthcdr'
6844==================================
6845
6846 * Using `C-h v' (`describe-variable'), look at the value of your
6847 kill ring. Add several items to your kill ring; look at its
6848 value again. Using `M-y' (`yank-pop)', move all the way around
6849 the kill ring. How many items were in your kill ring? Find the
6850 value of `kill-ring-max'. Was your kill ring full, or could you
6851 have kept more blocks of text within it?
6852
6853 * Using `nthcdr' and `car', construct a series of expressions to
6854 return the first, second, third, and fourth elements of a list.
6855
6856Loops and Recursion
6857*******************
6858
6859Emacs Lisp has two primary ways to cause an expression, or a series of
6860expressions, to be evaluated repeatedly: one uses a `while' loop, and
6861the other uses "recursion".
6862
6863Repetition can be very valuable. For example, to move forward four
6864sentences, you need only write a program that will move forward one
6865sentence and then repeat the process four times. Since a computer
6866does not get bored or tired, such repetitive action does not have the
6867deleterious effects that excessive or the wrong kinds of repetition
6868can have on humans.
6869
6870People mostly write Emacs Lisp functions using `while' loops and
6871their kin; but you can use recursion, which provides a very powerful
6872way to think about and then to solve problems(1).
6873
6874---------- Footnotes ----------
6875
6876(1) You can write recursive functions to be frugal or wasteful of
6877mental or computer resources; as it happens, methods that people find
6878easy--that are frugal of `mental resources'--sometimes use
6879considerable computer resources. Emacs was designed to run on
6880machines that we now consider limited and its default settings are
6881conservative. You may want to increase the values of
6882`max-specpdl-size' and `max-lisp-eval-depth'. In my `.emacs' file, I
6883set them to 15 and 30 times their default value.
6884
6885`while'
6886=======
6887
6888The `while' special form tests whether the value returned by
6889evaluating its first argument is true or false. This is similar to
6890what the Lisp interpreter does with an `if'; what the interpreter does
6891next, however, is different.
6892
6893In a `while' expression, if the value returned by evaluating the
6894first argument is false, the Lisp interpreter skips the rest of the
6895expression (the "body" of the expression) and does not evaluate it.
6896However, if the value is true, the Lisp interpreter evaluates the body
6897of the expression and then again tests whether the first argument to
6898`while' is true or false. If the value returned by evaluating the
6899first argument is again true, the Lisp interpreter again evaluates the
6900body of the expression.
6901
6902The template for a `while' expression looks like this:
6903
6904 (while TRUE-OR-FALSE-TEST
6905 BODY...)
6906
6907Looping with `while'
6908--------------------
6909
6910So long as the true-or-false-test of the `while' expression returns a
6911true value when it is evaluated, the body is repeatedly evaluated.
6912This process is called a loop since the Lisp interpreter repeats the
6913same thing again and again, like an airplane doing a loop. When the
6914result of evaluating the true-or-false-test is false, the Lisp
6915interpreter does not evaluate the rest of the `while' expression and
6916`exits the loop'.
6917
6918Clearly, if the value returned by evaluating the first argument to
6919`while' is always true, the body following will be evaluated again
6920and again ... and again ... forever. Conversely, if the value
6921returned is never true, the expressions in the body will never be
6922evaluated. The craft of writing a `while' loop consists of choosing
6923a mechanism such that the true-or-false-test returns true just the
6924number of times that you want the subsequent expressions to be
6925evaluated, and then have the test return false.
6926
6927The value returned by evaluating a `while' is the value of the
6928true-or-false-test. An interesting consequence of this is that a
6929`while' loop that evaluates without error will return `nil' or false
6930regardless of whether it has looped 1 or 100 times or none at all. A
6931`while' expression that evaluates successfully never returns a true
6932value! What this means is that `while' is always evaluated for its
6933side effects, which is to say, the consequences of evaluating the
6934expressions within the body of the `while' loop. This makes sense.
6935It is not the mere act of looping that is desired, but the
6936consequences of what happens when the expressions in the loop are
6937repeatedly evaluated.
6938
6939A `while' Loop and a List
6940-------------------------
6941
6942A common way to control a `while' loop is to test whether a list has
6943any elements. If it does, the loop is repeated; but if it does not,
6944the repetition is ended. Since this is an important technique, we
6945will create a short example to illustrate it.
6946
6947A simple way to test whether a list has elements is to evaluate the
6948list: if it has no elements, it is an empty list and will return the
6949empty list, `()', which is a synonym for `nil' or false. On the
6950other hand, a list with elements will return those elements when it
6951is evaluated. Since Emacs Lisp considers as true any value that is
6952not `nil', a list that returns elements will test true in a `while'
6953loop.
6954
6955For example, you can set the variable `empty-list' to `nil' by
6956evaluating the following `setq' expression:
6957
6958 (setq empty-list ())
6959
6960After evaluating the `setq' expression, you can evaluate the variable
6961`empty-list' in the usual way, by placing the cursor after the symbol
6962and typing `C-x C-e'; `nil' will appear in your echo area:
6963
6964 empty-list
6965
6966On the other hand, if you set a variable to be a list with elements,
6967the list will appear when you evaluate the variable, as you can see by
6968evaluating the following two expressions:
6969
6970 (setq animals '(gazelle giraffe lion tiger))
6971
6972 animals
6973
6974Thus, to create a `while' loop that tests whether there are any items
6975in the list `animals', the first part of the loop will be written
6976like this:
6977
6978 (while animals
6979 ...
6980
6981When the `while' tests its first argument, the variable `animals' is
6982evaluated. It returns a list. So long as the list has elements, the
6983`while' considers the results of the test to be true; but when the
6984list is empty, it considers the results of the test to be false.
6985
6986To prevent the `while' loop from running forever, some mechanism
6987needs to be provided to empty the list eventually. An oft-used
6988technique is to have one of the subsequent forms in the `while'
6989expression set the value of the list to be the CDR of the list. Each
6990time the `cdr' function is evaluated, the list will be made shorter,
6991until eventually only the empty list will be left. At this point,
6992the test of the `while' loop will return false, and the arguments to
6993the `while' will no longer be evaluated.
6994
6995For example, the list of animals bound to the variable `animals' can
6996be set to be the CDR of the original list with the following
6997expression:
6998
6999 (setq animals (cdr animals))
7000
7001If you have evaluated the previous expressions and then evaluate this
7002expression, you will see `(giraffe lion tiger)' appear in the echo
7003area. If you evaluate the expression again, `(lion tiger)' will
7004appear in the echo area. If you evaluate it again and yet again,
7005`(tiger)' appears and then the empty list, shown by `nil'.
7006
7007A template for a `while' loop that uses the `cdr' function repeatedly
7008to cause the true-or-false-test eventually to test false looks like
7009this:
7010
7011 (while TEST-WHETHER-LIST-IS-EMPTY
7012 BODY...
7013 SET-LIST-TO-CDR-OF-LIST)
7014
7015This test and use of `cdr' can be put together in a function that
7016goes through a list and prints each element of the list on a line of
7017its own.
7018
7019An Example: `print-elements-of-list'
7020------------------------------------
7021
7022The `print-elements-of-list' function illustrates a `while' loop with
7023a list.
7024
7025The function requires several lines for its output. If you are
7026reading this in Emacs 21 or a later version, you can evaluate the
7027following expression inside of Info, as usual.
7028
7029If you are using an earlier version of Emacs, you need to copy the
7030necessary expressions to your `*scratch*' buffer and evaluate them
7031there. This is because the echo area had only one line in the
7032earlier versions.
7033
7034You can copy the expressions by marking the beginning of the region
7035with `C-<SPC>' (`set-mark-command'), moving the cursor to the end of
7036the region and then copying the region using `M-w'
7037(`copy-region-as-kill'). In the `*scratch*' buffer, you can yank the
7038expressions back by typing `C-y' (`yank').
7039
7040After you have copied the expressions to the `*scratch*' buffer,
7041evaluate each expression in turn. Be sure to evaluate the last
7042expression, `(print-elements-of-list animals)', by typing `C-u C-x
7043C-e', that is, by giving an argument to `eval-last-sexp'. This will
7044cause the result of the evaluation to be printed in the `*scratch*'
7045buffer instead of being printed in the echo area. (Otherwise you
7046will see something like this in your echo area:
7047`^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil', in which each `^J'
7048stands for a `newline'.)
7049
7050If you are using Emacs 21 or later, you can evaluate these expressions
7051directly in the Info buffer, and the echo area will grow to show the
7052results.
7053
7054 (setq animals '(gazelle giraffe lion tiger))
7055
7056 (defun print-elements-of-list (list)
7057 "Print each element of LIST on a line of its own."
7058 (while list
7059 (print (car list))
7060 (setq list (cdr list))))
7061
7062 (print-elements-of-list animals)
7063
7064When you evaluate the three expressions in sequence, you will see
7065this:
7066
7067 gazelle
7068
7069 giraffe
7070
7071 lion
7072
7073 tiger
7074 nil
7075
7076Each element of the list is printed on a line of its own (that is what
7077the function `print' does) and then the value returned by the
7078function is printed. Since the last expression in the function is the
7079`while' loop, and since `while' loops always return `nil', a `nil' is
7080printed after the last element of the list.
7081
7082A Loop with an Incrementing Counter
7083-----------------------------------
7084
7085A loop is not useful unless it stops when it ought. Besides
7086controlling a loop with a list, a common way of stopping a loop is to
7087write the first argument as a test that returns false when the correct
7088number of repetitions are complete. This means that the loop must
7089have a counter--an expression that counts how many times the loop
7090repeats itself.
7091
7092The test can be an expression such as `(< count desired-number)'
7093which returns `t' for true if the value of `count' is less than the
7094`desired-number' of repetitions and `nil' for false if the value of
7095`count' is equal to or is greater than the `desired-number'. The
7096expression that increments the count can be a simple `setq' such as
7097`(setq count (1+ count))', where `1+' is a built-in function in Emacs
7098Lisp that adds 1 to its argument. (The expression `(1+ count)' has
7099the same result as `(+ count 1)', but is easier for a human to read.)
7100
7101The template for a `while' loop controlled by an incrementing counter
7102looks like this:
7103
7104 SET-COUNT-TO-INITIAL-VALUE
7105 (while (< count desired-number) ; true-or-false-test
7106 BODY...
7107 (setq count (1+ count))) ; incrementer
7108
7109Note that you need to set the initial value of `count'; usually it is
7110set to 1.
7111
7112Example with incrementing counter
7113.................................
7114
7115Suppose you are playing on the beach and decide to make a triangle of
7116pebbles, putting one pebble in the first row, two in the second row,
7117three in the third row and so on, like this:
7118
7119
7120 *
7121 * *
7122 * * *
7123 * * * *
7124
7125
7126(About 2500 years ago, Pythagoras and others developed the beginnings
7127of number theory by considering questions such as this.)
7128
7129Suppose you want to know how many pebbles you will need to make a
7130triangle with 7 rows?
7131
7132Clearly, what you need to do is add up the numbers from 1 to 7. There
7133are two ways to do this; start with the smallest number, one, and add
7134up the list in sequence, 1, 2, 3, 4 and so on; or start with the
7135largest number and add the list going down: 7, 6, 5, 4 and so on.
7136Because both mechanisms illustrate common ways of writing `while'
7137loops, we will create two examples, one counting up and the other
7138counting down. In this first example, we will start with 1 and add
71392, 3, 4 and so on.
7140
7141If you are just adding up a short list of numbers, the easiest way to
7142do it is to add up all the numbers at once. However, if you do not
7143know ahead of time how many numbers your list will have, or if you
7144want to be prepared for a very long list, then you need to design
7145your addition so that what you do is repeat a simple process many
7146times instead of doing a more complex process once.
7147
7148For example, instead of adding up all the pebbles all at once, what
7149you can do is add the number of pebbles in the first row, 1, to the
7150number in the second row, 2, and then add the total of those two rows
7151to the third row, 3. Then you can add the number in the fourth row,
71524, to the total of the first three rows; and so on.
7153
7154The critical characteristic of the process is that each repetitive
7155action is simple. In this case, at each step we add only two numbers,
7156the number of pebbles in the row and the total already found. This
7157process of adding two numbers is repeated again and again until the
7158last row has been added to the total of all the preceding rows. In a
7159more complex loop the repetitive action might not be so simple, but
7160it will be simpler than doing everything all at once.
7161
7162The parts of the function definition
7163....................................
7164
7165The preceding analysis gives us the bones of our function definition:
7166first, we will need a variable that we can call `total' that will be
7167the total number of pebbles. This will be the value returned by the
7168function.
7169
7170Second, we know that the function will require an argument: this
7171argument will be the total number of rows in the triangle. It can be
7172called `number-of-rows'.
7173
7174Finally, we need a variable to use as a counter. We could call this
7175variable `counter', but a better name is `row-number'. That is
7176because what the counter does is count rows, and a program should be
7177written to be as understandable as possible.
7178
7179When the Lisp interpreter first starts evaluating the expressions in
7180the function, the value of `total' should be set to zero, since we
7181have not added anything to it. Then the function should add the
7182number of pebbles in the first row to the total, and then add the
7183number of pebbles in the second to the total, and then add the number
7184of pebbles in the third row to the total, and so on, until there are
7185no more rows left to add.
7186
7187Both `total' and `row-number' are used only inside the function, so
7188they can be declared as local variables with `let' and given initial
7189values. Clearly, the initial value for `total' should be 0. The
7190initial value of `row-number' should be 1, since we start with the
7191first row. This means that the `let' statement will look like this:
7192
7193 (let ((total 0)
7194 (row-number 1))
7195 BODY...)
7196
7197After the internal variables are declared and bound to their initial
7198values, we can begin the `while' loop. The expression that serves as
7199the test should return a value of `t' for true so long as the
7200`row-number' is less than or equal to the `number-of-rows'. (If the
7201expression tests true only so long as the row number is less than the
7202number of rows in the triangle, the last row will never be added to
7203the total; hence the row number has to be either less than or equal
7204to the number of rows.)
7205
7206Lisp provides the `<=' function that returns true if the value of its
7207first argument is less than or equal to the value of its second
7208argument and false otherwise. So the expression that the `while'
7209will evaluate as its test should look like this:
7210
7211 (<= row-number number-of-rows)
7212
7213The total number of pebbles can be found by repeatedly adding the
7214number of pebbles in a row to the total already found. Since the
7215number of pebbles in the row is equal to the row number, the total
7216can be found by adding the row number to the total. (Clearly, in a
7217more complex situation, the number of pebbles in the row might be
7218related to the row number in a more complicated way; if this were the
7219case, the row number would be replaced by the appropriate expression.)
7220
7221 (setq total (+ total row-number))
7222
7223What this does is set the new value of `total' to be equal to the sum
7224of adding the number of pebbles in the row to the previous total.
7225
7226After setting the value of `total', the conditions need to be
7227established for the next repetition of the loop, if there is one.
7228This is done by incrementing the value of the `row-number' variable,
7229which serves as a counter. After the `row-number' variable has been
7230incremented, the true-or-false-test at the beginning of the `while'
7231loop tests whether its value is still less than or equal to the value
7232of the `number-of-rows' and if it is, adds the new value of the
7233`row-number' variable to the `total' of the previous repetition of
7234the loop.
7235
7236The built-in Emacs Lisp function `1+' adds 1 to a number, so the
7237`row-number' variable can be incremented with this expression:
7238
7239 (setq row-number (1+ row-number))
7240
7241Putting the function definition together
7242........................................
7243
7244We have created the parts for the function definition; now we need to
7245put them together.
7246
7247First, the contents of the `while' expression:
7248
7249 (while (<= row-number number-of-rows) ; true-or-false-test
7250 (setq total (+ total row-number))
7251 (setq row-number (1+ row-number))) ; incrementer
7252
7253Along with the `let' expression varlist, this very nearly completes
7254the body of the function definition. However, it requires one final
7255element, the need for which is somewhat subtle.
7256
7257The final touch is to place the variable `total' on a line by itself
7258after the `while' expression. Otherwise, the value returned by the
7259whole function is the value of the last expression that is evaluated
7260in the body of the `let', and this is the value returned by the
7261`while', which is always `nil'.
7262
7263This may not be evident at first sight. It almost looks as if the
7264incrementing expression is the last expression of the whole function.
7265But that expression is part of the body of the `while'; it is the
7266last element of the list that starts with the symbol `while'.
7267Moreover, the whole of the `while' loop is a list within the body of
7268the `let'.
7269
7270In outline, the function will look like this:
7271
7272 (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
7273 "DOCUMENTATION..."
7274 (let (VARLIST)
7275 (while (TRUE-OR-FALSE-TEST)
7276 BODY-OF-WHILE... )
7277 ... ) ; Need final expression here.
7278
7279The result of evaluating the `let' is what is going to be returned by
7280the `defun' since the `let' is not embedded within any containing
7281list, except for the `defun' as a whole. However, if the `while' is
7282the last element of the `let' expression, the function will always
7283return `nil'. This is not what we want! Instead, what we want is
7284the value of the variable `total'. This is returned by simply
7285placing the symbol as the last element of the list starting with
7286`let'. It gets evaluated after the preceding elements of the list
7287are evaluated, which means it gets evaluated after it has been
7288assigned the correct value for the total.
7289
7290It may be easier to see this by printing the list starting with `let'
7291all on one line. This format makes it evident that the VARLIST and
7292`while' expressions are the second and third elements of the list
7293starting with `let', and the `total' is the last element:
7294
7295 (let (VARLIST) (while (TRUE-OR-FALSE-TEST) BODY-OF-WHILE... ) total)
7296
7297Putting everything together, the `triangle' function definition looks
7298like this:
7299
7300 (defun triangle (number-of-rows) ; Version with
7301 ; incrementing counter.
7302 "Add up the number of pebbles in a triangle.
7303 The first row has one pebble, the second row two pebbles,
7304 the third row three pebbles, and so on.
7305 The argument is NUMBER-OF-ROWS."
7306 (let ((total 0)
7307 (row-number 1))
7308 (while (<= row-number number-of-rows)
7309 (setq total (+ total row-number))
7310 (setq row-number (1+ row-number)))
7311 total))
7312
7313After you have installed `triangle' by evaluating the function, you
7314can try it out. Here are two examples:
7315
7316 (triangle 4)
7317
7318 (triangle 7)
7319
7320The sum of the first four numbers is 10 and the sum of the first seven
7321numbers is 28.
7322
7323Loop with a Decrementing Counter
7324--------------------------------
7325
7326Another common way to write a `while' loop is to write the test so
7327that it determines whether a counter is greater than zero. So long
7328as the counter is greater than zero, the loop is repeated. But when
7329the counter is equal to or less than zero, the loop is stopped. For
7330this to work, the counter has to start out greater than zero and then
7331be made smaller and smaller by a form that is evaluated repeatedly.
7332
7333The test will be an expression such as `(> counter 0)' which returns
7334`t' for true if the value of `counter' is greater than zero, and
7335`nil' for false if the value of `counter' is equal to or less than
7336zero. The expression that makes the number smaller and smaller can
7337be a simple `setq' such as `(setq counter (1- counter))', where `1-'
7338is a built-in function in Emacs Lisp that subtracts 1 from its
7339argument.
7340
7341The template for a decrementing `while' loop looks like this:
7342
7343 (while (> counter 0) ; true-or-false-test
7344 BODY...
7345 (setq counter (1- counter))) ; decrementer
7346
7347Example with decrementing counter
7348.................................
7349
7350To illustrate a loop with a decrementing counter, we will rewrite the
7351`triangle' function so the counter decreases to zero.
7352
7353This is the reverse of the earlier version of the function. In this
7354case, to find out how many pebbles are needed to make a triangle with
73553 rows, add the number of pebbles in the third row, 3, to the number
7356in the preceding row, 2, and then add the total of those two rows to
7357the row that precedes them, which is 1.
7358
7359Likewise, to find the number of pebbles in a triangle with 7 rows, add
7360the number of pebbles in the seventh row, 7, to the number in the
7361preceding row, which is 6, and then add the total of those two rows to
7362the row that precedes them, which is 5, and so on. As in the previous
7363example, each addition only involves adding two numbers, the total of
7364the rows already added up and the number of pebbles in the row that is
7365being added to the total. This process of adding two numbers is
7366repeated again and again until there are no more pebbles to add.
7367
7368We know how many pebbles to start with: the number of pebbles in the
7369last row is equal to the number of rows. If the triangle has seven
7370rows, the number of pebbles in the last row is 7. Likewise, we know
7371how many pebbles are in the preceding row: it is one less than the
7372number in the row.
7373
7374The parts of the function definition
7375....................................
7376
7377We start with three variables: the total number of rows in the
7378triangle; the number of pebbles in a row; and the total number of
7379pebbles, which is what we want to calculate. These variables can be
7380named `number-of-rows', `number-of-pebbles-in-row', and `total',
7381respectively.
7382
7383Both `total' and `number-of-pebbles-in-row' are used only inside the
7384function and are declared with `let'. The initial value of `total'
7385should, of course, be zero. However, the initial value of
7386`number-of-pebbles-in-row' should be equal to the number of rows in
7387the triangle, since the addition will start with the longest row.
7388
7389This means that the beginning of the `let' expression will look like
7390this:
7391
7392 (let ((total 0)
7393 (number-of-pebbles-in-row number-of-rows))
7394 BODY...)
7395
7396The total number of pebbles can be found by repeatedly adding the
7397number of pebbles in a row to the total already found, that is, by
7398repeatedly evaluating the following expression:
7399
7400 (setq total (+ total number-of-pebbles-in-row))
7401
7402After the `number-of-pebbles-in-row' is added to the `total', the
7403`number-of-pebbles-in-row' should be decremented by one, since the
7404next time the loop repeats, the preceding row will be added to the
7405total.
7406
7407The number of pebbles in a preceding row is one less than the number
7408of pebbles in a row, so the built-in Emacs Lisp function `1-' can be
7409used to compute the number of pebbles in the preceding row. This can
7410be done with the following expression:
7411
7412 (setq number-of-pebbles-in-row
7413 (1- number-of-pebbles-in-row))
7414
7415Finally, we know that the `while' loop should stop making repeated
7416additions when there are no pebbles in a row. So the test for the
7417`while' loop is simply:
7418
7419 (while (> number-of-pebbles-in-row 0)
7420
7421Putting the function definition together
7422........................................
7423
7424We can put these expressions together to create a function definition
7425that works. However, on examination, we find that one of the local
7426variables is unneeded!
7427
7428The function definition looks like this:
7429
7430 ;;; First subtractive version.
7431 (defun triangle (number-of-rows)
7432 "Add up the number of pebbles in a triangle."
7433 (let ((total 0)
7434 (number-of-pebbles-in-row number-of-rows))
7435 (while (> number-of-pebbles-in-row 0)
7436 (setq total (+ total number-of-pebbles-in-row))
7437 (setq number-of-pebbles-in-row
7438 (1- number-of-pebbles-in-row)))
7439 total))
7440
7441As written, this function works.
7442
7443However, we do not need `number-of-pebbles-in-row'.
7444
7445When the `triangle' function is evaluated, the symbol
7446`number-of-rows' will be bound to a number, giving it an initial
7447value. That number can be changed in the body of the function as if
7448it were a local variable, without any fear that such a change will
7449effect the value of the variable outside of the function. This is a
7450very useful characteristic of Lisp; it means that the variable
7451`number-of-rows' can be used anywhere in the function where
7452`number-of-pebbles-in-row' is used.
7453
7454Here is a second version of the function written a bit more cleanly:
7455
7456 (defun triangle (number) ; Second version.
7457 "Return sum of numbers 1 through NUMBER inclusive."
7458 (let ((total 0))
7459 (while (> number 0)
7460 (setq total (+ total number))
7461 (setq number (1- number)))
7462 total))
7463
7464In brief, a properly written `while' loop will consist of three parts:
7465
7466 1. A test that will return false after the loop has repeated itself
7467 the correct number of times.
7468
7469 2. An expression the evaluation of which will return the value
7470 desired after being repeatedly evaluated.
7471
7472 3. An expression to change the value passed to the
7473 true-or-false-test so that the test returns false after the loop
7474 has repeated itself the right number of times.
7475
7476Save your time: `dolist' and `dotimes'
7477======================================
7478
7479In addition to `while', both `dolist' and `dotimes' provide for
7480looping. Sometimes these are quicker to write than the equivalent
7481`while' loop. Both are Lisp macros. (*Note Macros: (elisp)Macros. )
7482
7483`dolist' works like a `while' loop that `CDRs down a list': `dolist'
7484automatically shortens the list each time it loops--takes the CDR of
7485the list--and binds the CAR of each shorter version of the list to
7486the first of its arguments.
7487
7488`dotimes' loops a specific number of times: you specify the number.
7489
7490The `dolist' Macro
7491..................
7492
7493Suppose, for example, you want to reverse a list, so that "first"
7494"second" "third" becomes "third" "second" "first".
7495
7496In practice, you would use the `reverse' function, like this:
7497
7498 (setq animals '(gazelle giraffe lion tiger))
7499
7500 (reverse animals)
7501
7502Here is how you could reverse the list using a `while' loop:
7503
7504 (setq animals '(gazelle giraffe lion tiger))
7505
7506 (defun reverse-list-with-while (list)
7507 "Using while, reverse the order of LIST."
7508 (let (value) ; make sure list starts empty
7509 (while list
7510 (setq value (cons (car list) value))
7511 (setq list (cdr list)))
7512 value))
7513
7514 (reverse-list-with-while animals)
7515
7516And here is how you could use the `dolist' macro:
7517
7518 (setq animals '(gazelle giraffe lion tiger))
7519
7520 (defun reverse-list-with-dolist (list)
7521 "Using dolist, reverse the order of LIST."
7522 (let (value) ; make sure list starts empty
7523 (dolist (element list value)
7524 (setq value (cons element value)))))
7525
7526 (reverse-list-with-dolist animals)
7527
7528In Info, you can place your cursor after the closing parenthesis of
7529each expression and type `C-x C-e'; in each case, you should see
7530
7531 (tiger lion giraffe gazelle)
7532
7533in the echo area.
7534
7535For this example, the existing `reverse' function is obviously best.
7536The `while' loop is just like our first example (*note A `while' Loop
7537and a List: Loop Example.). The `while' first checks whether the
7538list has elements; if so, it constructs a new list by adding the
7539first element of the list to the existing list (which in the first
7540iteration of the loop is `nil'). Since the second element is
7541prepended in front of the first element, and the third element is
7542prepended in front of the second element, the list is reversed.
7543
7544In the expression using a `while' loop, the `(setq list (cdr list))'
7545expression shortens the list, so the `while' loop eventually stops.
7546In addition, it provides the `cons' expression with a new first
7547element by creating a new and shorter list at each repetition of the
7548loop.
7549
7550The `dolist' expression does very much the same as the `while'
7551expression, except that the `dolist' macro does some of the work you
7552have to do when writing a `while' expression.
7553
7554Like a `while' loop, a `dolist' loops. What is different is that it
7555automatically shortens the list each time it loops -- it `CDRs down
7556the list' on its own -- and it automatically binds the CAR of each
7557shorter version of the list to the first of its arguments.
7558
7559In the example, the CAR of each shorter version of the list is
7560referred to using the symbol `element', the list itself is called
7561`list', and the value returned is called `value'. The remainder of
7562the `dolist' expression is the body.
7563
7564The `dolist' expression binds the CAR of each shorter version of the
7565list to `element' and then evaluates the body of the expression; and
7566repeats the loop. The result is returned in `value'.
7567
7568The `dotimes' Macro
7569...................
7570
7571The `dotimes' macro is similar to `dolist', except that it loops a
7572specific number of times.
7573
7574The first argument to `dotimes' is assigned the numbers 0, 1, 2 and
7575so forth each time around the loop, and the value of the third
7576argument is returned. You need to provide the value of the second
7577argument, which is how many times the macro loops.
7578
7579For example, the following binds the numbers from 0 up to, but not
7580including, the number 3 to the first argument, NUMBER, and then
7581constructs a list of the three numbers. (The first number is 0, the
7582second number is 1, and the third number is 2; this makes a total of
7583three numbers in all, starting with zero as the first number.)
7584
7585 (let (value) ; otherwise a value is a void variable
7586 (dotimes (number 3 value)
7587 (setq value (cons number value))))
7588
7589 => (2 1 0)
7590
7591`dotimes' returns `value', so the way to use `dotimes' is to operate
7592on some expression NUMBER number of times and then return the result,
7593either as a list or an atom.
7594
7595Here is an example of a `defun' that uses `dotimes' to add up the
7596number of pebbles in a triangle.
7597
7598 (defun triangle-using-dotimes (number-of-rows)
7599 "Using dotimes, add up the number of pebbles in a triangle."
7600 (let ((total 0)) ; otherwise a total is a void variable
7601 (dotimes (number number-of-rows total)
7602 (setq total (+ total (1+ number))))))
7603
7604 (triangle-using-dotimes 4)
7605
7606Recursion
7607=========
7608
7609A recursive function contains code that tells the Lisp interpreter to
7610call a program that runs exactly like itself, but with slightly
7611different arguments. The code runs exactly the same because it has
7612the same name. However, even though the program has the same name, it
7613is not the same entity. It is different. In the jargon, it is a
7614different `instance'.
7615
7616Eventually, if the program is written correctly, the `slightly
7617different arguments' will become sufficiently different from the first
7618arguments that the final instance will stop.
7619
7620Building Robots: Extending the Metaphor
7621---------------------------------------
7622
7623It is sometimes helpful to think of a running program as a robot that
7624does a job. In doing its job, a recursive function calls on a second
7625robot to help it. The second robot is identical to the first in every
7626way, except that the second robot helps the first and has been passed
7627different arguments than the first.
7628
7629In a recursive function, the second robot may call a third; and the
7630third may call a fourth, and so on. Each of these is a different
7631entity; but all are clones.
7632
7633Since each robot has slightly different instructions--the arguments
7634will differ from one robot to the next--the last robot should know
7635when to stop.
7636
7637Let's expand on the metaphor in which a computer program is a robot.
7638
7639A function definition provides the blueprints for a robot. When you
7640install a function definition, that is, when you evaluate a `defun'
7641special form, you install the necessary equipment to build robots.
7642It is as if you were in a factory, setting up an assembly line.
7643Robots with the same name are built according to the same blueprints.
7644So they have, as it were, the same `model number', but a different
7645`serial number'.
7646
7647We often say that a recursive function `calls itself'. What we mean
7648is that the instructions in a recursive function cause the Lisp
7649interpreter to run a different function that has the same name and
7650does the same job as the first, but with different arguments.
7651
7652It is important that the arguments differ from one instance to the
7653next; otherwise, the process will never stop.
7654
7655The Parts of a Recursive Definition
7656-----------------------------------
7657
7658A recursive function typically contains a conditional expression which
7659has three parts:
7660
7661 1. A true-or-false-test that determines whether the function is
7662 called again, here called the "do-again-test".
7663
7664 2. The name of the function. When this name is called, a new
7665 instance of the function--a new robot, as it were--is created
7666 and told what to do.
7667
7668 3. An expression that returns a different value each time the
7669 function is called, here called the "next-step-expression".
7670 Consequently, the argument (or arguments) passed to the new
7671 instance of the function will be different from that passed to
7672 the previous instance. This causes the conditional expression,
7673 the "do-again-test", to test false after the correct number of
7674 repetitions.
7675
7676Recursive functions can be much simpler than any other kind of
7677function. Indeed, when people first start to use them, they often
7678look so mysteriously simple as to be incomprehensible. Like riding a
7679bicycle, reading a recursive function definition takes a certain knack
7680which is hard at first but then seems simple.
7681
7682There are several different common recursive patterns. A very simple
7683pattern looks like this:
7684
7685 (defun NAME-OF-RECURSIVE-FUNCTION (ARGUMENT-LIST)
7686 "DOCUMENTATION..."
7687 (if DO-AGAIN-TEST
7688 BODY...
7689 (NAME-OF-RECURSIVE-FUNCTION
7690 NEXT-STEP-EXPRESSION)))
7691
7692Each time a recursive function is evaluated, a new instance of it is
7693created and told what to do. The arguments tell the instance what to
7694do.
7695
7696An argument is bound to the value of the next-step-expression. Each
7697instance runs with a different value of the next-step-expression.
7698
7699The value in the next-step-expression is used in the do-again-test.
7700
7701The value returned by the next-step-expression is passed to the new
7702instance of the function, which evaluates it (or some
7703transmogrification of it) to determine whether to continue or stop.
7704The next-step-expression is designed so that the do-again-test returns
7705false when the function should no longer be repeated.
7706
7707The do-again-test is sometimes called the "stop condition", since it
7708stops the repetitions when it tests false.
7709
7710Recursion with a List
7711---------------------
7712
7713The example of a `while' loop that printed the elements of a list of
7714numbers can be written recursively. Here is the code, including an
7715expression to set the value of the variable `animals' to a list.
7716
7717If you are using Emacs 20 or before, this example must be copied to
7718the `*scratch*' buffer and each expression must be evaluated there.
7719Use `C-u C-x C-e' to evaluate the `(print-elements-recursively
7720animals)' expression so that the results are printed in the buffer;
7721otherwise the Lisp interpreter will try to squeeze the results into
7722the one line of the echo area.
7723
7724Also, place your cursor immediately after the last closing parenthesis
7725of the `print-elements-recursively' function, before the comment.
7726Otherwise, the Lisp interpreter will try to evaluate the comment.
7727
7728If you are using Emacs 21 or later, you can evaluate this expression
7729directly in Info.
7730
7731 (setq animals '(gazelle giraffe lion tiger))
7732
7733 (defun print-elements-recursively (list)
7734 "Print each element of LIST on a line of its own.
7735 Uses recursion."
7736 (if list ; do-again-test
7737 (progn
7738 (print (car list)) ; body
7739 (print-elements-recursively ; recursive call
7740 (cdr list))))) ; next-step-expression
7741
7742 (print-elements-recursively animals)
7743
7744The `print-elements-recursively' function first tests whether there
7745is any content in the list; if there is, the function prints the
7746first element of the list, the CAR of the list. Then the function
7747`invokes itself', but gives itself as its argument, not the whole
7748list, but the second and subsequent elements of the list, the CDR of
7749the list.
7750
7751Put another way, if the list is not empty, the function invokes
7752another instance of code that is similar to the initial code, but is a
7753different thread of execution, with different arguments than the first
7754instance.
7755
7756Put in yet another way, if the list is not empty, the first robot
7757assemblies a second robot and tells it what to do; the second robot is
7758a different individual from the first, but is the same model.
7759
7760When the second evaluation occurs, the `if' expression is evaluated
7761and if true, prints the first element of the list it receives as its
7762argument (which is the second element of the original list). Then
7763the function `calls itself' with the CDR of the list it is invoked
7764with, which (the second time around) is the CDR of the CDR of the
7765original list.
7766
7767Note that although we say that the function `calls itself', what we
7768mean is that the Lisp interpreter assembles and instructs a new
7769instance of the program. The new instance is a clone of the first,
7770but is a separate individual.
7771
7772Each time the function `invokes itself', it invokes itself on a
7773shorter version of the original list. It creates a new instance that
7774works on a shorter list.
7775
7776Eventually, the function invokes itself on an empty list. It creates
7777a new instance whose argument is `nil'. The conditional expression
7778tests the value of `list'. Since the value of `list' is `nil', the
7779`if' expression tests false so the then-part is not evaluated. The
7780function as a whole then returns `nil'.
7781
7782When you evaluate `(print-elements-recursively animals)' in the
7783`*scratch*' buffer, you see this result:
7784
7785 gazelle
7786
7787 giraffe
7788
7789 lion
7790
7791 tiger
7792 nil
7793
7794Recursion in Place of a Counter
7795-------------------------------
7796
7797The `triangle' function described in a previous section can also be
7798written recursively. It looks like this:
7799
7800 (defun triangle-recursively (number)
7801 "Return the sum of the numbers 1 through NUMBER inclusive.
7802 Uses recursion."
7803 (if (= number 1) ; do-again-test
7804 1 ; then-part
7805 (+ number ; else-part
7806 (triangle-recursively ; recursive call
7807 (1- number))))) ; next-step-expression
7808
7809 (triangle-recursively 7)
7810
7811You can install this function by evaluating it and then try it by
7812evaluating `(triangle-recursively 7)'. (Remember to put your cursor
7813immediately after the last parenthesis of the function definition,
7814before the comment.) The function evaluates to 28.
7815
7816To understand how this function works, let's consider what happens in
7817the various cases when the function is passed 1, 2, 3, or 4 as the
7818value of its argument.
7819
7820An argument of 1 or 2
7821.....................
7822
7823First, what happens if the value of the argument is 1?
7824
7825The function has an `if' expression after the documentation string.
7826It tests whether the value of `number' is equal to 1; if so, Emacs
7827evaluates the then-part of the `if' expression, which returns the
7828number 1 as the value of the function. (A triangle with one row has
7829one pebble in it.)
7830
7831Suppose, however, that the value of the argument is 2. In this case,
7832Emacs evaluates the else-part of the `if' expression.
7833
7834The else-part consists of an addition, the recursive call to
7835`triangle-recursively' and a decrementing action; and it looks like
7836this:
7837
7838 (+ number (triangle-recursively (1- number)))
7839
7840When Emacs evaluates this expression, the innermost expression is
7841evaluated first; then the other parts in sequence. Here are the steps
7842in detail:
7843
7844Step 1 Evaluate the innermost expression.
7845 The innermost expression is `(1- number)' so Emacs decrements the
7846 value of `number' from 2 to 1.
7847
7848Step 2 Evaluate the `triangle-recursively' function.
7849 The Lisp interpreter creates an individual instance of
7850 `triangle-recursively'. It does not matter that this function is
7851 contained within itself. Emacs passes the result Step 1 as the
7852 argument used by this instance of the `triangle-recursively'
7853 function
7854
7855 In this case, Emacs evaluates `triangle-recursively' with an
7856 argument of 1. This means that this evaluation of
7857 `triangle-recursively' returns 1.
7858
7859Step 3 Evaluate the value of `number'.
7860 The variable `number' is the second element of the list that
7861 starts with `+'; its value is 2.
7862
7863Step 4 Evaluate the `+' expression.
7864 The `+' expression receives two arguments, the first from the
7865 evaluation of `number' (Step 3) and the second from the
7866 evaluation of `triangle-recursively' (Step 2).
7867
7868 The result of the addition is the sum of 2 plus 1, and the
7869 number 3 is returned, which is correct. A triangle with two
7870 rows has three pebbles in it.
7871
7872An argument of 3 or 4
7873.....................
7874
7875Suppose that `triangle-recursively' is called with an argument of 3.
7876
7877Step 1 Evaluate the do-again-test.
7878 The `if' expression is evaluated first. This is the do-again
7879 test and returns false, so the else-part of the `if' expression
7880 is evaluated. (Note that in this example, the do-again-test
7881 causes the function to call itself when it tests false, not when
7882 it tests true.)
7883
7884Step 2 Evaluate the innermost expression of the else-part.
7885 The innermost expression of the else-part is evaluated, which
7886 decrements 3 to 2. This is the next-step-expression.
7887
7888Step 3 Evaluate the `triangle-recursively' function.
7889 The number 2 is passed to the `triangle-recursively' function.
7890
7891 We know what happens when Emacs evaluates `triangle-recursively'
7892 with an argument of 2. After going through the sequence of
7893 actions described earlier, it returns a value of 3. So that is
7894 what will happen here.
7895
7896Step 4 Evaluate the addition.
7897 3 will be passed as an argument to the addition and will be
7898 added to the number with which the function was called, which is
7899 3.
7900
7901The value returned by the function as a whole will be 6.
7902
7903Now that we know what will happen when `triangle-recursively' is
7904called with an argument of 3, it is evident what will happen if it is
7905called with an argument of 4:
7906
7907 In the recursive call, the evaluation of
7908
7909 (triangle-recursively (1- 4))
7910
7911 will return the value of evaluating
7912
7913 (triangle-recursively 3)
7914
7915 which is 6 and this value will be added to 4 by the addition in
7916 the third line.
7917
7918The value returned by the function as a whole will be 10.
7919
7920Each time `triangle-recursively' is evaluated, it evaluates a version
7921of itself--a different instance of itself--with a smaller argument,
7922until the argument is small enough so that it does not evaluate
7923itself.
7924
7925Note that this particular design for a recursive function requires
7926that operations be deferred.
7927
7928Before `(triangle-recursively 7)' can calculate its answer, it must
7929call `(triangle-recursively 6)'; and before `(triangle-recursively
79306)' can calculate its answer, it must call `(triangle-recursively
79315)'; and so on. That is to say, the calculation that
7932`(triangle-recursively 7)' makes must be deferred until
7933`(triangle-recursively 6)' makes its calculation; and
7934`(triangle-recursively 6)' must defer until `(triangle-recursively
79355)' completes; and so on.
7936
7937If each of these instances of `triangle-recursively' are thought of
7938as different robots, the first robot must wait for the second to
7939complete its job, which must wait until the third completes, and so
7940on.
7941
7942There is a way around this kind of waiting, which we will discuss in
7943*Note Recursion without Deferments: No Deferment.
7944
7945Recursion Example Using `cond'
7946------------------------------
7947
7948The version of `triangle-recursively' described earlier is written
7949with the `if' special form. It can also be written using another
7950special form called `cond'. The name of the special form `cond' is
7951an abbreviation of the word `conditional'.
7952
7953Although the `cond' special form is not used as often in the Emacs
7954Lisp sources as `if', it is used often enough to justify explaining
7955it.
7956
7957The template for a `cond' expression looks like this:
7958
7959 (cond
7960 BODY...)
7961
7962where the BODY is a series of lists.
7963
7964Written out more fully, the template looks like this:
7965
7966 (cond
7967 (FIRST-TRUE-OR-FALSE-TEST FIRST-CONSEQUENT)
7968 (SECOND-TRUE-OR-FALSE-TEST SECOND-CONSEQUENT)
7969 (THIRD-TRUE-OR-FALSE-TEST THIRD-CONSEQUENT)
7970 ...)
7971
7972When the Lisp interpreter evaluates the `cond' expression, it
7973evaluates the first element (the CAR or true-or-false-test) of the
7974first expression in a series of expressions within the body of the
7975`cond'.
7976
7977If the true-or-false-test returns `nil' the rest of that expression,
7978the consequent, is skipped and the true-or-false-test of the next
7979expression is evaluated. When an expression is found whose
7980true-or-false-test returns a value that is not `nil', the consequent
7981of that expression is evaluated. The consequent can be one or more
7982expressions. If the consequent consists of more than one expression,
7983the expressions are evaluated in sequence and the value of the last
7984one is returned. If the expression does not have a consequent, the
7985value of the true-or-false-test is returned.
7986
7987If none of the true-or-false-tests test true, the `cond' expression
7988returns `nil'.
7989
7990Written using `cond', the `triangle' function looks like this:
7991
7992 (defun triangle-using-cond (number)
7993 (cond ((<= number 0) 0)
7994 ((= number 1) 1)
7995 ((> number 1)
7996 (+ number (triangle-using-cond (1- number))))))
7997
7998In this example, the `cond' returns 0 if the number is less than or
7999equal to 0, it returns 1 if the number is 1 and it evaluates `(+
8000number (triangle-using-cond (1- number)))' if the number is greater
8001than 1.
8002
8003Recursive Patterns
8004------------------
8005
8006Here are three common recursive patterns. Each involves a list.
8007Recursion does not need to involve lists, but Lisp is designed for
8008lists and this provides a sense of its primal capabilities.
8009
8010Recursive Pattern: _every_
8011..........................
8012
8013In the `every' recursive pattern, an action is performed on every
8014element of a list.
8015
8016The basic pattern is:
8017
8018 * If a list be empty, return `nil'.
8019
8020 * Else, act on the beginning of the list (the CAR of the list)
8021 - through a recursive call by the function on the rest
8022 (the CDR) of the list,
8023
8024 - and, optionally, combine the acted-on element, using
8025 `cons', with the results of acting on the rest.
8026
8027Here is example:
8028
8029 (defun square-each (numbers-list)
8030 "Square each of a NUMBERS LIST, recursively."
8031 (if (not numbers-list) ; do-again-test
8032 nil
8033 (cons
8034 (* (car numbers-list) (car numbers-list))
8035 (square-each (cdr numbers-list))))) ; next-step-expression
8036
8037 (square-each '(1 2 3))
8038 => (1 4 9)
8039
8040If `numbers-list' is empty, do nothing. But if it has content,
8041construct a list combining the square of the first number in the list
8042with the result of the recursive call.
8043
8044(The example follows the pattern exactly: `nil' is returned if the
8045numbers' list is empty. In practice, you would write the conditional
8046so it carries out the action when the numbers' list is not empty.)
8047
8048The `print-elements-recursively' function (*note Recursion with a
8049List: Recursion with list.) is another example of an `every' pattern,
8050except in this case, rather than bring the results together using
8051`cons', we print each element of output.
8052
8053The `print-elements-recursively' function looks like this:
8054
8055 (setq animals '(gazelle giraffe lion tiger))
8056
8057 (defun print-elements-recursively (list)
8058 "Print each element of LIST on a line of its own.
8059 Uses recursion."
8060 (if list ; do-again-test
8061 (progn
8062 (print (car list)) ; body
8063 (print-elements-recursively ; recursive call
8064 (cdr list))))) ; next-step-expression
8065
8066 (print-elements-recursively animals)
8067
8068The pattern for `print-elements-recursively' is:
8069
8070 * If the list be empty, do nothing.
8071
8072 * But if the list has at least one element,
8073 - act on the beginning of the list (the CAR of the list),
8074
8075 - and make a recursive call on the rest (the CDR) of the
8076 list.
8077
8078Recursive Pattern: _accumulate_
8079...............................
8080
8081Another recursive pattern is called the `accumulate' pattern. In the
8082`accumulate' recursive pattern, an action is performed on every
8083element of a list and the result of that action is accumulated with
8084the results of performing the action on the other elements.
8085
8086This is very like the `every' pattern using `cons', except that
8087`cons' is not used, but some other combiner.
8088
8089The pattern is:
8090
8091 * If a list be empty, return zero or some other constant.
8092
8093 * Else, act on the beginning of the list (the CAR of the list),
8094 - and combine that acted-on element, using `+' or
8095 some other combining function, with
8096
8097 - a recursive call by the function on the rest (the CDR)
8098 of the list.
8099
8100Here is an example:
8101
8102 (defun add-elements (numbers-list)
8103 "Add the elements of NUMBERS-LIST together."
8104 (if (not numbers-list)
8105 0
8106 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
8107
8108 (add-elements '(1 2 3 4))
8109 => 10
8110
8111*Note Making a List of Files: Files List, for an example of the
8112accumulate pattern.
8113
8114Recursive Pattern: _keep_
8115.........................
8116
8117A third recursive pattern is called the `keep' pattern. In the
8118`keep' recursive pattern, each element of a list is tested; the
8119element is acted on and the results are kept only if the element
8120meets a criterion.
8121
8122Again, this is very like the `every' pattern, except the element is
8123skipped unless it meets a criterion.
8124
8125The pattern has three parts:
8126
8127 * If a list be empty, return `nil'.
8128
8129 * Else, if the beginning of the list (the CAR of the list) passes
8130 a test
8131 - act on that element and combine it, using `cons' with
8132
8133 - a recursive call by the function on the rest (the CDR)
8134 of the list.
8135
8136 * Otherwise, if the beginning of the list (the CAR of the list)
8137 fails the test
8138 - skip on that element,
8139
8140 - and, recursively call the function on the rest (the
8141 CDR) of the list.
8142
8143Here is an example that uses `cond':
8144
8145 (defun keep-three-letter-words (word-list)
8146 "Keep three letter words in WORD-LIST."
8147 (cond
8148 ;; First do-again-test: stop-condition
8149 ((not word-list) nil)
8150
8151 ;; Second do-again-test: when to act
8152 ((eq 3 (length (symbol-name (car word-list))))
8153 ;; combine acted-on element with recursive call on shorter list
8154 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
8155
8156 ;; Third do-again-test: when to skip element;
8157 ;; recursively call shorter list with next-step expression
8158 (t (keep-three-letter-words (cdr word-list)))))
8159
8160 (keep-three-letter-words '(one two three four five six))
8161 => (one two six)
8162
8163It goes without saying that you need not use `nil' as the test for
8164when to stop; and you can, of course, combine these patterns.
8165
8166Recursion without Deferments
8167----------------------------
8168
8169Let's consider again what happens with the `triangle-recursively'
8170function. We will find that the intermediate calculations are
8171deferred until all can be done.
8172
8173Here is the function definition:
8174
8175 (defun triangle-recursively (number)
8176 "Return the sum of the numbers 1 through NUMBER inclusive.
8177 Uses recursion."
8178 (if (= number 1) ; do-again-test
8179 1 ; then-part
8180 (+ number ; else-part
8181 (triangle-recursively ; recursive call
8182 (1- number))))) ; next-step-expression
8183
8184What happens when we call this function with a argument of 7?
8185
8186The first instance of the `triangle-recursively' function adds the
8187number 7 to the value returned by a second instance of
8188`triangle-recursively', an instance that has been passed an argument
8189of 6. That is to say, the first calculation is:
8190
8191 (+ 7 (triangle-recursively 6))
8192
8193The first instance of `triangle-recursively'--you may want to think
8194of it as a little robot--cannot complete its job. It must hand off
8195the calculation for `(triangle-recursively 6)' to a second instance
8196of the program, to a second robot. This second individual is
8197completely different from the first one; it is, in the jargon, a
8198`different instantiation'. Or, put another way, it is a different
8199robot. It is the same model as the first; it calculates triangle
8200numbers recursively; but it has a different serial number.
8201
8202And what does `(triangle-recursively 6)' return? It returns the
8203number 6 added to the value returned by evaluating
8204`triangle-recursively' with an argument of 5. Using the robot
8205metaphor, it asks yet another robot to help it.
8206
8207Now the total is:
8208
8209 (+ 7 6 (triangle-recursively 5))
8210
8211And what happens next?
8212
8213 (+ 7 6 5 (triangle-recursively 4))
8214
8215Each time `triangle-recursively' is called, except for the last time,
8216it creates another instance of the program--another robot--and asks
8217it to make a calculation.
8218
8219Eventually, the full addition is set up and performed:
8220
8221 (+ 7 6 5 4 3 2 1)
8222
8223This design for the function defers the calculation of the first step
8224until the second can be done, and defers that until the third can be
8225done, and so on. Each deferment means the computer must remember what
8226is being waited on. This is not a problem when there are only a few
8227steps, as in this example. But it can be a problem when there are
8228more steps.
8229
8230No Deferment Solution
8231---------------------
8232
8233The solution to the problem of deferred operations is to write in a
8234manner that does not defer operations(1). This requires writing to a
8235different pattern, often one that involves writing two function
8236definitions, an `initialization' function and a `helper' function.
8237
8238The `initialization' function sets up the job; the `helper' function
8239does the work.
8240
8241Here are the two function definitions for adding up numbers. They are
8242so simple, I find them hard to understand.
8243
8244 (defun triangle-initialization (number)
8245 "Return the sum of the numbers 1 through NUMBER inclusive.
8246 This is the `initialization' component of a two function
8247 duo that uses recursion."
8248 (triangle-recursive-helper 0 0 number))
8249
8250 (defun triangle-recursive-helper (sum counter number)
8251 "Return SUM, using COUNTER, through NUMBER inclusive.
8252 This is the `helper' component of a two function duo
8253 that uses recursion."
8254 (if (> counter number)
8255 sum
8256 (triangle-recursive-helper (+ sum counter) ; sum
8257 (1+ counter) ; counter
8258 number))) ; number
8259
8260Install both function definitions by evaluating them, then call
8261`triangle-initialization' with 2 rows:
8262
8263 (triangle-initialization 2)
8264 => 3
8265
8266The `initialization' function calls the first instance of the `helper'
8267function with three arguments: zero, zero, and a number which is the
8268number of rows in the triangle.
8269
8270The first two arguments passed to the `helper' function are
8271initialization values. These values are changed when
8272`triangle-recursive-helper' invokes new instances.(2)
8273
8274Let's see what happens when we have a triangle that has one row.
8275(This triangle will have one pebble in it!)
8276
8277`triangle-initialization' will call its helper with the arguments
8278`0 0 1'. That function will run the conditional test whether `(>
8279counter number)':
8280
8281 (> 0 1)
8282
8283and find that the result is false, so it will invoke the then-part of
8284the `if' clause:
8285
8286 (triangle-recursive-helper
8287 (+ sum counter) ; sum plus counter => sum
8288 (1+ counter) ; increment counter => counter
8289 number) ; number stays the same
8290
8291which will first compute:
8292
8293 (triangle-recursive-helper (+ 0 0) ; sum
8294 (1+ 0) ; counter
8295 1) ; number
8296which is:
8297
8298 (triangle-recursive-helper 0 1 1)
8299
8300Again, `(> counter number)' will be false, so again, the Lisp
8301interpreter will evaluate `triangle-recursive-helper', creating a new
8302instance with new arguments.
8303
8304This new instance will be;
8305
8306 (triangle-recursive-helper
8307 (+ sum counter) ; sum plus counter => sum
8308 (1+ counter) ; increment counter => counter
8309 number) ; number stays the same
8310
8311which is:
8312
8313 (triangle-recursive-helper 1 2 1)
8314
8315In this case, the `(> counter number)' test will be true! So the
8316instance will return the value of the sum, which will be 1, as
8317expected.
8318
8319Now, let's pass `triangle-initialization' an argument of 2, to find
8320out how many pebbles there are in a triangle with two rows.
8321
8322That function calls `(triangle-recursive-helper 0 0 2)'.
8323
8324In stages, the instances called will be:
8325
8326 sum counter number
8327 (triangle-recursive-helper 0 1 2)
8328
8329 (triangle-recursive-helper 1 2 2)
8330
8331 (triangle-recursive-helper 3 3 2)
8332
8333When the last instance is called, the `(> counter number)' test will
8334be true, so the instance will return the value of `sum', which will
8335be 3.
8336
8337This kind of pattern helps when you are writing functions that can use
8338many resources in a computer.
8339
8340---------- Footnotes ----------
8341
8342(1) The phrase "tail recursive" is used to describe such a process,
8343one that uses `constant space'.
8344
8345(2) The jargon is mildly confusing: `triangle-recursive-helper' uses
8346a process that is iterative in a procedure that is recursive. The
8347process is called iterative because the computer need only record the
8348three values, `sum', `counter', and `number'; the procedure is
8349recursive because the function `calls itself'. On the other hand,
8350both the process and the procedure used by `triangle-recursively' are
8351called recursive. The word `recursive' has different meanings in the
8352two contexts.
8353
8354Looping Exercise
8355================
8356
8357 * Write a function similar to `triangle' in which each row has a
8358 value which is the square of the row number. Use a `while' loop.
8359
8360 * Write a function similar to `triangle' that multiplies instead of
8361 adds the values.
8362
8363 * Rewrite these two functions recursively. Rewrite these functions
8364 using `cond'.
8365
8366 * Write a function for Texinfo mode that creates an index entry at
8367 the beginning of a paragraph for every `@dfn' within the
8368 paragraph. (In a Texinfo file, `@dfn' marks a definition. For
8369 more information, see *Note Indicating Definitions:
8370 (texinfo)Indicating.)
8371
8372Regular Expression Searches
8373***************************
8374
8375Regular expression searches are used extensively in GNU Emacs. The
8376two functions, `forward-sentence' and `forward-paragraph', illustrate
8377these searches well. They use regular expressions to find where to
8378move point. The phrase `regular expression' is often written as
8379`regexp'.
8380
8381Regular expression searches are described in *Note Regular Expression
8382Search: (emacs)Regexp Search, as well as in *Note Regular
8383Expressions: (elisp)Regular Expressions. In writing this chapter, I
8384am presuming that you have at least a mild acquaintance with them.
8385The major point to remember is that regular expressions permit you to
8386search for patterns as well as for literal strings of characters.
8387For example, the code in `forward-sentence' searches for the pattern
8388of possible characters that could mark the end of a sentence, and
8389moves point to that spot.
8390
8391Before looking at the code for the `forward-sentence' function, it is
8392worth considering what the pattern that marks the end of a sentence
8393must be. The pattern is discussed in the next section; following that
8394is a description of the regular expression search function,
8395`re-search-forward'. The `forward-sentence' function is described in
8396the section following. Finally, the `forward-paragraph' function is
8397described in the last section of this chapter. `forward-paragraph'
8398is a complex function that introduces several new features.
8399
8400The Regular Expression for `sentence-end'
8401=========================================
8402
8403The symbol `sentence-end' is bound to the pattern that marks the end
8404of a sentence. What should this regular expression be?
8405
8406Clearly, a sentence may be ended by a period, a question mark, or an
8407exclamation mark. Indeed, only clauses that end with one of those
8408three characters should be considered the end of a sentence. This
8409means that the pattern should include the character set:
8410
8411 [.?!]
8412
8413However, we do not want `forward-sentence' merely to jump to a
8414period, a question mark, or an exclamation mark, because such a
8415character might be used in the middle of a sentence. A period, for
8416example, is used after abbreviations. So other information is needed.
8417
8418According to convention, you type two spaces after every sentence, but
8419only one space after a period, a question mark, or an exclamation
8420mark in the body of a sentence. So a period, a question mark, or an
8421exclamation mark followed by two spaces is a good indicator of an end
8422of sentence. However, in a file, the two spaces may instead be a tab
8423or the end of a line. This means that the regular expression should
8424include these three items as alternatives.
8425
8426This group of alternatives will look like this:
8427
8428 \\($\\| \\| \\)
8429 ^ ^^
8430 TAB SPC
8431
8432Here, `$' indicates the end of the line, and I have pointed out where
8433the tab and two spaces are inserted in the expression. Both are
8434inserted by putting the actual characters into the expression.
8435
8436Two backslashes, `\\', are required before the parentheses and
8437vertical bars: the first backslash quotes the following backslash in
8438Emacs; and the second indicates that the following character, the
8439parenthesis or the vertical bar, is special.
8440
8441Also, a sentence may be followed by one or more carriage returns, like
8442this:
8443
8444 [
8445 ]*
8446
8447Like tabs and spaces, a carriage return is inserted into a regular
8448expression by inserting it literally. The asterisk indicates that the
8449<RET> is repeated zero or more times.
8450
8451But a sentence end does not consist only of a period, a question mark
8452or an exclamation mark followed by appropriate space: a closing
8453quotation mark or a closing brace of some kind may precede the space.
8454Indeed more than one such mark or brace may precede the space.
8455These require a expression that looks like this:
8456
8457 []\"')}]*
8458
8459In this expression, the first `]' is the first character in the
8460expression; the second character is `"', which is preceded by a `\'
8461to tell Emacs the `"' is _not_ special. The last three characters
8462are `'', `)', and `}'.
8463
8464All this suggests what the regular expression pattern for matching the
8465end of a sentence should be; and, indeed, if we evaluate
8466`sentence-end' we find that it returns the following value:
8467
8468 sentence-end
8469 => "[.?!][]\"')}]*\\($\\| \\| \\)[
8470 ]*"
8471
8472The `re-search-forward' Function
8473================================
8474
8475The `re-search-forward' function is very like the `search-forward'
8476function. (*Note The `search-forward' Function: search-forward.)
8477
8478`re-search-forward' searches for a regular expression. If the search
8479is successful, it leaves point immediately after the last character
8480in the target. If the search is backwards, it leaves point just
8481before the first character in the target. You may tell
8482`re-search-forward' to return `t' for true. (Moving point is
8483therefore a `side effect'.)
8484
8485Like `search-forward', the `re-search-forward' function takes four
8486arguments:
8487
8488 1. The first argument is the regular expression that the function
8489 searches for. The regular expression will be a string between
8490 quotations marks.
8491
8492 2. The optional second argument limits how far the function will
8493 search; it is a bound, which is specified as a position in the
8494 buffer.
8495
8496 3. The optional third argument specifies how the function responds
8497 to failure: `nil' as the third argument causes the function to
8498 signal an error (and print a message) when the search fails; any
8499 other value causes it to return `nil' if the search fails and `t'
8500 if the search succeeds.
8501
8502 4. The optional fourth argument is the repeat count. A negative
8503 repeat count causes `re-search-forward' to search backwards.
8504
8505The template for `re-search-forward' looks like this:
8506
8507 (re-search-forward "REGULAR-EXPRESSION"
8508 LIMIT-OF-SEARCH
8509 WHAT-TO-DO-IF-SEARCH-FAILS
8510 REPEAT-COUNT)
8511
8512The second, third, and fourth arguments are optional. However, if you
8513want to pass a value to either or both of the last two arguments, you
8514must also pass a value to all the preceding arguments. Otherwise, the
8515Lisp interpreter will mistake which argument you are passing the value
8516to.
8517
8518In the `forward-sentence' function, the regular expression will be
8519the value of the variable `sentence-end', namely:
8520
8521 "[.?!][]\"')}]*\\($\\| \\| \\)[
8522 ]*"
8523
8524The limit of the search will be the end of the paragraph (since a
8525sentence cannot go beyond a paragraph). If the search fails, the
8526function will return `nil'; and the repeat count will be provided by
8527the argument to the `forward-sentence' function.
8528
8529`forward-sentence'
8530==================
8531
8532The command to move the cursor forward a sentence is a straightforward
8533illustration of how to use regular expression searches in Emacs Lisp.
8534Indeed, the function looks longer and more complicated than it is;
8535this is because the function is designed to go backwards as well as
8536forwards; and, optionally, over more than one sentence. The function
8537is usually bound to the key command `M-e'.
8538
8539Complete `forward-sentence' function definition
8540-----------------------------------------------
8541
8542Here is the code for `forward-sentence':
8543
8544 (defun forward-sentence (&optional arg)
8545 "Move forward to next sentence-end. With argument, repeat.
8546 With negative argument, move backward repeatedly to sentence-beginning.
8547 Sentence ends are identified by the value of sentence-end
8548 treated as a regular expression. Also, every paragraph boundary
8549 terminates sentences as well."
8550 (interactive "p")
8551 (or arg (setq arg 1))
8552 (while (< arg 0)
8553 (let ((par-beg
8554 (save-excursion (start-of-paragraph-text) (point))))
8555 (if (re-search-backward
8556 (concat sentence-end "[^ \t\n]") par-beg t)
8557 (goto-char (1- (match-end 0)))
8558 (goto-char par-beg)))
8559 (setq arg (1+ arg)))
8560 (while (> arg 0)
8561 (let ((par-end
8562 (save-excursion (end-of-paragraph-text) (point))))
8563 (if (re-search-forward sentence-end par-end t)
8564 (skip-chars-backward " \t\n")
8565 (goto-char par-end)))
8566 (setq arg (1- arg))))
8567
8568The function looks long at first sight and it is best to look at its
8569skeleton first, and then its muscle. The way to see the skeleton is
8570to look at the expressions that start in the left-most columns:
8571
8572 (defun forward-sentence (&optional arg)
8573 "DOCUMENTATION..."
8574 (interactive "p")
8575 (or arg (setq arg 1))
8576 (while (< arg 0)
8577 BODY-OF-WHILE-LOOP
8578 (while (> arg 0)
8579 BODY-OF-WHILE-LOOP
8580
8581This looks much simpler! The function definition consists of
8582documentation, an `interactive' expression, an `or' expression, and
8583`while' loops.
8584
8585Let's look at each of these parts in turn.
8586
8587We note that the documentation is thorough and understandable.
8588
8589The function has an `interactive "p"' declaration. This means that
8590the processed prefix argument, if any, is passed to the function as
8591its argument. (This will be a number.) If the function is not
8592passed an argument (it is optional) then the argument `arg' will be
8593bound to 1. When `forward-sentence' is called non-interactively
8594without an argument, `arg' is bound to `nil'.
8595
8596The `or' expression handles the prefix argument. What it does is
8597either leave the value of `arg' as it is, but only if `arg' is bound
8598to a value; or it sets the value of `arg' to 1, in the case when
8599`arg' is bound to `nil'.
8600
8601The `while' loops
8602-----------------
8603
8604Two `while' loops follow the `or' expression. The first `while' has
8605a true-or-false-test that tests true if the prefix argument for
8606`forward-sentence' is a negative number. This is for going
8607backwards. The body of this loop is similar to the body of the
8608second `while' clause, but it is not exactly the same. We will skip
8609this `while' loop and concentrate on the second `while' loop.
8610
8611The second `while' loop is for moving point forward. Its skeleton
8612looks like this:
8613
8614 (while (> arg 0) ; true-or-false-test
8615 (let VARLIST
8616 (if (TRUE-OR-FALSE-TEST)
8617 THEN-PART
8618 ELSE-PART
8619 (setq arg (1- arg)))) ; `while' loop decrementer
8620
8621The `while' loop is of the decrementing kind. (*Note A Loop with a
8622Decrementing Counter: Decrementing Loop.) It has a
8623true-or-false-test that tests true so long as the counter (in this
8624case, the variable `arg') is greater than zero; and it has a
8625decrementer that subtracts 1 from the value of the counter every time
8626the loop repeats.
8627
8628If no prefix argument is given to `forward-sentence', which is the
8629most common way the command is used, this `while' loop will run once,
8630since the value of `arg' will be 1.
8631
8632The body of the `while' loop consists of a `let' expression, which
8633creates and binds a local variable, and has, as its body, an `if'
8634expression.
8635
8636The body of the `while' loop looks like this:
8637
8638 (let ((par-end
8639 (save-excursion (end-of-paragraph-text) (point))))
8640 (if (re-search-forward sentence-end par-end t)
8641 (skip-chars-backward " \t\n")
8642 (goto-char par-end)))
8643
8644The `let' expression creates and binds the local variable `par-end'.
8645As we shall see, this local variable is designed to provide a bound
8646or limit to the regular expression search. If the search fails to
8647find a proper sentence ending in the paragraph, it will stop on
8648reaching the end of the paragraph.
8649
8650But first, let us examine how `par-end' is bound to the value of the
8651end of the paragraph. What happens is that the `let' sets the value
8652of `par-end' to the value returned when the Lisp interpreter
8653evaluates the expression
8654
8655 (save-excursion (end-of-paragraph-text) (point))
8656
8657In this expression, `(end-of-paragraph-text)' moves point to the end
8658of the paragraph, `(point)' returns the value of point, and then
8659`save-excursion' restores point to its original position. Thus, the
8660`let' binds `par-end' to the value returned by the `save-excursion'
8661expression, which is the position of the end of the paragraph. (The
8662`(end-of-paragraph-text)' function uses `forward-paragraph', which we
8663will discuss shortly.)
8664
8665Emacs next evaluates the body of the `let', which is an `if'
8666expression that looks like this:
8667
8668 (if (re-search-forward sentence-end par-end t) ; if-part
8669 (skip-chars-backward " \t\n") ; then-part
8670 (goto-char par-end))) ; else-part
8671
8672The `if' tests whether its first argument is true and if so,
8673evaluates its then-part; otherwise, the Emacs Lisp interpreter
8674evaluates the else-part. The true-or-false-test of the `if'
8675expression is the regular expression search.
8676
8677It may seem odd to have what looks like the `real work' of the
8678`forward-sentence' function buried here, but this is a common way
8679this kind of operation is carried out in Lisp.
8680
8681The regular expression search
8682-----------------------------
8683
8684The `re-search-forward' function searches for the end of the
8685sentence, that is, for the pattern defined by the `sentence-end'
8686regular expression. If the pattern is found--if the end of the
8687sentence is found--then the `re-search-forward' function does two
8688things:
8689
8690 1. The `re-search-forward' function carries out a side effect, which
8691 is to move point to the end of the occurrence found.
8692
8693 2. The `re-search-forward' function returns a value of true. This
8694 is the value received by the `if', and means that the search was
8695 successful.
8696
8697The side effect, the movement of point, is completed before the `if'
8698function is handed the value returned by the successful conclusion of
8699the search.
8700
8701When the `if' function receives the value of true from a successful
8702call to `re-search-forward', the `if' evaluates the then-part, which
8703is the expression `(skip-chars-backward " \t\n")'. This expression
8704moves backwards over any blank spaces, tabs or carriage returns until
8705a printed character is found and then leaves point after the
8706character. Since point has already been moved to the end of the
8707pattern that marks the end of the sentence, this action leaves point
8708right after the closing printed character of the sentence, which is
8709usually a period.
8710
8711On the other hand, if the `re-search-forward' function fails to find
8712a pattern marking the end of the sentence, the function returns
8713false. The false then causes the `if' to evaluate its third
8714argument, which is `(goto-char par-end)': it moves point to the end
8715of the paragraph.
8716
8717Regular expression searches are exceptionally useful and the pattern
8718illustrated by `re-search-forward', in which the search is the test
8719of an `if' expression, is handy. You will see or write code
8720incorporating this pattern often.
8721
8722`forward-paragraph': a Goldmine of Functions
8723============================================
8724
8725The `forward-paragraph' function moves point forward to the end of
8726the paragraph. It is usually bound to `M-}' and makes use of a
8727number of functions that are important in themselves, including
8728`let*', `match-beginning', and `looking-at'.
8729
8730The function definition for `forward-paragraph' is considerably
8731longer than the function definition for `forward-sentence' because it
8732works with a paragraph, each line of which may begin with a fill
8733prefix.
8734
8735A fill prefix consists of a string of characters that are repeated at
8736the beginning of each line. For example, in Lisp code, it is a
8737convention to start each line of a paragraph-long comment with `;;;
8738'. In Text mode, four blank spaces make up another common fill
8739prefix, creating an indented paragraph. (*Note Fill Prefix:
8740(emacs)Fill Prefix, for more information about fill prefixes.)
8741
8742The existence of a fill prefix means that in addition to being able to
8743find the end of a paragraph whose lines begin on the left-most
8744column, the `forward-paragraph' function must be able to find the end
8745of a paragraph when all or many of the lines in the buffer begin with
8746the fill prefix.
8747
8748Moreover, it is sometimes practical to ignore a fill prefix that
8749exists, especially when blank lines separate paragraphs. This is an
8750added complication.
8751
8752Shortened `forward-paragraph' function definition
8753-------------------------------------------------
8754
8755Rather than print all of the `forward-paragraph' function, we will
8756only print parts of it. Read without preparation, the function can
8757be daunting!
8758
8759In outline, the function looks like this:
8760
8761 (defun forward-paragraph (&optional arg)
8762 "DOCUMENTATION..."
8763 (interactive "p")
8764 (or arg (setq arg 1))
8765 (let*
8766 VARLIST
8767 (while (< arg 0) ; backward-moving-code
8768 ...
8769 (setq arg (1+ arg)))
8770 (while (> arg 0) ; forward-moving-code
8771 ...
8772 (setq arg (1- arg)))))
8773
8774The first parts of the function are routine: the function's argument
8775list consists of one optional argument. Documentation follows.
8776
8777The lower case `p' in the `interactive' declaration means that the
8778processed prefix argument, if any, is passed to the function. This
8779will be a number, and is the repeat count of how many paragraphs
8780point will move. The `or' expression in the next line handles the
8781common case when no argument is passed to the function, which occurs
8782if the function is called from other code rather than interactively.
8783This case was described earlier. (*Note The `forward-sentence'
8784function: forward-sentence.) Now we reach the end of the familiar
8785part of this function.
8786
8787The `let*' expression
8788---------------------
8789
8790The next line of the `forward-paragraph' function begins a `let*'
8791expression. This is a different kind of expression than we have seen
8792so far. The symbol is `let*' not `let'.
8793
8794The `let*' special form is like `let' except that Emacs sets each
8795variable in sequence, one after another, and variables in the latter
8796part of the varlist can make use of the values to which Emacs set
8797variables in the earlier part of the varlist.
8798
8799In the `let*' expression in this function, Emacs binds two variables:
8800`fill-prefix-regexp' and `paragraph-separate'. The value to which
8801`paragraph-separate' is bound depends on the value of
8802`fill-prefix-regexp'.
8803
8804Let's look at each in turn. The symbol `fill-prefix-regexp' is set
8805to the value returned by evaluating the following list:
8806
8807 (and fill-prefix
8808 (not (equal fill-prefix ""))
8809 (not paragraph-ignore-fill-prefix)
8810 (regexp-quote fill-prefix))
8811
8812This is an expression whose first element is the `and' special form.
8813
8814As we learned earlier (*note The `kill-new' function: kill-new
8815function.), the `and' special form evaluates each of its arguments
8816until one of the arguments returns a value of `nil', in which case
8817the `and' expression returns `nil'; however, if none of the arguments
8818returns a value of `nil', the value resulting from evaluating the
8819last argument is returned. (Since such a value is not `nil', it is
8820considered true in Lisp.) In other words, an `and' expression
8821returns a true value only if all its arguments are true.
8822
8823In this case, the variable `fill-prefix-regexp' is bound to a
8824non-`nil' value only if the following four expressions produce a true
8825(i.e., a non-`nil') value when they are evaluated; otherwise,
8826`fill-prefix-regexp' is bound to `nil'.
8827
8828`fill-prefix'
8829 When this variable is evaluated, the value of the fill prefix,
8830 if any, is returned. If there is no fill prefix, this variable
8831 returns `nil'.
8832
8833`(not (equal fill-prefix "")'
8834 This expression checks whether an existing fill prefix is an
8835 empty string, that is, a string with no characters in it. An
8836 empty string is not a useful fill prefix.
8837
8838`(not paragraph-ignore-fill-prefix)'
8839 This expression returns `nil' if the variable
8840 `paragraph-ignore-fill-prefix' has been turned on by being set
8841 to a true value such as `t'.
8842
8843`(regexp-quote fill-prefix)'
8844 This is the last argument to the `and' special form. If all the
8845 arguments to the `and' are true, the value resulting from
8846 evaluating this expression will be returned by the `and'
8847 expression and bound to the variable `fill-prefix-regexp',
8848
8849The result of evaluating this `and' expression successfully is that
8850`fill-prefix-regexp' will be bound to the value of `fill-prefix' as
8851modified by the `regexp-quote' function. What `regexp-quote' does is
8852read a string and return a regular expression that will exactly match
8853the string and match nothing else. This means that
8854`fill-prefix-regexp' will be set to a value that will exactly match
8855the fill prefix if the fill prefix exists. Otherwise, the variable
8856will be set to `nil'.
8857
8858The second local variable in the `let*' expression is
8859`paragraph-separate'. It is bound to the value returned by
8860evaluating the expression:
8861
8862 (if fill-prefix-regexp
8863 (concat paragraph-separate
8864 "\\|^" fill-prefix-regexp "[ \t]*$")
8865 paragraph-separate)))
8866
8867This expression shows why `let*' rather than `let' was used. The
8868true-or-false-test for the `if' depends on whether the variable
8869`fill-prefix-regexp' evaluates to `nil' or some other value.
8870
8871If `fill-prefix-regexp' does not have a value, Emacs evaluates the
8872else-part of the `if' expression and binds `paragraph-separate' to
8873its local value. (`paragraph-separate' is a regular expression that
8874matches what separates paragraphs.)
8875
8876But if `fill-prefix-regexp' does have a value, Emacs evaluates the
8877then-part of the `if' expression and binds `paragraph-separate' to a
8878regular expression that includes the `fill-prefix-regexp' as part of
8879the pattern.
8880
8881Specifically, `paragraph-separate' is set to the original value of
8882the paragraph separate regular expression concatenated with an
8883alternative expression that consists of the `fill-prefix-regexp'
8884followed by a blank line. The `^' indicates that the
8885`fill-prefix-regexp' must begin a line, and the optional whitespace
8886to the end of the line is defined by `"[ \t]*$"'.) The `\\|' defines
8887this portion of the regexp as an alternative to `paragraph-separate'.
8888
8889Now we get into the body of the `let*'. The first part of the body
8890of the `let*' deals with the case when the function is given a
8891negative argument and is therefore moving backwards. We will skip
8892this section.
8893
8894The forward motion `while' loop
8895-------------------------------
8896
8897The second part of the body of the `let*' deals with forward motion.
8898It is a `while' loop that repeats itself so long as the value of
8899`arg' is greater than zero. In the most common use of the function,
8900the value of the argument is 1, so the body of the `while' loop is
8901evaluated exactly once, and the cursor moves forward one paragraph.
8902
8903This part handles three situations: when point is between paragraphs,
8904when point is within a paragraph and there is a fill prefix, and when
8905point is within a paragraph and there is no fill prefix.
8906
8907The `while' loop looks like this:
8908
8909 (while (> arg 0)
8910 (beginning-of-line)
8911
8912 ;; between paragraphs
8913 (while (prog1 (and (not (eobp))
8914 (looking-at paragraph-separate))
8915 (forward-line 1)))
8916
8917 ;; within paragraphs, with a fill prefix
8918 (if fill-prefix-regexp
8919 ;; There is a fill prefix; it overrides paragraph-start.
8920 (while (and (not (eobp))
8921 (not (looking-at paragraph-separate))
8922 (looking-at fill-prefix-regexp))
8923 (forward-line 1))
8924
8925 ;; within paragraphs, no fill prefix
8926 (if (re-search-forward paragraph-start nil t)
8927 (goto-char (match-beginning 0))
8928 (goto-char (point-max))))
8929
8930 (setq arg (1- arg)))
8931
8932We can see immediately that this is a decrementing counter `while'
8933loop, using the expression `(setq arg (1- arg))' as the decrementer.
8934
8935The body of the loop consists of three expressions:
8936
8937 ;; between paragraphs
8938 (beginning-of-line)
8939 (while
8940 BODY-OF-WHILE)
8941
8942 ;; within paragraphs, with fill prefix
8943 (if TRUE-OR-FALSE-TEST
8944 THEN-PART
8945
8946 ;; within paragraphs, no fill prefix
8947 ELSE-PART
8948
8949When the Emacs Lisp interpreter evaluates the body of the `while'
8950loop, the first thing it does is evaluate the `(beginning-of-line)'
8951expression and move point to the beginning of the line. Then there
8952is an inner `while' loop. This `while' loop is designed to move the
8953cursor out of the blank space between paragraphs, if it should happen
8954to be there. Finally, there is an `if' expression that actually
8955moves point to the end of the paragraph.
8956
8957Between paragraphs
8958------------------
8959
8960First, let us look at the inner `while' loop. This loop handles the
8961case when point is between paragraphs; it uses three functions that
8962are new to us: `prog1', `eobp' and `looking-at'.
8963
8964 * `prog1' is similar to the `progn' special form, except that
8965 `prog1' evaluates its arguments in sequence and then returns the
8966 value of its first argument as the value of the whole
8967 expression. (`progn' returns the value of its last argument as
8968 the value of the expression.) The second and subsequent
8969 arguments to `prog1' are evaluated only for their side effects.
8970
8971 * `eobp' is an abbreviation of `End Of Buffer P' and is a function
8972 that returns true if point is at the end of the buffer.
8973
8974 * `looking-at' is a function that returns true if the text
8975 following point matches the regular expression passed
8976 `looking-at' as its argument.
8977
8978The `while' loop we are studying looks like this:
8979
8980 (while (prog1 (and (not (eobp))
8981 (looking-at paragraph-separate))
8982 (forward-line 1)))
8983
8984This is a `while' loop with no body! The true-or-false-test of the
8985loop is the expression:
8986
8987 (prog1 (and (not (eobp))
8988 (looking-at paragraph-separate))
8989 (forward-line 1))
8990
8991The first argument to the `prog1' is the `and' expression. It has
8992within in it a test of whether point is at the end of the buffer and
8993also a test of whether the pattern following point matches the regular
8994expression for separating paragraphs.
8995
8996If the cursor is not at the end of the buffer and if the characters
8997following the cursor mark the separation between two paragraphs, then
8998the `and' expression is true. After evaluating the `and' expression,
8999the Lisp interpreter evaluates the second argument to `prog1', which
9000is `forward-line'. This moves point forward one line. The value
9001returned by the `prog1' however, is the value of its first argument,
9002so the `while' loop continues so long as point is not at the end of
9003the buffer and is between paragraphs. When, finally, point is moved
9004to a paragraph, the `and' expression tests false. Note however, that
9005the `forward-line' command is carried out anyhow. This means that
9006when point is moved from between paragraphs to a paragraph, it is left
9007at the beginning of the second line of the paragraph.
9008
9009Within paragraphs
9010-----------------
9011
9012The next expression in the outer `while' loop is an `if' expression.
9013The Lisp interpreter evaluates the then-part of the `if' when the
9014`fill-prefix-regexp' variable has a value other than `nil', and it
9015evaluates the else-part when the value of `if fill-prefix-regexp' is
9016`nil', that is, when there is no fill prefix.
9017
9018No fill prefix
9019--------------
9020
9021It is simplest to look at the code for the case when there is no fill
9022prefix first. This code consists of yet another inner `if'
9023expression, and reads as follows:
9024
9025 (if (re-search-forward paragraph-start nil t)
9026 (goto-char (match-beginning 0))
9027 (goto-char (point-max)))
9028
9029This expression actually does the work that most people think of as
9030the primary purpose of the `forward-paragraph' command: it causes a
9031regular expression search to occur that searches forward to the start
9032of the next paragraph and if it is found, moves point there; but if
9033the start of another paragraph if not found, it moves point to the
9034end of the accessible region of the buffer.
9035
9036The only unfamiliar part of this is the use of `match-beginning'.
9037This is another function that is new to us. The `match-beginning'
9038function returns a number specifying the location of the start of the
9039text that was matched by the last regular expression search.
9040
9041The `match-beginning' function is used here because of a
9042characteristic of a forward search: a successful forward search,
9043regardless of whether it is a plain search or a regular expression
9044search, will move point to the end of the text that is found. In this
9045case, a successful search will move point to the end of the pattern
9046for `paragraph-start', which will be the beginning of the next
9047paragraph rather than the end of the current one.
9048
9049However, we want to put point at the end of the current paragraph,
9050not at the beginning of the next one. The two positions may be
9051different, because there may be several blank lines between
9052paragraphs.
9053
9054When given an argument of 0, `match-beginning' returns the position
9055that is the start of the text that the most recent regular expression
9056search matched. In this case, the most recent regular expression
9057search is the one looking for `paragraph-start', so `match-beginning'
9058returns the beginning position of the pattern, rather than the end of
9059the pattern. The beginning position is the end of the paragraph.
9060
9061(Incidentally, when passed a positive number as an argument, the
9062`match-beginning' function will place point at that parenthesized
9063expression in the last regular expression. It is a useful function.)
9064
9065With a fill prefix
9066------------------
9067
9068The inner `if' expression just discussed is the else-part of an
9069enclosing `if' expression which tests whether there is a fill prefix.
9070If there is a fill prefix, the then-part of this `if' is evaluated.
9071It looks like this:
9072
9073 (while (and (not (eobp))
9074 (not (looking-at paragraph-separate))
9075 (looking-at fill-prefix-regexp))
9076 (forward-line 1))
9077
9078What this expression does is move point forward line by line so long
9079as three conditions are true:
9080
9081 1. Point is not at the end of the buffer.
9082
9083 2. The text following point does not separate paragraphs.
9084
9085 3. The pattern following point is the fill prefix regular
9086 expression.
9087
9088The last condition may be puzzling, until you remember that point was
9089moved to the beginning of the line early in the `forward-paragraph'
9090function. This means that if the text has a fill prefix, the
9091`looking-at' function will see it.
9092
9093Summary
9094-------
9095
9096In summary, when moving forward, the `forward-paragraph' function
9097does the following:
9098
9099 * Move point to the beginning of the line.
9100
9101 * Skip over lines between paragraphs.
9102
9103 * Check whether there is a fill prefix, and if there is:
9104
9105 -- Go forward line by line so long as the line is not a
9106 paragraph separating line.
9107
9108 * But if there is no fill prefix,
9109
9110 -- Search for the next paragraph start pattern.
9111
9112 -- Go to the beginning of the paragraph start pattern, which
9113 will be the end of the previous paragraph.
9114
9115 -- Or else go to the end of the accessible portion of the
9116 buffer.
9117
9118For review, here is the code we have just been discussing, formatted
9119for clarity:
9120
9121 (interactive "p")
9122 (or arg (setq arg 1))
9123 (let* (
9124 (fill-prefix-regexp
9125 (and fill-prefix (not (equal fill-prefix ""))
9126 (not paragraph-ignore-fill-prefix)
9127 (regexp-quote fill-prefix)))
9128
9129 (paragraph-separate
9130 (if fill-prefix-regexp
9131 (concat paragraph-separate
9132 "\\|^"
9133 fill-prefix-regexp
9134 "[ \t]*$")
9135 paragraph-separate)))
9136
9137 OMITTED-BACKWARD-MOVING-CODE ...
9138
9139 (while (> arg 0) ; forward-moving-code
9140 (beginning-of-line)
9141
9142 (while (prog1 (and (not (eobp))
9143 (looking-at paragraph-separate))
9144 (forward-line 1)))
9145
9146 (if fill-prefix-regexp
9147 (while (and (not (eobp)) ; then-part
9148 (not (looking-at paragraph-separate))
9149 (looking-at fill-prefix-regexp))
9150 (forward-line 1))
9151 ; else-part: the inner-if
9152 (if (re-search-forward paragraph-start nil t)
9153 (goto-char (match-beginning 0))
9154 (goto-char (point-max))))
9155
9156 (setq arg (1- arg))))) ; decrementer
9157
9158The full definition for the `forward-paragraph' function not only
9159includes this code for going forwards, but also code for going
9160backwards.
9161
9162If you are reading this inside of GNU Emacs and you want to see the
9163whole function, you can type `C-h f' (`describe-function') and the
9164name of the function. This gives you the function documentation and
9165the name of the library containing the function's source. Place
9166point over the name of the library and press the RET key; you will be
9167taken directly to the source. (Be sure to install your sources!
9168Without them, you are like a person who tries to drive a car with his
9169eyes shut!)
9170
9171Or - a good habit to get into - you can type `M-.' (`find-tag') and
9172the name of the function when prompted for it. This will take you
9173directly to the source. If the `find-tag' function first asks you
9174for the name of a `TAGS' table, give it the name of the `TAGS' file
9175such as `/usr/local/share/emacs/21.0.100/lisp/TAGS'. (The exact path
9176to your `TAGS' file depends on how your copy of Emacs was installed.)
9177
9178You can also create your own `TAGS' file for directories that lack
9179one. *Note Create Your Own `TAGS' File: etags.
9180
9181Create Your Own `TAGS' File
9182===========================
9183
9184The `M-.' (`find-tag') command takes you directly to the source for a
9185function, variable, node, or other source. The function depends on
9186tags tables to tell it where to go.
9187
9188You often need to build and install tags tables yourself. They are
9189not built automatically. A tags table is called a `TAGS' file; the
9190name is in upper case letters.
9191
9192You can create a `TAGS' file by calling the `etags' program that
9193comes as a part of the Emacs distribution. Usually, `etags' is
9194compiled and installed when Emacs is built. (`etags' is not an Emacs
9195Lisp function or a part of Emacs; it is a C program.)
9196
9197To create a `TAGS' file, first switch to the directory in which you
9198want to create the file. In Emacs you can do this with the `M-x cd'
9199command, or by visiting a file in the directory, or by listing the
9200directory with `C-x d' (`dired'). Then run the compile command, with
9201`etags *.el' as the command to execute
9202
9203 M-x compile RET etags *.el RET
9204
9205to create a `TAGS' file.
9206
9207For example, if you have a large number of files in your `~/emacs'
9208directory, as I do--I have 137 `.el' files in it, of which I load
920912--you can create a `TAGS' file for the Emacs Lisp files in that
9210directory.
9211
9212The `etags' program takes all the usual shell `wildcards'. For
9213example, if you have two directories for which you want a single
9214`TAGS file', type `etags *.el ../elisp/*.el', where `../elisp/' is
9215the second directory:
9216
9217 M-x compile RET etags *.el ../elisp/*.el RET
9218
9219Type
9220
9221 M-x compile RET etags --help RET
9222
9223to see a list of the options accepted by `etags' as well as a list of
9224supported languages.
9225
9226The `etags' program handles more than 20 languages, including Emacs
9227Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX, Pascal,
9228Perl, Python, Texinfo, makefiles, and most assemblers. The program
9229has no switches for specifying the language; it recognizes the
9230language in an input file according to its file name and contents.
9231
9232`etags' is very helpful when you are writing code yourself and want
9233to refer back to functions you have already written. Just run
9234`etags' again at intervals as you write new functions, so they become
9235part of the `TAGS' file.
9236
9237If you think an appropriate `TAGS' file already exists for what you
9238want, but do not know where it is, you can use the `locate' program
9239to attempt to find it.
9240
9241Type `M-x locate RET TAGS RET' and Emacs will list for you the full
9242path names of all your `TAGS' files. On my system, this command
9243lists 34 `TAGS' files. On the other hand, a `plain vanilla' system I
9244recently installed did not contain any `TAGS' files.
9245
9246If the tags table you want has been created, you can use the `M-x
9247visit-tags-table' command to specify it. Otherwise, you will need to
9248create the tag table yourself and then use `M-x visit-tags-table'.
9249
9250Building Tags in the Emacs sources
9251..................................
9252
9253The GNU Emacs sources come with a `Makefile' that contains a
9254sophisticated `etags' command that creates, collects, and merges tags
9255tables from all over the Emacs sources and puts the information into
9256one `TAGS' file in the `src/' directory below the top level of your
9257Emacs source directory.
9258
9259To build this `TAGS' file, go to the top level of your Emacs source
9260directory and run the compile command `make tags':
9261
9262 M-x compile RET make tags RET
9263
9264(The `make tags' command works well with the GNU Emacs sources, as
9265well as with some other source packages.)
9266
9267For more information, see *Note Tag Tables: (emacs)Tags.
9268
9269Review
9270======
9271
9272Here is a brief summary of some recently introduced functions.
9273
9274`while'
9275 Repeatedly evaluate the body of the expression so long as the
9276 first element of the body tests true. Then return `nil'. (The
9277 expression is evaluated only for its side effects.)
9278
9279 For example:
9280
9281 (let ((foo 2))
9282 (while (> foo 0)
9283 (insert (format "foo is %d.\n" foo))
9284 (setq foo (1- foo))))
9285
9286 => foo is 2.
9287 foo is 1.
9288 nil
9289
9290 (The `insert' function inserts its arguments at point; the
9291 `format' function returns a string formatted from its arguments
9292 the way `message' formats its arguments; `\n' produces a new
9293 line.)
9294
9295`re-search-forward'
9296 Search for a pattern, and if the pattern is found, move point to
9297 rest just after it.
9298
9299 Takes four arguments, like `search-forward':
9300
9301 1. A regular expression that specifies the pattern to search
9302 for.
9303
9304 2. Optionally, the limit of the search.
9305
9306 3. Optionally, what to do if the search fails, return `nil' or
9307 an error message.
9308
9309 4. Optionally, how many times to repeat the search; if
9310 negative, the search goes backwards.
9311
9312`let*'
9313 Bind some variables locally to particular values, and then
9314 evaluate the remaining arguments, returning the value of the
9315 last one. While binding the local variables, use the local
9316 values of variables bound earlier, if any.
9317
9318 For example:
9319
9320 (let* ((foo 7)
9321 (bar (* 3 foo)))
9322 (message "`bar' is %d." bar))
9323 => `bar' is 21.
9324
9325`match-beginning'
9326 Return the position of the start of the text found by the last
9327 regular expression search.
9328
9329`looking-at'
9330 Return `t' for true if the text after point matches the argument,
9331 which should be a regular expression.
9332
9333`eobp'
9334 Return `t' for true if point is at the end of the accessible part
9335 of a buffer. The end of the accessible part is the end of the
9336 buffer if the buffer is not narrowed; it is the end of the
9337 narrowed part if the buffer is narrowed.
9338
9339`prog1'
9340 Evaluate each argument in sequence and then return the value of
9341 the _first_.
9342
9343 For example:
9344
9345 (prog1 1 2 3 4)
9346 => 1
9347
9348Exercises with `re-search-forward'
9349==================================
9350
9351 * Write a function to search for a regular expression that matches
9352 two or more blank lines in sequence.
9353
9354 * Write a function to search for duplicated words, such as `the
9355 the'. *Note Syntax of Regular Expressions: (emacs)Regexps, for
9356 information on how to write a regexp (a regular expression) to
9357 match a string that is composed of two identical halves. You
9358 can devise several regexps; some are better than others. The
9359 function I use is described in an appendix, along with several
9360 regexps. *Note `the-the' Duplicated Words Function: the-the.
9361
9362Counting: Repetition and Regexps
9363********************************
9364
9365Repetition and regular expression searches are powerful tools that you
9366often use when you write code in Emacs Lisp. This chapter illustrates
9367the use of regular expression searches through the construction of
9368word count commands using `while' loops and recursion.
9369
9370Counting words
9371==============
9372
9373The standard Emacs distribution contains a function for counting the
9374number of lines within a region. However, there is no corresponding
9375function for counting words.
9376
9377Certain types of writing ask you to count words. Thus, if you write
9378an essay, you may be limited to 800 words; if you write a novel, you
9379may discipline yourself to write 1000 words a day. It seems odd to me
9380that Emacs lacks a word count command. Perhaps people use Emacs
9381mostly for code or types of documentation that do not require word
9382counts; or perhaps they restrict themselves to the operating system
9383word count command, `wc'. Alternatively, people may follow the
9384publishers' convention and compute a word count by dividing the
9385number of characters in a document by five. In any event, here are
9386commands to count words.
9387
9388The `count-words-region' Function
9389=================================
9390
9391A word count command could count words in a line, paragraph, region,
9392or buffer. What should the command cover? You could design the
9393command to count the number of words in a complete buffer. However,
9394the Emacs tradition encourages flexibility--you may want to count
9395words in just a section, rather than all of a buffer. So it makes
9396more sense to design the command to count the number of words in a
9397region. Once you have a `count-words-region' command, you can, if
9398you wish, count words in a whole buffer by marking it with `C-x h'
9399(`mark-whole-buffer').
9400
9401Clearly, counting words is a repetitive act: starting from the
9402beginning of the region, you count the first word, then the second
9403word, then the third word, and so on, until you reach the end of the
9404region. This means that word counting is ideally suited to recursion
9405or to a `while' loop.
9406
9407Designing `count-words-region'
9408------------------------------
9409
9410First, we will implement the word count command with a `while' loop,
9411then with recursion. The command will, of course, be interactive.
9412
9413The template for an interactive function definition is, as always:
9414
9415 (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
9416 "DOCUMENTATION..."
9417 (INTERACTIVE-EXPRESSION...)
9418 BODY...)
9419
9420What we need to do is fill in the slots.
9421
9422The name of the function should be self-explanatory and similar to the
9423existing `count-lines-region' name. This makes the name easier to
9424remember. `count-words-region' is a good choice.
9425
9426The function counts words within a region. This means that the
9427argument list must contain symbols that are bound to the two
9428positions, the beginning and end of the region. These two positions
9429can be called `beginning' and `end' respectively. The first line of
9430the documentation should be a single sentence, since that is all that
9431is printed as documentation by a command such as `apropos'. The
9432interactive expression will be of the form `(interactive "r")', since
9433that will cause Emacs to pass the beginning and end of the region to
9434the function's argument list. All this is routine.
9435
9436The body of the function needs to be written to do three tasks:
9437first, to set up conditions under which the `while' loop can count
9438words, second, to run the `while' loop, and third, to send a message
9439to the user.
9440
9441When a user calls `count-words-region', point may be at the beginning
9442or the end of the region. However, the counting process must start
9443at the beginning of the region. This means we will want to put point
9444there if it is not already there. Executing `(goto-char beginning)'
9445ensures this. Of course, we will want to return point to its
9446expected position when the function finishes its work. For this
9447reason, the body must be enclosed in a `save-excursion' expression.
9448
9449The central part of the body of the function consists of a `while'
9450loop in which one expression jumps point forward word by word, and
9451another expression counts those jumps. The true-or-false-test of the
9452`while' loop should test true so long as point should jump forward,
9453and false when point is at the end of the region.
9454
9455We could use `(forward-word 1)' as the expression for moving point
9456forward word by word, but it is easier to see what Emacs identifies
9457as a `word' if we use a regular expression search.
9458
9459A regular expression search that finds the pattern for which it is
9460searching leaves point after the last character matched. This means
9461that a succession of successful word searches will move point forward
9462word by word.
9463
9464As a practical matter, we want the regular expression search to jump
9465over whitespace and punctuation between words as well as over the
9466words themselves. A regexp that refuses to jump over interword
9467whitespace would never jump more than one word! This means that the
9468regexp should include the whitespace and punctuation that follows a
9469word, if any, as well as the word itself. (A word may end a buffer
9470and not have any following whitespace or punctuation, so that part of
9471the regexp must be optional.)
9472
9473Thus, what we want for the regexp is a pattern defining one or more
9474word constituent characters followed, optionally, by one or more
9475characters that are not word constituents. The regular expression for
9476this is:
9477
9478 \w+\W*
9479
9480The buffer's syntax table determines which characters are and are not
9481word constituents. (*Note What Constitutes a Word or Symbol?:
9482Syntax, for more about syntax. Also, see *Note Syntax:
9483(emacs)Syntax, and *Note Syntax Tables: (elisp)Syntax Tables.)
9484
9485The search expression looks like this:
9486
9487 (re-search-forward "\\w+\\W*")
9488
9489(Note that paired backslashes precede the `w' and `W'. A single
9490backslash has special meaning to the Emacs Lisp interpreter. It
9491indicates that the following character is interpreted differently than
9492usual. For example, the two characters, `\n', stand for `newline',
9493rather than for a backslash followed by `n'. Two backslashes in a
9494row stand for an ordinary, `unspecial' backslash.)
9495
9496We need a counter to count how many words there are; this variable
9497must first be set to 0 and then incremented each time Emacs goes
9498around the `while' loop. The incrementing expression is simply:
9499
9500 (setq count (1+ count))
9501
9502Finally, we want to tell the user how many words there are in the
9503region. The `message' function is intended for presenting this kind
9504of information to the user. The message has to be phrased so that it
9505reads properly regardless of how many words there are in the region:
9506we don't want to say that "there are 1 words in the region". The
9507conflict between singular and plural is ungrammatical. We can solve
9508this problem by using a conditional expression that evaluates
9509different messages depending on the number of words in the region.
9510There are three possibilities: no words in the region, one word in the
9511region, and more than one word. This means that the `cond' special
9512form is appropriate.
9513
9514All this leads to the following function definition:
9515
9516 ;;; First version; has bugs!
9517 (defun count-words-region (beginning end)
9518 "Print number of words in the region.
9519 Words are defined as at least one word-constituent
9520 character followed by at least one character that
9521 is not a word-constituent. The buffer's syntax
9522 table determines which characters these are."
9523 (interactive "r")
9524 (message "Counting words in region ... ")
9525
9526 ;;; 1. Set up appropriate conditions.
9527 (save-excursion
9528 (goto-char beginning)
9529 (let ((count 0))
9530
9531 ;;; 2. Run the while loop.
9532 (while (< (point) end)
9533 (re-search-forward "\\w+\\W*")
9534 (setq count (1+ count)))
9535
9536 ;;; 3. Send a message to the user.
9537 (cond ((zerop count)
9538 (message
9539 "The region does NOT have any words."))
9540 ((= 1 count)
9541 (message
9542 "The region has 1 word."))
9543 (t
9544 (message
9545 "The region has %d words." count))))))
9546
9547As written, the function works, but not in all circumstances.
9548
9549The Whitespace Bug in `count-words-region'
9550------------------------------------------
9551
9552The `count-words-region' command described in the preceding section
9553has two bugs, or rather, one bug with two manifestations. First, if
9554you mark a region containing only whitespace in the middle of some
9555text, the `count-words-region' command tells you that the region
9556contains one word! Second, if you mark a region containing only
9557whitespace at the end of the buffer or the accessible portion of a
9558narrowed buffer, the command displays an error message that looks
9559like this:
9560
9561 Search failed: "\\w+\\W*"
9562
9563If you are reading this in Info in GNU Emacs, you can test for these
9564bugs yourself.
9565
9566First, evaluate the function in the usual manner to install it. Here
9567is a copy of the definition. Place your cursor after the closing
9568parenthesis and type `C-x C-e' to install it.
9569
9570 ;; First version; has bugs!
9571 (defun count-words-region (beginning end)
9572 "Print number of words in the region.
9573 Words are defined as at least one word-constituent character followed
9574 by at least one character that is not a word-constituent. The buffer's
9575 syntax table determines which characters these are."
9576 (interactive "r")
9577 (message "Counting words in region ... ")
9578
9579 ;;; 1. Set up appropriate conditions.
9580 (save-excursion
9581 (goto-char beginning)
9582 (let ((count 0))
9583
9584 ;;; 2. Run the while loop.
9585 (while (< (point) end)
9586 (re-search-forward "\\w+\\W*")
9587 (setq count (1+ count)))
9588
9589 ;;; 3. Send a message to the user.
9590 (cond ((zerop count)
9591 (message "The region does NOT have any words."))
9592 ((= 1 count) (message "The region has 1 word."))
9593 (t (message "The region has %d words." count))))))
9594
9595If you wish, you can also install this keybinding by evaluating it:
9596
9597 (global-set-key "\C-c=" 'count-words-region)
9598
9599To conduct the first test, set mark and point to the beginning and end
9600of the following line and then type `C-c =' (or `M-x
9601count-words-region' if you have not bound `C-c ='):
9602
9603 one two three
9604
9605Emacs will tell you, correctly, that the region has three words.
9606
9607Repeat the test, but place mark at the beginning of the line and place
9608point just _before_ the word `one'. Again type the command `C-c ='
9609(or `M-x count-words-region'). Emacs should tell you that the region
9610has no words, since it is composed only of the whitespace at the
9611beginning of the line. But instead Emacs tells you that the region
9612has one word!
9613
9614For the third test, copy the sample line to the end of the
9615`*scratch*' buffer and then type several spaces at the end of the
9616line. Place mark right after the word `three' and point at the end
9617of line. (The end of the line will be the end of the buffer.) Type
9618`C-c =' (or `M-x count-words-region') as you did before. Again,
9619Emacs should tell you that the region has no words, since it is
9620composed only of the whitespace at the end of the line. Instead,
9621Emacs displays an error message saying `Search failed'.
9622
9623The two bugs stem from the same problem.
9624
9625Consider the first manifestation of the bug, in which the command
9626tells you that the whitespace at the beginning of the line contains
9627one word. What happens is this: The `M-x count-words-region' command
9628moves point to the beginning of the region. The `while' tests
9629whether the value of point is smaller than the value of `end', which
9630it is. Consequently, the regular expression search looks for and
9631finds the first word. It leaves point after the word. `count' is
9632set to one. The `while' loop repeats; but this time the value of
9633point is larger than the value of `end', the loop is exited; and the
9634function displays a message saying the number of words in the region
9635is one. In brief, the regular expression search looks for and finds
9636the word even though it is outside the marked region.
9637
9638In the second manifestation of the bug, the region is whitespace at
9639the end of the buffer. Emacs says `Search failed'. What happens is
9640that the true-or-false-test in the `while' loop tests true, so the
9641search expression is executed. But since there are no more words in
9642the buffer, the search fails.
9643
9644In both manifestations of the bug, the search extends or attempts to
9645extend outside of the region.
9646
9647The solution is to limit the search to the region--this is a fairly
9648simple action, but as you may have come to expect, it is not quite as
9649simple as you might think.
9650
9651As we have seen, the `re-search-forward' function takes a search
9652pattern as its first argument. But in addition to this first,
9653mandatory argument, it accepts three optional arguments. The optional
9654second argument bounds the search. The optional third argument, if
9655`t', causes the function to return `nil' rather than signal an error
9656if the search fails. The optional fourth argument is a repeat count.
9657(In Emacs, you can see a function's documentation by typing `C-h f',
9658the name of the function, and then <RET>.)
9659
9660In the `count-words-region' definition, the value of the end of the
9661region is held by the variable `end' which is passed as an argument
9662to the function. Thus, we can add `end' as an argument to the
9663regular expression search expression:
9664
9665 (re-search-forward "\\w+\\W*" end)
9666
9667However, if you make only this change to the `count-words-region'
9668definition and then test the new version of the definition on a
9669stretch of whitespace, you will receive an error message saying
9670`Search failed'.
9671
9672What happens is this: the search is limited to the region, and fails
9673as you expect because there are no word-constituent characters in the
9674region. Since it fails, we receive an error message. But we do not
9675want to receive an error message in this case; we want to receive the
9676message that "The region does NOT have any words."
9677
9678The solution to this problem is to provide `re-search-forward' with a
9679third argument of `t', which causes the function to return `nil'
9680rather than signal an error if the search fails.
9681
9682However, if you make this change and try it, you will see the message
9683"Counting words in region ... " and ... you will keep on seeing that
9684message ..., until you type `C-g' (`keyboard-quit').
9685
9686Here is what happens: the search is limited to the region, as before,
9687and it fails because there are no word-constituent characters in the
9688region, as expected. Consequently, the `re-search-forward'
9689expression returns `nil'. It does nothing else. In particular, it
9690does not move point, which it does as a side effect if it finds the
9691search target. After the `re-search-forward' expression returns
9692`nil', the next expression in the `while' loop is evaluated. This
9693expression increments the count. Then the loop repeats. The
9694true-or-false-test tests true because the value of point is still less
9695than the value of end, since the `re-search-forward' expression did
9696not move point. ... and the cycle repeats ...
9697
9698The `count-words-region' definition requires yet another
9699modification, to cause the true-or-false-test of the `while' loop to
9700test false if the search fails. Put another way, there are two
9701conditions that must be satisfied in the true-or-false-test before the
9702word count variable is incremented: point must still be within the
9703region and the search expression must have found a word to count.
9704
9705Since both the first condition and the second condition must be true
9706together, the two expressions, the region test and the search
9707expression, can be joined with an `and' special form and embedded in
9708the `while' loop as the true-or-false-test, like this:
9709
9710 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
9711
9712(*Note forward-paragraph::, for information about `and'.)
9713
9714The `re-search-forward' expression returns `t' if the search succeeds
9715and as a side effect moves point. Consequently, as words are found,
9716point is moved through the region. When the search expression fails
9717to find another word, or when point reaches the end of the region,
9718the true-or-false-test tests false, the `while' loop exists, and the
9719`count-words-region' function displays one or other of its messages.
9720
9721After incorporating these final changes, the `count-words-region'
9722works without bugs (or at least, without bugs that I have found!).
9723Here is what it looks like:
9724
9725 ;;; Final version: `while'
9726 (defun count-words-region (beginning end)
9727 "Print number of words in the region."
9728 (interactive "r")
9729 (message "Counting words in region ... ")
9730
9731 ;;; 1. Set up appropriate conditions.
9732 (save-excursion
9733 (let ((count 0))
9734 (goto-char beginning)
9735
9736 ;;; 2. Run the while loop.
9737 (while (and (< (point) end)
9738 (re-search-forward "\\w+\\W*" end t))
9739 (setq count (1+ count)))
9740
9741 ;;; 3. Send a message to the user.
9742 (cond ((zerop count)
9743 (message
9744 "The region does NOT have any words."))
9745 ((= 1 count)
9746 (message
9747 "The region has 1 word."))
9748 (t
9749 (message
9750 "The region has %d words." count))))))
9751
9752Count Words Recursively
9753=======================
9754
9755You can write the function for counting words recursively as well as
9756with a `while' loop. Let's see how this is done.
9757
9758First, we need to recognize that the `count-words-region' function
9759has three jobs: it sets up the appropriate conditions for counting to
9760occur; it counts the words in the region; and it sends a message to
9761the user telling how many words there are.
9762
9763If we write a single recursive function to do everything, we will
9764receive a message for every recursive call. If the region contains 13
9765words, we will receive thirteen messages, one right after the other.
9766We don't want this! Instead, we must write two functions to do the
9767job, one of which (the recursive function) will be used inside of the
9768other. One function will set up the conditions and display the
9769message; the other will return the word count.
9770
9771Let us start with the function that causes the message to be
9772displayed. We can continue to call this `count-words-region'.
9773
9774This is the function that the user will call. It will be interactive.
9775Indeed, it will be similar to our previous versions of this function,
9776except that it will call `recursive-count-words' to determine how
9777many words are in the region.
9778
9779We can readily construct a template for this function, based on our
9780previous versions:
9781
9782 ;; Recursive version; uses regular expression search
9783 (defun count-words-region (beginning end)
9784 "DOCUMENTATION..."
9785 (INTERACTIVE-EXPRESSION...)
9786
9787 ;;; 1. Set up appropriate conditions.
9788 (EXPLANATORY MESSAGE)
9789 (SET-UP FUNCTIONS...
9790
9791 ;;; 2. Count the words.
9792 RECURSIVE CALL
9793
9794 ;;; 3. Send a message to the user.
9795 MESSAGE PROVIDING WORD COUNT))
9796
9797The definition looks straightforward, except that somehow the count
9798returned by the recursive call must be passed to the message
9799displaying the word count. A little thought suggests that this can be
9800done by making use of a `let' expression: we can bind a variable in
9801the varlist of a `let' expression to the number of words in the
9802region, as returned by the recursive call; and then the `cond'
9803expression, using binding, can display the value to the user.
9804
9805Often, one thinks of the binding within a `let' expression as somehow
9806secondary to the `primary' work of a function. But in this case,
9807what you might consider the `primary' job of the function, counting
9808words, is done within the `let' expression.
9809
9810Using `let', the function definition looks like this:
9811
9812 (defun count-words-region (beginning end)
9813 "Print number of words in the region."
9814 (interactive "r")
9815
9816 ;;; 1. Set up appropriate conditions.
9817 (message "Counting words in region ... ")
9818 (save-excursion
9819 (goto-char beginning)
9820
9821 ;;; 2. Count the words.
9822 (let ((count (recursive-count-words end)))
9823
9824 ;;; 3. Send a message to the user.
9825 (cond ((zerop count)
9826 (message
9827 "The region does NOT have any words."))
9828 ((= 1 count)
9829 (message
9830 "The region has 1 word."))
9831 (t
9832 (message
9833 "The region has %d words." count))))))
9834
9835Next, we need to write the recursive counting function.
9836
9837A recursive function has at least three parts: the `do-again-test',
9838the `next-step-expression', and the recursive call.
9839
9840The do-again-test determines whether the function will or will not be
9841called again. Since we are counting words in a region and can use a
9842function that moves point forward for every word, the do-again-test
9843can check whether point is still within the region. The do-again-test
9844should find the value of point and determine whether point is before,
9845at, or after the value of the end of the region. We can use the
9846`point' function to locate point. Clearly, we must pass the value of
9847the end of the region to the recursive counting function as an
9848argument.
9849
9850In addition, the do-again-test should also test whether the search
9851finds a word. If it does not, the function should not call itself
9852again.
9853
9854The next-step-expression changes a value so that when the recursive
9855function is supposed to stop calling itself, it stops. More
9856precisely, the next-step-expression changes a value so that at the
9857right time, the do-again-test stops the recursive function from
9858calling itself again. In this case, the next-step-expression can be
9859the expression that moves point forward, word by word.
9860
9861The third part of a recursive function is the recursive call.
9862
9863Somewhere, also, we also need a part that does the `work' of the
9864function, a part that does the counting. A vital part!
9865
9866But already, we have an outline of the recursive counting function:
9867
9868 (defun recursive-count-words (region-end)
9869 "DOCUMENTATION..."
9870 DO-AGAIN-TEST
9871 NEXT-STEP-EXPRESSION
9872 RECURSIVE CALL)
9873
9874Now we need to fill in the slots. Let's start with the simplest cases
9875first: if point is at or beyond the end of the region, there cannot
9876be any words in the region, so the function should return zero.
9877Likewise, if the search fails, there are no words to count, so the
9878function should return zero.
9879
9880On the other hand, if point is within the region and the search
9881succeeds, the function should call itself again.
9882
9883Thus, the do-again-test should look like this:
9884
9885 (and (< (point) region-end)
9886 (re-search-forward "\\w+\\W*" region-end t))
9887
9888Note that the search expression is part of the do-again-test--the
9889function returns `t' if its search succeeds and `nil' if it fails.
9890(*Note The Whitespace Bug in `count-words-region': Whitespace Bug,
9891for an explanation of how `re-search-forward' works.)
9892
9893The do-again-test is the true-or-false test of an `if' clause.
9894Clearly, if the do-again-test succeeds, the then-part of the `if'
9895clause should call the function again; but if it fails, the else-part
9896should return zero since either point is outside the region or the
9897search failed because there were no words to find.
9898
9899But before considering the recursive call, we need to consider the
9900next-step-expression. What is it? Interestingly, it is the search
9901part of the do-again-test.
9902
9903In addition to returning `t' or `nil' for the do-again-test,
9904`re-search-forward' moves point forward as a side effect of a
9905successful search. This is the action that changes the value of
9906point so that the recursive function stops calling itself when point
9907completes its movement through the region. Consequently, the
9908`re-search-forward' expression is the next-step-expression.
9909
9910In outline, then, the body of the `recursive-count-words' function
9911looks like this:
9912
9913 (if DO-AGAIN-TEST-AND-NEXT-STEP-COMBINED
9914 ;; then
9915 RECURSIVE-CALL-RETURNING-COUNT
9916 ;; else
9917 RETURN-ZERO)
9918
9919How to incorporate the mechanism that counts?
9920
9921If you are not used to writing recursive functions, a question like
9922this can be troublesome. But it can and should be approached
9923systematically.
9924
9925We know that the counting mechanism should be associated in some way
9926with the recursive call. Indeed, since the next-step-expression moves
9927point forward by one word, and since a recursive call is made for
9928each word, the counting mechanism must be an expression that adds one
9929to the value returned by a call to `recursive-count-words'.
9930
9931Consider several cases:
9932
9933 * If there are two words in the region, the function should return
9934 a value resulting from adding one to the value returned when it
9935 counts the first word, plus the number returned when it counts
9936 the remaining words in the region, which in this case is one.
9937
9938 * If there is one word in the region, the function should return a
9939 value resulting from adding one to the value returned when it
9940 counts that word, plus the number returned when it counts the
9941 remaining words in the region, which in this case is zero.
9942
9943 * If there are no words in the region, the function should return
9944 zero.
9945
9946From the sketch we can see that the else-part of the `if' returns
9947zero for the case of no words. This means that the then-part of the
9948`if' must return a value resulting from adding one to the value
9949returned from a count of the remaining words.
9950
9951The expression will look like this, where `1+' is a function that
9952adds one to its argument.
9953
9954 (1+ (recursive-count-words region-end))
9955
9956The whole `recursive-count-words' function will then look like this:
9957
9958 (defun recursive-count-words (region-end)
9959 "DOCUMENTATION..."
9960
9961 ;;; 1. do-again-test
9962 (if (and (< (point) region-end)
9963 (re-search-forward "\\w+\\W*" region-end t))
9964
9965 ;;; 2. then-part: the recursive call
9966 (1+ (recursive-count-words region-end))
9967
9968 ;;; 3. else-part
9969 0))
9970
9971Let's examine how this works:
9972
9973If there are no words in the region, the else part of the `if'
9974expression is evaluated and consequently the function returns zero.
9975
9976If there is one word in the region, the value of point is less than
9977the value of `region-end' and the search succeeds. In this case, the
9978true-or-false-test of the `if' expression tests true, and the
9979then-part of the `if' expression is evaluated. The counting
9980expression is evaluated. This expression returns a value (which will
9981be the value returned by the whole function) that is the sum of one
9982added to the value returned by a recursive call.
9983
9984Meanwhile, the next-step-expression has caused point to jump over the
9985first (and in this case only) word in the region. This means that
9986when `(recursive-count-words region-end)' is evaluated a second time,
9987as a result of the recursive call, the value of point will be equal
9988to or greater than the value of region end. So this time,
9989`recursive-count-words' will return zero. The zero will be added to
9990one, and the original evaluation of `recursive-count-words' will
9991return one plus zero, which is one, which is the correct amount.
9992
9993Clearly, if there are two words in the region, the first call to
9994`recursive-count-words' returns one added to the value returned by
9995calling `recursive-count-words' on a region containing the remaining
9996word--that is, it adds one to one, producing two, which is the
9997correct amount.
9998
9999Similarly, if there are three words in the region, the first call to
10000`recursive-count-words' returns one added to the value returned by
10001calling `recursive-count-words' on a region containing the remaining
10002two words--and so on and so on.
10003
10004With full documentation the two functions look like this:
10005
10006The recursive function:
10007
10008 (defun recursive-count-words (region-end)
10009 "Number of words between point and REGION-END."
10010
10011 ;;; 1. do-again-test
10012 (if (and (< (point) region-end)
10013 (re-search-forward "\\w+\\W*" region-end t))
10014
10015 ;;; 2. then-part: the recursive call
10016 (1+ (recursive-count-words region-end))
10017
10018 ;;; 3. else-part
10019 0))
10020
10021The wrapper:
10022
10023 ;;; Recursive version
10024 (defun count-words-region (beginning end)
10025 "Print number of words in the region.
10026
10027 Words are defined as at least one word-constituent
10028 character followed by at least one character that is
10029 not a word-constituent. The buffer's syntax table
10030 determines which characters these are."
10031 (interactive "r")
10032 (message "Counting words in region ... ")
10033 (save-excursion
10034 (goto-char beginning)
10035 (let ((count (recursive-count-words end)))
10036 (cond ((zerop count)
10037 (message
10038 "The region does NOT have any words."))
10039 ((= 1 count)
10040 (message "The region has 1 word."))
10041 (t
10042 (message
10043 "The region has %d words." count))))))
10044
10045Exercise: Counting Punctuation
10046==============================
10047
10048Using a `while' loop, write a function to count the number of
10049punctuation marks in a region--period, comma, semicolon, colon,
10050exclamation mark, and question mark. Do the same using recursion.
10051
10052Counting Words in a `defun'
10053***************************
10054
10055Our next project is to count the number of words in a function
10056definition. Clearly, this can be done using some variant of
10057`count-word-region'. *Note Counting Words: Repetition and Regexps:
10058Counting Words. If we are just going to count the words in one
10059definition, it is easy enough to mark the definition with the `C-M-h'
10060(`mark-defun') command, and then call `count-word-region'.
10061
10062However, I am more ambitious: I want to count the words and symbols in
10063every definition in the Emacs sources and then print a graph that
10064shows how many functions there are of each length: how many contain 40
10065to 49 words or symbols, how many contain 50 to 59 words or symbols,
10066and so on. I have often been curious how long a typical function is,
10067and this will tell.
10068
10069Divide and Conquer
10070==================
10071
10072Described in one phrase, the histogram project is daunting; but
10073divided into numerous small steps, each of which we can take one at a
10074time, the project becomes less fearsome. Let us consider what the
10075steps must be:
10076
10077 * First, write a function to count the words in one definition.
10078 This includes the problem of handling symbols as well as words.
10079
10080 * Second, write a function to list the numbers of words in each
10081 function in a file. This function can use the
10082 `count-words-in-defun' function.
10083
10084 * Third, write a function to list the numbers of words in each
10085 function in each of several files. This entails automatically
10086 finding the various files, switching to them, and counting the
10087 words in the definitions within them.
10088
10089 * Fourth, write a function to convert the list of numbers that we
10090 created in step three to a form that will be suitable for
10091 printing as a graph.
10092
10093 * Fifth, write a function to print the results as a graph.
10094
10095This is quite a project! But if we take each step slowly, it will not
10096be difficult.
10097
10098What to Count?
10099==============
10100
10101When we first start thinking about how to count the words in a
10102function definition, the first question is (or ought to be) what are
10103we going to count? When we speak of `words' with respect to a Lisp
10104function definition, we are actually speaking, in large part, of
10105`symbols'. For example, the following `multiply-by-seven' function
10106contains the five symbols `defun', `multiply-by-seven', `number',
10107`*', and `7'. In addition, in the documentation string, it contains
10108the four words `Multiply', `NUMBER', `by', and `seven'. The symbol
10109`number' is repeated, so the definition contains a total of ten words
10110and symbols.
10111
10112 (defun multiply-by-seven (number)
10113 "Multiply NUMBER by seven."
10114 (* 7 number))
10115
10116However, if we mark the `multiply-by-seven' definition with `C-M-h'
10117(`mark-defun'), and then call `count-words-region' on it, we will
10118find that `count-words-region' claims the definition has eleven
10119words, not ten! Something is wrong!
10120
10121The problem is twofold: `count-words-region' does not count the `*'
10122as a word, and it counts the single symbol, `multiply-by-seven', as
10123containing three words. The hyphens are treated as if they were
10124interword spaces rather than intraword connectors:
10125`multiply-by-seven' is counted as if it were written `multiply by
10126seven'.
10127
10128The cause of this confusion is the regular expression search within
10129the `count-words-region' definition that moves point forward word by
10130word. In the canonical version of `count-words-region', the regexp
10131is:
10132
10133 "\\w+\\W*"
10134
10135This regular expression is a pattern defining one or more word
10136constituent characters possibly followed by one or more characters
10137that are not word constituents. What is meant by `word constituent
10138characters' brings us to the issue of syntax, which is worth a section
10139of its own.
10140
10141What Constitutes a Word or Symbol?
10142==================================
10143
10144Emacs treats different characters as belonging to different "syntax
10145categories". For example, the regular expression, `\\w+', is a
10146pattern specifying one or more _word constituent_ characters. Word
10147constituent characters are members of one syntax category. Other
10148syntax categories include the class of punctuation characters, such
10149as the period and the comma, and the class of whitespace characters,
10150such as the blank space and the tab character. (For more
10151information, see *Note Syntax: (emacs)Syntax, and *Note Syntax
10152Tables: (elisp)Syntax Tables.)
10153
10154Syntax tables specify which characters belong to which categories.
10155Usually, a hyphen is not specified as a `word constituent character'.
10156Instead, it is specified as being in the `class of characters that are
10157part of symbol names but not words.' This means that the
10158`count-words-region' function treats it in the same way it treats an
10159interword white space, which is why `count-words-region' counts
10160`multiply-by-seven' as three words.
10161
10162There are two ways to cause Emacs to count `multiply-by-seven' as one
10163symbol: modify the syntax table or modify the regular expression.
10164
10165We could redefine a hyphen as a word constituent character by
10166modifying the syntax table that Emacs keeps for each mode. This
10167action would serve our purpose, except that a hyphen is merely the
10168most common character within symbols that is not typically a word
10169constituent character; there are others, too.
10170
10171Alternatively, we can redefine the regular expression used in the
10172`count-words' definition so as to include symbols. This procedure
10173has the merit of clarity, but the task is a little tricky.
10174
10175The first part is simple enough: the pattern must match "at least one
10176character that is a word or symbol constituent". Thus:
10177
10178 "\\(\\w\\|\\s_\\)+"
10179
10180The `\\(' is the first part of the grouping construct that includes
10181the `\\w' and the `\\s_' as alternatives, separated by the `\\|'.
10182The `\\w' matches any word-constituent character and the `\\s_'
10183matches any character that is part of a symbol name but not a
10184word-constituent character. The `+' following the group indicates
10185that the word or symbol constituent characters must be matched at
10186least once.
10187
10188However, the second part of the regexp is more difficult to design.
10189What we want is to follow the first part with "optionally one or more
10190characters that are not constituents of a word or symbol". At first,
10191I thought I could define this with the following:
10192
10193 "\\(\\W\\|\\S_\\)*"
10194
10195The upper case `W' and `S' match characters that are _not_ word or
10196symbol constituents. Unfortunately, this expression matches any
10197character that is either not a word constituent or not a symbol
10198constituent. This matches any character!
10199
10200I then noticed that every word or symbol in my test region was
10201followed by white space (blank space, tab, or newline). So I tried
10202placing a pattern to match one or more blank spaces after the pattern
10203for one or more word or symbol constituents. This failed, too. Words
10204and symbols are often separated by whitespace, but in actual code
10205parentheses may follow symbols and punctuation may follow words. So
10206finally, I designed a pattern in which the word or symbol constituents
10207are followed optionally by characters that are not white space and
10208then followed optionally by white space.
10209
10210Here is the full regular expression:
10211
10212 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
10213
10214The `count-words-in-defun' Function
10215===================================
10216
10217We have seen that there are several ways to write a
10218`count-word-region' function. To write a `count-words-in-defun', we
10219need merely adapt one of these versions.
10220
10221The version that uses a `while' loop is easy to understand, so I am
10222going to adapt that. Because `count-words-in-defun' will be part of
10223a more complex program, it need not be interactive and it need not
10224display a message but just return the count. These considerations
10225simplify the definition a little.
10226
10227On the other hand, `count-words-in-defun' will be used within a
10228buffer that contains function definitions. Consequently, it is
10229reasonable to ask that the function determine whether it is called
10230when point is within a function definition, and if it is, to return
10231the count for that definition. This adds complexity to the
10232definition, but saves us from needing to pass arguments to the
10233function.
10234
10235These considerations lead us to prepare the following template:
10236
10237 (defun count-words-in-defun ()
10238 "DOCUMENTATION..."
10239 (SET UP...
10240 (WHILE LOOP...)
10241 RETURN COUNT)
10242
10243As usual, our job is to fill in the slots.
10244
10245First, the set up.
10246
10247We are presuming that this function will be called within a buffer
10248containing function definitions. Point will either be within a
10249function definition or not. For `count-words-in-defun' to work,
10250point must move to the beginning of the definition, a counter must
10251start at zero, and the counting loop must stop when point reaches the
10252end of the definition.
10253
10254The `beginning-of-defun' function searches backwards for an opening
10255delimiter such as a `(' at the beginning of a line, and moves point
10256to that position, or else to the limit of the search. In practice,
10257this means that `beginning-of-defun' moves point to the beginning of
10258an enclosing or preceding function definition, or else to the
10259beginning of the buffer. We can use `beginning-of-defun' to place
10260point where we wish to start.
10261
10262The `while' loop requires a counter to keep track of the words or
10263symbols being counted. A `let' expression can be used to create a
10264local variable for this purpose, and bind it to an initial value of
10265zero.
10266
10267The `end-of-defun' function works like `beginning-of-defun' except
10268that it moves point to the end of the definition. `end-of-defun' can
10269be used as part of an expression that determines the position of the
10270end of the definition.
10271
10272The set up for `count-words-in-defun' takes shape rapidly: first we
10273move point to the beginning of the definition, then we create a local
10274variable to hold the count, and finally, we record the position of
10275the end of the definition so the `while' loop will know when to stop
10276looping.
10277
10278The code looks like this:
10279
10280 (beginning-of-defun)
10281 (let ((count 0)
10282 (end (save-excursion (end-of-defun) (point))))
10283
10284The code is simple. The only slight complication is likely to concern
10285`end': it is bound to the position of the end of the definition by a
10286`save-excursion' expression that returns the value of point after
10287`end-of-defun' temporarily moves it to the end of the definition.
10288
10289The second part of the `count-words-in-defun', after the set up, is
10290the `while' loop.
10291
10292The loop must contain an expression that jumps point forward word by
10293word and symbol by symbol, and another expression that counts the
10294jumps. The true-or-false-test for the `while' loop should test true
10295so long as point should jump forward, and false when point is at the
10296end of the definition. We have already redefined the regular
10297expression for this (*note Syntax::), so the loop is straightforward:
10298
10299 (while (and (< (point) end)
10300 (re-search-forward
10301 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t)
10302 (setq count (1+ count)))
10303
10304The third part of the function definition returns the count of words
10305and symbols. This part is the last expression within the body of the
10306`let' expression, and can be, very simply, the local variable
10307`count', which when evaluated returns the count.
10308
10309Put together, the `count-words-in-defun' definition looks like this:
10310
10311 (defun count-words-in-defun ()
10312 "Return the number of words and symbols in a defun."
10313 (beginning-of-defun)
10314 (let ((count 0)
10315 (end (save-excursion (end-of-defun) (point))))
10316 (while
10317 (and (< (point) end)
10318 (re-search-forward
10319 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
10320 end t))
10321 (setq count (1+ count)))
10322 count))
10323
10324How to test this? The function is not interactive, but it is easy to
10325put a wrapper around the function to make it interactive; we can use
10326almost the same code as for the recursive version of
10327`count-words-region':
10328
10329 ;;; Interactive version.
10330 (defun count-words-defun ()
10331 "Number of words and symbols in a function definition."
10332 (interactive)
10333 (message
10334 "Counting words and symbols in function definition ... ")
10335 (let ((count (count-words-in-defun)))
10336 (cond
10337 ((zerop count)
10338 (message
10339 "The definition does NOT have any words or symbols."))
10340 ((= 1 count)
10341 (message
10342 "The definition has 1 word or symbol."))
10343 (t
10344 (message
10345 "The definition has %d words or symbols." count)))))
10346
10347Let's re-use `C-c =' as a convenient keybinding:
10348
10349 (global-set-key "\C-c=" 'count-words-defun)
10350
10351Now we can try out `count-words-defun': install both
10352`count-words-in-defun' and `count-words-defun', and set the
10353keybinding, and then place the cursor within the following definition:
10354
10355 (defun multiply-by-seven (number)
10356 "Multiply NUMBER by seven."
10357 (* 7 number))
10358 => 10
10359
10360Success! The definition has 10 words and symbols.
10361
10362The next problem is to count the numbers of words and symbols in
10363several definitions within a single file.
10364
10365Count Several `defuns' Within a File
10366====================================
10367
10368A file such as `simple.el' may have 80 or more function definitions
10369within it. Our long term goal is to collect statistics on many
10370files, but as a first step, our immediate goal is to collect
10371statistics on one file.
10372
10373The information will be a series of numbers, each number being the
10374length of a function definition. We can store the numbers in a list.
10375
10376We know that we will want to incorporate the information regarding one
10377file with information about many other files; this means that the
10378function for counting definition lengths within one file need only
10379return the list of lengths. It need not and should not display any
10380messages.
10381
10382The word count commands contain one expression to jump point forward
10383word by word and another expression to count the jumps. The function
10384to return the lengths of definitions can be designed to work the same
10385way, with one expression to jump point forward definition by
10386definition and another expression to construct the lengths' list.
10387
10388This statement of the problem makes it elementary to write the
10389function definition. Clearly, we will start the count at the
10390beginning of the file, so the first command will be `(goto-char
10391(point-min))'. Next, we start the `while' loop; and the
10392true-or-false test of the loop can be a regular expression search for
10393the next function definition--so long as the search succeeds, point
10394is moved forward and then the body of the loop is evaluated. The body
10395needs an expression that constructs the lengths' list. `cons', the
10396list construction command, can be used to create the list. That is
10397almost all there is to it.
10398
10399Here is what this fragment of code looks like:
10400
10401 (goto-char (point-min))
10402 (while (re-search-forward "^(defun" nil t)
10403 (setq lengths-list
10404 (cons (count-words-in-defun) lengths-list)))
10405
10406What we have left out is the mechanism for finding the file that
10407contains the function definitions.
10408
10409In previous examples, we either used this, the Info file, or we
10410switched back and forth to some other buffer, such as the `*scratch*'
10411buffer.
10412
10413Finding a file is a new process that we have not yet discussed.
10414
10415Find a File
10416===========
10417
10418To find a file in Emacs, you use the `C-x C-f' (`find-file') command.
10419This command is almost, but not quite right for the lengths problem.
10420
10421Let's look at the source for `find-file' (you can use the `find-tag'
10422command or `C-h f' (`describe-function') to find the source of a
10423function):
10424
10425 (defun find-file (filename)
10426 "Edit file FILENAME.
10427 Switch to a buffer visiting file FILENAME,
10428 creating one if none already exists."
10429 (interactive "FFind file: ")
10430 (switch-to-buffer (find-file-noselect filename)))
10431
10432The definition possesses short but complete documentation and an
10433interactive specification that prompts you for a file name when you
10434use the command interactively. The body of the definition contains
10435two functions, `find-file-noselect' and `switch-to-buffer'.
10436
10437According to its documentation as shown by `C-h f' (the
10438`describe-function' command), the `find-file-noselect' function reads
10439the named file into a buffer and returns the buffer. However, the
10440buffer is not selected. Emacs does not switch its attention (or
10441yours if you are using `find-file-noselect') to the named buffer.
10442That is what `switch-to-buffer' does: it switches the buffer to which
10443Emacs attention is directed; and it switches the buffer displayed in
10444the window to the new buffer. We have discussed buffer switching
10445elsewhere. (*Note Switching Buffers::.)
10446
10447In this histogram project, we do not need to display each file on the
10448screen as the program determines the length of each definition within
10449it. Instead of employing `switch-to-buffer', we can work with
10450`set-buffer', which redirects the attention of the computer program
10451to a different buffer but does not redisplay it on the screen. So
10452instead of calling on `find-file' to do the job, we must write our
10453own expression.
10454
10455The task is easy: use `find-file-noselect' and `set-buffer'.
10456
10457`lengths-list-file' in Detail
10458=============================
10459
10460The core of the `lengths-list-file' function is a `while' loop
10461containing a function to move point forward `defun by defun' and a
10462function to count the number of words and symbols in each defun.
10463This core must be surrounded by functions that do various other tasks,
10464including finding the file, and ensuring that point starts out at the
10465beginning of the file. The function definition looks like this:
10466
10467 (defun lengths-list-file (filename)
10468 "Return list of definitions' lengths within FILE.
10469 The returned list is a list of numbers.
10470 Each number is the number of words or
10471 symbols in one function definition."
10472 (message "Working on `%s' ... " filename)
10473 (save-excursion
10474 (let ((buffer (find-file-noselect filename))
10475 (lengths-list))
10476 (set-buffer buffer)
10477 (setq buffer-read-only t)
10478 (widen)
10479 (goto-char (point-min))
10480 (while (re-search-forward "^(defun" nil t)
10481 (setq lengths-list
10482 (cons (count-words-in-defun) lengths-list)))
10483 (kill-buffer buffer)
10484 lengths-list)))
10485
10486The function is passed one argument, the name of the file on which it
10487will work. It has four lines of documentation, but no interactive
10488specification. Since people worry that a computer is broken if they
10489don't see anything going on, the first line of the body is a message.
10490
10491The next line contains a `save-excursion' that returns Emacs'
10492attention to the current buffer when the function completes. This is
10493useful in case you embed this function in another function that
10494presumes point is restored to the original buffer.
10495
10496In the varlist of the `let' expression, Emacs finds the file and
10497binds the local variable `buffer' to the buffer containing the file.
10498At the same time, Emacs creates `lengths-list' as a local variable.
10499
10500Next, Emacs switches its attention to the buffer.
10501
10502In the following line, Emacs makes the buffer read-only. Ideally,
10503this line is not necessary. None of the functions for counting words
10504and symbols in a function definition should change the buffer.
10505Besides, the buffer is not going to be saved, even if it were changed.
10506This line is entirely the consequence of great, perhaps excessive,
10507caution. The reason for the caution is that this function and those
10508it calls work on the sources for Emacs and it is very inconvenient if
10509they are inadvertently modified. It goes without saying that I did
10510not realize a need for this line until an experiment went awry and
10511started to modify my Emacs source files ...
10512
10513Next comes a call to widen the buffer if it is narrowed. This
10514function is usually not needed--Emacs creates a fresh buffer if none
10515already exists; but if a buffer visiting the file already exists Emacs
10516returns that one. In this case, the buffer may be narrowed and must
10517be widened. If we wanted to be fully `user-friendly', we would
10518arrange to save the restriction and the location of point, but we
10519won't.
10520
10521The `(goto-char (point-min))' expression moves point to the beginning
10522of the buffer.
10523
10524Then comes a `while' loop in which the `work' of the function is
10525carried out. In the loop, Emacs determines the length of each
10526definition and constructs a lengths' list containing the information.
10527
10528Emacs kills the buffer after working through it. This is to save
10529space inside of Emacs. My version of Emacs 19 contained over 300
10530source files of interest; Emacs 21 contains over 800 source files.
10531Another function will apply `lengths-list-file' to each of the files.
10532
10533Finally, the last expression within the `let' expression is the
10534`lengths-list' variable; its value is returned as the value of the
10535whole function.
10536
10537You can try this function by installing it in the usual fashion. Then
10538place your cursor after the following expression and type `C-x C-e'
10539(`eval-last-sexp').
10540
10541 (lengths-list-file
10542 "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el")
10543
10544(You may need to change the pathname of the file; the one here worked
10545with GNU Emacs version 21.0.100. To change the expression, copy it to
10546the `*scratch*' buffer and edit it.
10547
10548(Also, to see the full length of the list, rather than a truncated
10549version, you may have to evaluate the following:
10550
10551 (custom-set-variables '(eval-expression-print-length nil))
10552
10553(*Note Setting Variables with `defcustom': defcustom. Then evaluate
10554the `lengths-list-file' expression.)
10555
10556The lengths' list for `debug.el' takes less than a second to produce
10557and looks like this:
10558
10559 (77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
10560
10561(Using my old machine, the version 19 lengths' list for `debug.el'
10562took seven seconds to produce and looked like this:
10563
10564 (75 41 80 62 20 45 44 68 45 12 34 235)
10565
10566(The newer version of `debug.el' contains more defuns than the
10567earlier one; and my new machine is much faster than the old one.)
10568
10569Note that the length of the last definition in the file is first in
10570the list.
10571
10572Count Words in `defuns' in Different Files
10573==========================================
10574
10575In the previous section, we created a function that returns a list of
10576the lengths of each definition in a file. Now, we want to define a
10577function to return a master list of the lengths of the definitions in
10578a list of files.
10579
10580Working on each of a list of files is a repetitious act, so we can use
10581either a `while' loop or recursion.
10582
10583Determine the lengths of `defuns'
10584---------------------------------
10585
10586The design using a `while' loop is routine. The argument passed the
10587function is a list of files. As we saw earlier (*note Loop
10588Example::), you can write a `while' loop so that the body of the loop
10589is evaluated if such a list contains elements, but to exit the loop
10590if the list is empty. For this design to work, the body of the loop
10591must contain an expression that shortens the list each time the body
10592is evaluated, so that eventually the list is empty. The usual
10593technique is to set the value of the list to the value of the CDR of
10594the list each time the body is evaluated.
10595
10596The template looks like this:
10597
10598 (while TEST-WHETHER-LIST-IS-EMPTY
10599 BODY...
10600 SET-LIST-TO-CDR-OF-LIST)
10601
10602Also, we remember that a `while' loop returns `nil' (the result of
10603evaluating the true-or-false-test), not the result of any evaluation
10604within its body. (The evaluations within the body of the loop are
10605done for their side effects.) However, the expression that sets the
10606lengths' list is part of the body--and that is the value that we want
10607returned by the function as a whole. To do this, we enclose the
10608`while' loop within a `let' expression, and arrange that the last
10609element of the `let' expression contains the value of the lengths'
10610list. (*Note Loop Example with an Incrementing Counter: Incrementing
10611Example.)
10612
10613These considerations lead us directly to the function itself:
10614
10615 ;;; Use `while' loop.
10616 (defun lengths-list-many-files (list-of-files)
10617 "Return list of lengths of defuns in LIST-OF-FILES."
10618 (let (lengths-list)
10619
10620 ;;; true-or-false-test
10621 (while list-of-files
10622 (setq lengths-list
10623 (append
10624 lengths-list
10625
10626 ;;; Generate a lengths' list.
10627 (lengths-list-file
10628 (expand-file-name (car list-of-files)))))
10629
10630 ;;; Make files' list shorter.
10631 (setq list-of-files (cdr list-of-files)))
10632
10633 ;;; Return final value of lengths' list.
10634 lengths-list))
10635
10636`expand-file-name' is a built-in function that converts a file name
10637to the absolute, long, path name form of the directory in which the
10638function is called.
10639
10640Thus, if `expand-file-name' is called on `debug.el' when Emacs is
10641visiting the `/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/'
10642directory,
10643
10644 debug.el
10645
10646becomes
10647
10648 /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
10649
10650The only other new element of this function definition is the as yet
10651unstudied function `append', which merits a short section for itself.
10652
10653The `append' Function
10654---------------------
10655
10656The `append' function attaches one list to another. Thus,
10657
10658 (append '(1 2 3 4) '(5 6 7 8))
10659
10660produces the list
10661
10662 (1 2 3 4 5 6 7 8)
10663
10664This is exactly how we want to attach two lengths' lists produced by
10665`lengths-list-file' to each other. The results contrast with `cons',
10666
10667 (cons '(1 2 3 4) '(5 6 7 8))
10668
10669which constructs a new list in which the first argument to `cons'
10670becomes the first element of the new list:
10671
10672 ((1 2 3 4) 5 6 7 8)
10673
10674Recursively Count Words in Different Files
10675==========================================
10676
10677Besides a `while' loop, you can work on each of a list of files with
10678recursion. A recursive version of `lengths-list-many-files' is short
10679and simple.
10680
10681The recursive function has the usual parts: the `do-again-test', the
10682`next-step-expression', and the recursive call. The `do-again-test'
10683determines whether the function should call itself again, which it
10684will do if the `list-of-files' contains any remaining elements; the
10685`next-step-expression' resets the `list-of-files' to the CDR of
10686itself, so eventually the list will be empty; and the recursive call
10687calls itself on the shorter list. The complete function is shorter
10688than this description!
10689
10690 (defun recursive-lengths-list-many-files (list-of-files)
10691 "Return list of lengths of each defun in LIST-OF-FILES."
10692 (if list-of-files ; do-again-test
10693 (append
10694 (lengths-list-file
10695 (expand-file-name (car list-of-files)))
10696 (recursive-lengths-list-many-files
10697 (cdr list-of-files)))))
10698
10699In a sentence, the function returns the lengths' list for the first of
10700the `list-of-files' appended to the result of calling itself on the
10701rest of the `list-of-files'.
10702
10703Here is a test of `recursive-lengths-list-many-files', along with the
10704results of running `lengths-list-file' on each of the files
10705individually.
10706
10707Install `recursive-lengths-list-many-files' and `lengths-list-file',
10708if necessary, and then evaluate the following expressions. You may
10709need to change the files' pathnames; those here work when this Info
10710file and the Emacs sources are located in their customary places. To
10711change the expressions, copy them to the `*scratch*' buffer, edit
10712them, and then evaluate them.
10713
10714The results are shown after the `=>'. (These results are for files
10715from Emacs Version 21.0.100; files from other versions of Emacs may
10716produce different results.)
10717
10718 (cd "/usr/local/share/emacs/21.0.100/")
10719
10720 (lengths-list-file "./lisp/macros.el")
10721 => (273 263 456 90)
10722
10723 (lengths-list-file "./lisp/mail/mailalias.el")
10724 => (38 32 26 77 174 180 321 198 324)
10725
10726 (lengths-list-file "./lisp/makesum.el")
10727 => (85 181)
10728
10729 (recursive-lengths-list-many-files
10730 '("./lisp/macros.el"
10731 "./lisp/mail/mailalias.el"
10732 "./lisp/makesum.el"))
10733 => (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
10734
10735The `recursive-lengths-list-many-files' function produces the output
10736we want.
10737
10738The next step is to prepare the data in the list for display in a
10739graph.
10740
10741Prepare the Data for Display in a Graph
10742=======================================
10743
10744The `recursive-lengths-list-many-files' function returns a list of
10745numbers. Each number records the length of a function definition.
10746What we need to do now is transform this data into a list of numbers
10747suitable for generating a graph. The new list will tell how many
10748functions definitions contain less than 10 words and symbols, how
10749many contain between 10 and 19 words and symbols, how many contain
10750between 20 and 29 words and symbols, and so on.
10751
10752In brief, we need to go through the lengths' list produced by the
10753`recursive-lengths-list-many-files' function and count the number of
10754defuns within each range of lengths, and produce a list of those
10755numbers.
10756
10757Based on what we have done before, we can readily foresee that it
10758should not be too hard to write a function that `CDRs' down the
10759lengths' list, looks at each element, determines which length range it
10760is in, and increments a counter for that range.
10761
10762However, before beginning to write such a function, we should consider
10763the advantages of sorting the lengths' list first, so the numbers are
10764ordered from smallest to largest. First, sorting will make it easier
10765to count the numbers in each range, since two adjacent numbers will
10766either be in the same length range or in adjacent ranges. Second, by
10767inspecting a sorted list, we can discover the highest and lowest
10768number, and thereby determine the largest and smallest length range
10769that we will need.
10770
10771Sorting Lists
10772-------------
10773
10774Emacs contains a function to sort lists, called (as you might guess)
10775`sort'. The `sort' function takes two arguments, the list to be
10776sorted, and a predicate that determines whether the first of two list
10777elements is "less" than the second.
10778
10779As we saw earlier (*note Using the Wrong Type Object as an Argument:
10780Wrong Type of Argument.), a predicate is a function that determines
10781whether some property is true or false. The `sort' function will
10782reorder a list according to whatever property the predicate uses;
10783this means that `sort' can be used to sort non-numeric lists by
10784non-numeric criteria--it can, for example, alphabetize a list.
10785
10786The `<' function is used when sorting a numeric list. For example,
10787
10788 (sort '(4 8 21 17 33 7 21 7) '<)
10789
10790produces this:
10791
10792 (4 7 7 8 17 21 21 33)
10793
10794(Note that in this example, both the arguments are quoted so that the
10795symbols are not evaluated before being passed to `sort' as arguments.)
10796
10797Sorting the list returned by the `recursive-lengths-list-many-files'
10798function is straightforward; it uses the `<' function:
10799
10800 (sort
10801 (recursive-lengths-list-many-files
10802 '("../lisp/macros.el"
10803 "../lisp/mailalias.el"
10804 "../lisp/makesum.el"))
10805 '<
10806
10807which produces:
10808
10809 (85 86 116 122 154 176 179 265)
10810
10811(Note that in this example, the first argument to `sort' is not
10812quoted, since the expression must be evaluated so as to produce the
10813list that is passed to `sort'.)
10814
10815Making a List of Files
10816----------------------
10817
10818The `recursive-lengths-list-many-files' function requires a list of
10819files as its argument. For our test examples, we constructed such a
10820list by hand; but the Emacs Lisp source directory is too large for us
10821to do for that. Instead, we will write a function to do the job for
10822us. In this function, we will use both a `while' loop and a
10823recursive call.
10824
10825We did not have to write a function like this for older versions of
10826GNU Emacs, since they placed all the `.el' files in one directory.
10827Instead, we were able to use the `directory-files' function, which
10828lists the names of files that match a specified pattern within a
10829single directory.
10830
10831However, recent versions of Emacs place Emacs Lisp files in
10832sub-directories of the top level `lisp' directory. This
10833re-arrangement eases navigation. For example, all the mail related
10834files are in a `lisp' sub-directory called `mail'. But at the same
10835time, this arrangement forces us to create a file listing function
10836that descends into the sub-directories.
10837
10838We can create this function, called `files-in-below-directory', using
10839familiar functions such as `car', `nthcdr', and `substring' in
10840conjunction with an existing function called
10841`directory-files-and-attributes'. This latter function not only
10842lists all the filenames in a directory, including the names of
10843sub-directories, but also their attributes.
10844
10845To restate our goal: to create a function that will enable us to feed
10846filenames to `recursive-lengths-list-many-files' as a list that looks
10847like this (but with more elements):
10848
10849 ("../lisp/macros.el"
10850 "../lisp/mail/rmail.el"
10851 "../lisp/makesum.el")
10852
10853The `directory-files-and-attributes' function returns a list of
10854lists. Each of the lists within the main list consists of 13
10855elements. The first element is a string that contains the name of the
10856file - which, in GNU/Linux, may be a `directory file', that is to
10857say, a file with the special attributes of a directory. The second
10858element of the list is `t' for a directory, a string for symbolic
10859link (the string is the name linked to), or `nil'.
10860
10861For example, the first `.el' file in the `lisp/' directory is
10862`abbrev.el'. Its name is
10863`/usr/local/share/emacs/21.0.100/lisp/abbrev.el' and it is not a
10864directory or a symbolic link.
10865
10866This is how `directory-files-and-attributes' lists that file and its
10867attributes:
10868
10869 ("/usr/local/share/emacs/21.0.100/lisp/abbrev.el"
10870 nil
10871 1
10872 1000
10873 100
10874 (15019 32380)
10875 (14883 48041)
10876 (15214 49336)
10877 11583
10878 "-rw-rw-r--"
10879 t
10880 341385
10881 776)
10882
10883On the other hand, `mail/' is a directory within the `lisp/'
10884directory. The beginning of its listing looks like this:
10885
10886 ("/usr/local/share/emacs/21.0.100/lisp/mail"
10887 t
10888 ...
10889 )
10890
10891(Look at the documentation of `file-attributes' to learn about the
10892different attributes. Bear in mind that the `file-attributes'
10893function does not list the filename, so its first element is
10894`directory-files-and-attributes''s second element.)
10895
10896We will want our new function, `files-in-below-directory', to list
10897the `.el' files in the directory it is told to check, and in any
10898directories below that directory.
10899
10900This gives us a hint on how to construct `files-in-below-directory':
10901within a directory, the function should add `.el' filenames to a
10902list; and if, within a directory, the function comes upon a
10903sub-directory, it should go into that sub-directory and repeat its
10904actions.
10905
10906However, we should note that every directory contains a name that
10907refers to itself, called `.', ("dot") and a name that refers to its
10908parent directory, called `..' ("double dot"). (In `/', the root
10909directory, `..' refers to itself, since `/' has no parent.) Clearly,
10910we do not want our `files-in-below-directory' function to enter those
10911directories, since they always lead us, directly or indirectly, to
10912the current directory.
10913
10914Consequently, our `files-in-below-directory' function must do several
10915tasks:
10916
10917 * Check to see whether it is looking at a filename that ends in
10918 `.el'; and if so, add its name to a list.
10919
10920 * Check to see whether it is looking at a filename that is the
10921 name of a directory; and if so,
10922
10923 - Check to see whether it is looking at `.' or `..'; and if
10924 so skip it.
10925
10926 - Or else, go into that directory and repeat the process.
10927
10928Let's write a function definition to do these tasks. We will use a
10929`while' loop to move from one filename to another within a directory,
10930checking what needs to be done; and we will use a recursive call to
10931repeat the actions on each sub-directory. The recursive pattern is
10932`accumulate' (*note Recursive Pattern: _accumulate_: Accumulate.),
10933using `append' as the combiner.
10934
10935Here is the function:
10936
10937 (defun files-in-below-directory (directory)
10938 "List the .el files in DIRECTORY and in its sub-directories."
10939 ;; Although the function will be used non-interactively,
10940 ;; it will be easier to test if we make it interactive.
10941 ;; The directory will have a name such as
10942 ;; "/usr/local/share/emacs/21.0.100/lisp/"
10943 (interactive "DDirectory name: ")
10944 (let (el-files-list
10945 (current-directory-list
10946 (directory-files-and-attributes directory t)))
10947 ;; while we are in the current directory
10948 (while current-directory-list
10949 (cond
10950 ;; check to see whether filename ends in `.el'
10951 ;; and if so, append its name to a list.
10952 ((equal ".el" (substring (car (car current-directory-list)) -3))
10953 (setq el-files-list
10954 (cons (car (car current-directory-list)) el-files-list)))
10955 ;; check whether filename is that of a directory
10956 ((eq t (car (cdr (car current-directory-list))))
10957 ;; decide whether to skip or recurse
10958 (if
10959 (equal (or "." "..")
10960 (substring (car (car current-directory-list)) -1))
10961 ;; then do nothing if filename is that of
10962 ;; current directory or parent
10963 ()
10964 ;; else descend into the directory and repeat the process
10965 (setq el-files-list
10966 (append
10967 (files-in-below-directory
10968 (car (car current-directory-list)))
10969 el-files-list)))))
10970 ;; move to the next filename in the list; this also
10971 ;; shortens the list so the while loop eventually comes to an end
10972 (setq current-directory-list (cdr current-directory-list)))
10973 ;; return the filenames
10974 el-files-list))
10975
10976The `files-in-below-directory' `directory-files' function takes one
10977argument, the name of a directory.
10978
10979Thus, on my system,
10980
10981 (length
10982 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
10983
10984tells me that my version 21.0.100 Lisp sources directory contains 754
10985`.el' files.
10986
10987`files-in-below-directory' returns a list in reverse alphabetical
10988order. An expression to sort the list in alphabetical order looks
10989like this:
10990
10991 (sort
10992 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
10993 'string-lessp)
10994
10995Counting function definitions
10996-----------------------------
10997
10998Our immediate goal is to generate a list that tells us how many
10999function definitions contain fewer than 10 words and symbols, how many
11000contain between 10 and 19 words and symbols, how many contain between
1100120 and 29 words and symbols, and so on.
11002
11003With a sorted list of numbers, this is easy: count how many elements
11004of the list are smaller than 10, then, after moving past the numbers
11005just counted, count how many are smaller than 20, then, after moving
11006past the numbers just counted, count how many are smaller than 30, and
11007so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
11008larger than the top of that range. We can call the list of such
11009numbers the `top-of-ranges' list.
11010
11011If we wished, we could generate this list automatically, but it is
11012simpler to write a list manually. Here it is:
11013
11014 (defvar top-of-ranges
11015 '(10 20 30 40 50
11016 60 70 80 90 100
11017 110 120 130 140 150
11018 160 170 180 190 200
11019 210 220 230 240 250
11020 260 270 280 290 300)
11021 "List specifying ranges for `defuns-per-range'.")
11022
11023To change the ranges, we edit this list.
11024
11025Next, we need to write the function that creates the list of the
11026number of definitions within each range. Clearly, this function must
11027take the `sorted-lengths' and the `top-of-ranges' lists as arguments.
11028
11029The `defuns-per-range' function must do two things again and again:
11030it must count the number of definitions within a range specified by
11031the current top-of-range value; and it must shift to the next higher
11032value in the `top-of-ranges' list after counting the number of
11033definitions in the current range. Since each of these actions is
11034repetitive, we can use `while' loops for the job. One loop counts
11035the number of definitions in the range defined by the current
11036top-of-range value, and the other loop selects each of the
11037top-of-range values in turn.
11038
11039Several entries of the `sorted-lengths' list are counted for each
11040range; this means that the loop for the `sorted-lengths' list will be
11041inside the loop for the `top-of-ranges' list, like a small gear
11042inside a big gear.
11043
11044The inner loop counts the number of definitions within the range. It
11045is a simple counting loop of the type we have seen before. (*Note A
11046loop with an incrementing counter: Incrementing Loop.) The
11047true-or-false test of the loop tests whether the value from the
11048`sorted-lengths' list is smaller than the current value of the top of
11049the range. If it is, the function increments the counter and tests
11050the next value from the `sorted-lengths' list.
11051
11052The inner loop looks like this:
11053
11054 (while LENGTH-ELEMENT-SMALLER-THAN-TOP-OF-RANGE
11055 (setq number-within-range (1+ number-within-range))
11056 (setq sorted-lengths (cdr sorted-lengths)))
11057
11058The outer loop must start with the lowest value of the
11059`top-of-ranges' list, and then be set to each of the succeeding
11060higher values in turn. This can be done with a loop like this:
11061
11062 (while top-of-ranges
11063 BODY-OF-LOOP...
11064 (setq top-of-ranges (cdr top-of-ranges)))
11065
11066Put together, the two loops look like this:
11067
11068 (while top-of-ranges
11069
11070 ;; Count the number of elements within the current range.
11071 (while LENGTH-ELEMENT-SMALLER-THAN-TOP-OF-RANGE
11072 (setq number-within-range (1+ number-within-range))
11073 (setq sorted-lengths (cdr sorted-lengths)))
11074
11075 ;; Move to next range.
11076 (setq top-of-ranges (cdr top-of-ranges)))
11077
11078In addition, in each circuit of the outer loop, Emacs should record
11079the number of definitions within that range (the value of
11080`number-within-range') in a list. We can use `cons' for this
11081purpose. (*Note `cons': cons.)
11082
11083The `cons' function works fine, except that the list it constructs
11084will contain the number of definitions for the highest range at its
11085beginning and the number of definitions for the lowest range at its
11086end. This is because `cons' attaches new elements of the list to the
11087beginning of the list, and since the two loops are working their way
11088through the lengths' list from the lower end first, the
11089`defuns-per-range-list' will end up largest number first. But we
11090will want to print our graph with smallest values first and the
11091larger later. The solution is to reverse the order of the
11092`defuns-per-range-list'. We can do this using the `nreverse'
11093function, which reverses the order of a list.
11094
11095For example,
11096
11097 (nreverse '(1 2 3 4))
11098
11099produces:
11100
11101 (4 3 2 1)
11102
11103Note that the `nreverse' function is "destructive"--that is, it
11104changes the list to which it is applied; this contrasts with the
11105`car' and `cdr' functions, which are non-destructive. In this case,
11106we do not want the original `defuns-per-range-list', so it does not
11107matter that it is destroyed. (The `reverse' function provides a
11108reversed copy of a list, leaving the original list as is.)
11109
11110Put all together, the `defuns-per-range' looks like this:
11111
11112 (defun defuns-per-range (sorted-lengths top-of-ranges)
11113 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
11114 (let ((top-of-range (car top-of-ranges))
11115 (number-within-range 0)
11116 defuns-per-range-list)
11117
11118 ;; Outer loop.
11119 (while top-of-ranges
11120
11121 ;; Inner loop.
11122 (while (and
11123 ;; Need number for numeric test.
11124 (car sorted-lengths)
11125 (< (car sorted-lengths) top-of-range))
11126
11127 ;; Count number of definitions within current range.
11128 (setq number-within-range (1+ number-within-range))
11129 (setq sorted-lengths (cdr sorted-lengths)))
11130
11131 ;; Exit inner loop but remain within outer loop.
11132
11133 (setq defuns-per-range-list
11134 (cons number-within-range defuns-per-range-list))
11135 (setq number-within-range 0) ; Reset count to zero.
11136
11137 ;; Move to next range.
11138 (setq top-of-ranges (cdr top-of-ranges))
11139 ;; Specify next top of range value.
11140 (setq top-of-range (car top-of-ranges)))
11141
11142 ;; Exit outer loop and count the number of defuns larger than
11143 ;; the largest top-of-range value.
11144 (setq defuns-per-range-list
11145 (cons
11146 (length sorted-lengths)
11147 defuns-per-range-list))
11148
11149 ;; Return a list of the number of definitions within each range,
11150 ;; smallest to largest.
11151 (nreverse defuns-per-range-list)))
11152
11153The function is straightforward except for one subtle feature. The
11154true-or-false test of the inner loop looks like this:
11155
11156 (and (car sorted-lengths)
11157 (< (car sorted-lengths) top-of-range))
11158
11159instead of like this:
11160
11161 (< (car sorted-lengths) top-of-range)
11162
11163The purpose of the test is to determine whether the first item in the
11164`sorted-lengths' list is less than the value of the top of the range.
11165
11166The simple version of the test works fine unless the `sorted-lengths'
11167list has a `nil' value. In that case, the `(car sorted-lengths)'
11168expression function returns `nil'. The `<' function cannot compare a
11169number to `nil', which is an empty list, so Emacs signals an error and
11170stops the function from attempting to continue to execute.
11171
11172The `sorted-lengths' list always becomes `nil' when the counter
11173reaches the end of the list. This means that any attempt to use the
11174`defuns-per-range' function with the simple version of the test will
11175fail.
11176
11177We solve the problem by using the `(car sorted-lengths)' expression
11178in conjunction with the `and' expression. The `(car sorted-lengths)'
11179expression returns a non-`nil' value so long as the list has at least
11180one number within it, but returns `nil' if the list is empty. The
11181`and' expression first evaluates the `(car sorted-lengths)'
11182expression, and if it is `nil', returns false _without_ evaluating the
11183`<' expression. But if the `(car sorted-lengths)' expression returns
11184a non-`nil' value, the `and' expression evaluates the `<' expression,
11185and returns that value as the value of the `and' expression.
11186
11187This way, we avoid an error. *Note forward-paragraph::, for more
11188information about `and'.
11189
11190Here is a short test of the `defuns-per-range' function. First,
11191evaluate the expression that binds (a shortened) `top-of-ranges' list
11192to the list of values, then evaluate the expression for binding the
11193`sorted-lengths' list, and then evaluate the `defuns-per-range'
11194function.
11195
11196 ;; (Shorter list than we will use later.)
11197 (setq top-of-ranges
11198 '(110 120 130 140 150
11199 160 170 180 190 200))
11200
11201 (setq sorted-lengths
11202 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
11203
11204 (defuns-per-range sorted-lengths top-of-ranges)
11205
11206The list returned looks like this:
11207
11208 (2 2 2 0 0 1 0 2 0 0 4)
11209
11210Indeed, there are two elements of the `sorted-lengths' list smaller
11211than 110, two elements between 110 and 119, two elements between 120
11212and 129, and so on. There are four elements with a value of 200 or
11213larger.
11214
11215Readying a Graph
11216****************
11217
11218Our goal is to construct a graph showing the numbers of function
11219definitions of various lengths in the Emacs lisp sources.
11220
11221As a practical matter, if you were creating a graph, you would
11222probably use a program such as `gnuplot' to do the job. (`gnuplot'
11223is nicely integrated into GNU Emacs.) In this case, however, we
11224create one from scratch, and in the process we will re-acquaint
11225ourselves with some of what we learned before and learn more.
11226
11227In this chapter, we will first write a simple graph printing function.
11228This first definition will be a "prototype", a rapidly written
11229function that enables us to reconnoiter this unknown graph-making
11230territory. We will discover dragons, or find that they are myth.
11231After scouting the terrain, we will feel more confident and enhance
11232the function to label the axes automatically.
11233
11234Printing the Columns of a Graph
11235===============================
11236
11237Since Emacs is designed to be flexible and work with all kinds of
11238terminals, including character-only terminals, the graph will need to
11239be made from one of the `typewriter' symbols. An asterisk will do; as
11240we enhance the graph-printing function, we can make the choice of
11241symbol a user option.
11242
11243We can call this function `graph-body-print'; it will take a
11244`numbers-list' as its only argument. At this stage, we will not
11245label the graph, but only print its body.
11246
11247The `graph-body-print' function inserts a vertical column of
11248asterisks for each element in the `numbers-list'. The height of each
11249line is determined by the value of that element of the `numbers-list'.
11250
11251Inserting columns is a repetitive act; that means that this function
11252can be written either with a `while' loop or recursively.
11253
11254Our first challenge is to discover how to print a column of asterisks.
11255Usually, in Emacs, we print characters onto a screen horizontally,
11256line by line, by typing. We have two routes we can follow: write our
11257own column-insertion function or discover whether one exists in Emacs.
11258
11259To see whether there is one in Emacs, we can use the `M-x apropos'
11260command. This command is like the `C-h a' (command-apropos) command,
11261except that the latter finds only those functions that are commands.
11262The `M-x apropos' command lists all symbols that match a regular
11263expression, including functions that are not interactive.
11264
11265What we want to look for is some command that prints or inserts
11266columns. Very likely, the name of the function will contain either
11267the word `print' or the word `insert' or the word `column'.
11268Therefore, we can simply type `M-x apropos RET print\|insert\|column
11269RET' and look at the result. On my system, this command takes quite
11270some time, and then produces a list of 79 functions and variables.
11271Scanning down the list, the only function that looks as if it might
11272do the job is `insert-rectangle'.
11273
11274Indeed, this is the function we want; its documentation says:
11275
11276 insert-rectangle:
11277 Insert text of RECTANGLE with upper left corner at point.
11278 RECTANGLE's first line is inserted at point,
11279 its second line is inserted at a point vertically under point, etc.
11280 RECTANGLE should be a list of strings.
11281
11282We can run a quick test, to make sure it does what we expect of it.
11283
11284Here is the result of placing the cursor after the `insert-rectangle'
11285expression and typing `C-u C-x C-e' (`eval-last-sexp'). The function
11286inserts the strings `"first"', `"second"', and `"third"' at and below
11287point. Also the function returns `nil'.
11288
11289 (insert-rectangle '("first" "second" "third"))first
11290 second
11291 third
11292 nil
11293
11294Of course, we won't be inserting the text of the `insert-rectangle'
11295expression itself into the buffer in which we are making the graph,
11296but will call the function from our program. We shall, however, have
11297to make sure that point is in the buffer at the place where the
11298`insert-rectangle' function will insert its column of strings.
11299
11300If you are reading this in Info, you can see how this works by
11301switching to another buffer, such as the `*scratch*' buffer, placing
11302point somewhere in the buffer, typing `M-:', typing the
11303`insert-rectangle' expression into the minibuffer at the prompt, and
11304then typing <RET>. This causes Emacs to evaluate the expression in
11305the minibuffer, but to use as the value of point the position of
11306point in the `*scratch*' buffer. (`M-:' is the keybinding for
11307`eval-expression'.)
11308
11309We find when we do this that point ends up at the end of the last
11310inserted line--that is to say, this function moves point as a
11311side-effect. If we were to repeat the command, with point at this
11312position, the next insertion would be below and to the right of the
11313previous insertion. We don't want this! If we are going to make a
11314bar graph, the columns need to be beside each other.
11315
11316So we discover that each cycle of the column-inserting `while' loop
11317must reposition point to the place we want it, and that place will be
11318at the top, not the bottom, of the column. Moreover, we remember
11319that when we print a graph, we do not expect all the columns to be
11320the same height. This means that the top of each column may be at a
11321different height from the previous one. We cannot simply reposition
11322point to the same line each time, but moved over to the right--or
11323perhaps we can...
11324
11325We are planning to make the columns of the bar graph out of asterisks.
11326The number of asterisks in the column is the number specified by the
11327current element of the `numbers-list'. We need to construct a list
11328of asterisks of the right length for each call to `insert-rectangle'.
11329If this list consists solely of the requisite number of asterisks,
11330then we will have position point the right number of lines above the
11331base for the graph to print correctly. This could be difficult.
11332
11333Alternatively, if we can figure out some way to pass
11334`insert-rectangle' a list of the same length each time, then we can
11335place point on the same line each time, but move it over one column
11336to the right for each new column. If we do this, however, some of
11337the entries in the list passed to `insert-rectangle' must be blanks
11338rather than asterisks. For example, if the maximum height of the
11339graph is 5, but the height of the column is 3, then
11340`insert-rectangle' requires an argument that looks like this:
11341
11342 (" " " " "*" "*" "*")
11343
11344This last proposal is not so difficult, so long as we can determine
11345the column height. There are two ways for us to specify the column
11346height: we can arbitrarily state what it will be, which would work
11347fine for graphs of that height; or we can search through the list of
11348numbers and use the maximum height of the list as the maximum height
11349of the graph. If the latter operation were difficult, then the former
11350procedure would be easiest, but there is a function built into Emacs
11351that determines the maximum of its arguments. We can use that
11352function. The function is called `max' and it returns the largest of
11353all its arguments, which must be numbers. Thus, for example,
11354
11355 (max 3 4 6 5 7 3)
11356
11357returns 7. (A corresponding function called `min' returns the
11358smallest of all its arguments.)
11359
11360However, we cannot simply call `max' on the `numbers-list'; the `max'
11361function expects numbers as its argument, not a list of numbers.
11362Thus, the following expression,
11363
11364 (max '(3 4 6 5 7 3))
11365
11366produces the following error message;
11367
11368 Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
11369
11370We need a function that passes a list of arguments to a function.
11371This function is `apply'. This function `applies' its first argument
11372(a function) to its remaining arguments, the last of which may be a
11373list.
11374
11375For example,
11376
11377 (apply 'max 3 4 7 3 '(4 8 5))
11378
11379returns 8.
11380
11381(Incidentally, I don't know how you would learn of this function
11382without a book such as this. It is possible to discover other
11383functions, like `search-forward' or `insert-rectangle', by guessing
11384at a part of their names and then using `apropos'. Even though its
11385base in metaphor is clear--`apply' its first argument to the rest--I
11386doubt a novice would come up with that particular word when using
11387`apropos' or other aid. Of course, I could be wrong; after all, the
11388function was first named by someone who had to invent it.)
11389
11390The second and subsequent arguments to `apply' are optional, so we
11391can use `apply' to call a function and pass the elements of a list to
11392it, like this, which also returns 8:
11393
11394 (apply 'max '(4 8 5))
11395
11396This latter way is how we will use `apply'. The
11397`recursive-lengths-list-many-files' function returns a numbers' list
11398to which we can apply `max' (we could also apply `max' to the sorted
11399numbers' list; it does not matter whether the list is sorted or not.)
11400
11401Hence, the operation for finding the maximum height of the graph is
11402this:
11403
11404 (setq max-graph-height (apply 'max numbers-list))
11405
11406Now we can return to the question of how to create a list of strings
11407for a column of the graph. Told the maximum height of the graph and
11408the number of asterisks that should appear in the column, the
11409function should return a list of strings for the `insert-rectangle'
11410command to insert.
11411
11412Each column is made up of asterisks or blanks. Since the function is
11413passed the value of the height of the column and the number of
11414asterisks in the column, the number of blanks can be found by
11415subtracting the number of asterisks from the height of the column.
11416Given the number of blanks and the number of asterisks, two `while'
11417loops can be used to construct the list:
11418
11419 ;;; First version.
11420 (defun column-of-graph (max-graph-height actual-height)
11421 "Return list of strings that is one column of a graph."
11422 (let ((insert-list nil)
11423 (number-of-top-blanks
11424 (- max-graph-height actual-height)))
11425
11426 ;; Fill in asterisks.
11427 (while (> actual-height 0)
11428 (setq insert-list (cons "*" insert-list))
11429 (setq actual-height (1- actual-height)))
11430
11431 ;; Fill in blanks.
11432 (while (> number-of-top-blanks 0)
11433 (setq insert-list (cons " " insert-list))
11434 (setq number-of-top-blanks
11435 (1- number-of-top-blanks)))
11436
11437 ;; Return whole list.
11438 insert-list))
11439
11440If you install this function and then evaluate the following
11441expression you will see that it returns the list as desired:
11442
11443 (column-of-graph 5 3)
11444
11445returns
11446
11447 (" " " " "*" "*" "*")
11448
11449As written, `column-of-graph' contains a major flaw: the symbols used
11450for the blank and for the marked entries in the column are
11451`hard-coded' as a space and asterisk. This is fine for a prototype,
11452but you, or another user, may wish to use other symbols. For example,
11453in testing the graph function, you many want to use a period in place
11454of the space, to make sure the point is being repositioned properly
11455each time the `insert-rectangle' function is called; or you might
11456want to substitute a `+' sign or other symbol for the asterisk. You
11457might even want to make a graph-column that is more than one display
11458column wide. The program should be more flexible. The way to do
11459that is to replace the blank and the asterisk with two variables that
11460we can call `graph-blank' and `graph-symbol' and define those
11461variables separately.
11462
11463Also, the documentation is not well written. These considerations
11464lead us to the second version of the function:
11465
11466 (defvar graph-symbol "*"
11467 "String used as symbol in graph, usually an asterisk.")
11468
11469 (defvar graph-blank " "
11470 "String used as blank in graph, usually a blank space.
11471 graph-blank must be the same number of columns wide
11472 as graph-symbol.")
11473
11474(For an explanation of `defvar', see *Note Initializing a Variable
11475with `defvar': defvar.)
11476
11477 ;;; Second version.
11478 (defun column-of-graph (max-graph-height actual-height)
11479 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
11480 The graph-symbols are contiguous entries at the end
11481 of the list.
11482 The list will be inserted as one column of a graph.
11483 The strings are either graph-blank or graph-symbol."
11484
11485 (let ((insert-list nil)
11486 (number-of-top-blanks
11487 (- max-graph-height actual-height)))
11488
11489 ;; Fill in `graph-symbols'.
11490 (while (> actual-height 0)
11491 (setq insert-list (cons graph-symbol insert-list))
11492 (setq actual-height (1- actual-height)))
11493
11494 ;; Fill in `graph-blanks'.
11495 (while (> number-of-top-blanks 0)
11496 (setq insert-list (cons graph-blank insert-list))
11497 (setq number-of-top-blanks
11498 (1- number-of-top-blanks)))
11499
11500 ;; Return whole list.
11501 insert-list))
11502
11503If we wished, we could rewrite `column-of-graph' a third time to
11504provide optionally for a line graph as well as for a bar graph. This
11505would not be hard to do. One way to think of a line graph is that it
11506is no more than a bar graph in which the part of each bar that is
11507below the top is blank. To construct a column for a line graph, the
11508function first constructs a list of blanks that is one shorter than
11509the value, then it uses `cons' to attach a graph symbol to the list;
11510then it uses `cons' again to attach the `top blanks' to the list.
11511
11512It is easy to see how to write such a function, but since we don't
11513need it, we will not do it. But the job could be done, and if it were
11514done, it would be done with `column-of-graph'. Even more important,
11515it is worth noting that few changes would have to be made anywhere
11516else. The enhancement, if we ever wish to make it, is simple.
11517
11518Now, finally, we come to our first actual graph printing function.
11519This prints the body of a graph, not the labels for the vertical and
11520horizontal axes, so we can call this `graph-body-print'.
11521
11522The `graph-body-print' Function
11523===============================
11524
11525After our preparation in the preceding section, the
11526`graph-body-print' function is straightforward. The function will
11527print column after column of asterisks and blanks, using the elements
11528of a numbers' list to specify the number of asterisks in each column.
11529This is a repetitive act, which means we can use a decrementing
11530`while' loop or recursive function for the job. In this section, we
11531will write the definition using a `while' loop.
11532
11533The `column-of-graph' function requires the height of the graph as an
11534argument, so we should determine and record that as a local variable.
11535
11536This leads us to the following template for the `while' loop version
11537of this function:
11538
11539 (defun graph-body-print (numbers-list)
11540 "DOCUMENTATION..."
11541 (let ((height ...
11542 ...))
11543
11544 (while numbers-list
11545 INSERT-COLUMNS-AND-REPOSITION-POINT
11546 (setq numbers-list (cdr numbers-list)))))
11547
11548We need to fill in the slots of the template.
11549
11550Clearly, we can use the `(apply 'max numbers-list)' expression to
11551determine the height of the graph.
11552
11553The `while' loop will cycle through the `numbers-list' one element at
11554a time. As it is shortened by the `(setq numbers-list (cdr
11555numbers-list))' expression, the CAR of each instance of the list is
11556the value of the argument for `column-of-graph'.
11557
11558At each cycle of the `while' loop, the `insert-rectangle' function
11559inserts the list returned by `column-of-graph'. Since the
11560`insert-rectangle' function moves point to the lower right of the
11561inserted rectangle, we need to save the location of point at the time
11562the rectangle is inserted, move back to that position after the
11563rectangle is inserted, and then move horizontally to the next place
11564from which `insert-rectangle' is called.
11565
11566If the inserted columns are one character wide, as they will be if
11567single blanks and asterisks are used, the repositioning command is
11568simply `(forward-char 1)'; however, the width of a column may be
11569greater than one. This means that the repositioning command should be
11570written `(forward-char symbol-width)'. The `symbol-width' itself is
11571the length of a `graph-blank' and can be found using the expression
11572`(length graph-blank)'. The best place to bind the `symbol-width'
11573variable to the value of the width of graph column is in the varlist
11574of the `let' expression.
11575
11576These considerations lead to the following function definition:
11577
11578 (defun graph-body-print (numbers-list)
11579 "Print a bar graph of the NUMBERS-LIST.
11580 The numbers-list consists of the Y-axis values."
11581
11582 (let ((height (apply 'max numbers-list))
11583 (symbol-width (length graph-blank))
11584 from-position)
11585
11586 (while numbers-list
11587 (setq from-position (point))
11588 (insert-rectangle
11589 (column-of-graph height (car numbers-list)))
11590 (goto-char from-position)
11591 (forward-char symbol-width)
11592 ;; Draw graph column by column.
11593 (sit-for 0)
11594 (setq numbers-list (cdr numbers-list)))
11595 ;; Place point for X axis labels.
11596 (forward-line height)
11597 (insert "\n")
11598 ))
11599
11600The one unexpected expression in this function is the `(sit-for 0)'
11601expression in the `while' loop. This expression makes the graph
11602printing operation more interesting to watch than it would be
11603otherwise. The expression causes Emacs to `sit' or do nothing for a
11604zero length of time and then redraw the screen. Placed here, it
11605causes Emacs to redraw the screen column by column. Without it,
11606Emacs would not redraw the screen until the function exits.
11607
11608We can test `graph-body-print' with a short list of numbers.
11609
11610 1. Install `graph-symbol', `graph-blank', `column-of-graph', which
11611 are in *Note Columns of a graph::, and `graph-body-print'.
11612
11613 2. Copy the following expression:
11614
11615 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
11616
11617 3. Switch to the `*scratch*' buffer and place the cursor where you
11618 want the graph to start.
11619
11620 4. Type `M-:' (`eval-expression').
11621
11622 5. Yank the `graph-body-print' expression into the minibuffer with
11623 `C-y' (`yank)'.
11624
11625 6. Press <RET> to evaluate the `graph-body-print' expression.
11626
11627Emacs will print a graph like this:
11628
11629 *
11630 * **
11631 * ****
11632 *** ****
11633 ********* *
11634 ************
11635 *************
11636
11637The `recursive-graph-body-print' Function
11638=========================================
11639
11640The `graph-body-print' function may also be written recursively. The
11641recursive solution is divided into two parts: an outside `wrapper'
11642that uses a `let' expression to determine the values of several
11643variables that need only be found once, such as the maximum height of
11644the graph, and an inside function that is called recursively to print
11645the graph.
11646
11647The `wrapper' is uncomplicated:
11648
11649 (defun recursive-graph-body-print (numbers-list)
11650 "Print a bar graph of the NUMBERS-LIST.
11651 The numbers-list consists of the Y-axis values."
11652 (let ((height (apply 'max numbers-list))
11653 (symbol-width (length graph-blank))
11654 from-position)
11655 (recursive-graph-body-print-internal
11656 numbers-list
11657 height
11658 symbol-width)))
11659
11660The recursive function is a little more difficult. It has four parts:
11661the `do-again-test', the printing code, the recursive call, and the
11662`next-step-expression'. The `do-again-test' is an `if' expression
11663that determines whether the `numbers-list' contains any remaining
11664elements; if it does, the function prints one column of the graph
11665using the printing code and calls itself again. The function calls
11666itself again according to the value produced by the
11667`next-step-expression' which causes the call to act on a shorter
11668version of the `numbers-list'.
11669
11670 (defun recursive-graph-body-print-internal
11671 (numbers-list height symbol-width)
11672 "Print a bar graph.
11673 Used within recursive-graph-body-print function."
11674
11675 (if numbers-list
11676 (progn
11677 (setq from-position (point))
11678 (insert-rectangle
11679 (column-of-graph height (car numbers-list)))
11680 (goto-char from-position)
11681 (forward-char symbol-width)
11682 (sit-for 0) ; Draw graph column by column.
11683 (recursive-graph-body-print-internal
11684 (cdr numbers-list) height symbol-width))))
11685
11686After installation, this expression can be tested; here is a sample:
11687
11688 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
11689
11690Here is what `recursive-graph-body-print' produces:
11691
11692 *
11693 ** *
11694 **** *
11695 **** ***
11696 * *********
11697 ************
11698 *************
11699
11700Either of these two functions, `graph-body-print' or
11701`recursive-graph-body-print', create the body of a graph.
11702
11703Need for Printed Axes
11704=====================
11705
11706A graph needs printed axes, so you can orient yourself. For a do-once
11707project, it may be reasonable to draw the axes by hand using Emacs'
11708Picture mode; but a graph drawing function may be used more than once.
11709
11710For this reason, I have written enhancements to the basic
11711`print-graph-body' function that automatically print labels for the
11712horizontal and vertical axes. Since the label printing functions do
11713not contain much new material, I have placed their description in an
11714appendix. *Note A Graph with Labelled Axes: Full Graph.
11715
11716Exercise
11717========
11718
11719Write a line graph version of the graph printing functions.
11720
11721Your `.emacs' File
11722******************
11723
11724"You don't have to like Emacs to like it" - this seemingly
11725paradoxical statement is the secret of GNU Emacs. The plain, `out of
11726the box' Emacs is a generic tool. Most people who use it, customize
11727it to suit themselves.
11728
11729GNU Emacs is mostly written in Emacs Lisp; this means that by writing
11730expressions in Emacs Lisp you can change or extend Emacs.
11731
11732Emacs' Default Configuration
11733============================
11734
11735There are those who appreciate Emacs' default configuration. After
11736all, Emacs starts you in C mode when you edit a C file, starts you in
11737Fortran mode when you edit a Fortran file, and starts you in
11738Fundamental mode when you edit an unadorned file. This all makes
11739sense, if you do not know who is going to use Emacs. Who knows what a
11740person hopes to do with an unadorned file? Fundamental mode is the
11741right default for such a file, just as C mode is the right default for
11742editing C code. But when you do know who is going to use Emacs--you,
11743yourself--then it makes sense to customize Emacs.
11744
11745For example, I seldom want Fundamental mode when I edit an otherwise
11746undistinguished file; I want Text mode. This is why I customize
11747Emacs: so it suits me.
11748
11749You can customize and extend Emacs by writing or adapting a
11750`~/.emacs' file. This is your personal initialization file; its
11751contents, written in Emacs Lisp, tell Emacs what to do.(1)
11752
11753A `~/.emacs' file contains Emacs Lisp code. You can write this code
11754yourself; or you can use Emacs' `customize' feature to write the code
11755for you. You can combine your own expressions and auto-written
11756Customize expressions in your `.emacs' file.
11757
11758(I myself prefer to write my own expressions, except for those,
11759particularly fonts, that I find easier to manipulate using the
11760`customize' command. I combine the two methods.)
11761
11762Most of this chapter is about writing expressions yourself. It
11763describes a simple `.emacs' file; for more information, see *Note The
11764Init File: (emacs)Init File, and *Note The Init File: (elisp)Init
11765File.
11766
11767---------- Footnotes ----------
11768
11769(1) You may also add `.el' to `~/.emacs' and call it a `~/.emacs.el'
11770file. In the past, you were forbidden to type the extra keystrokes
11771that the name `~/.emacs.el' requires, but now you may. The new
11772format is consistent with the Emacs Lisp file naming conventions; the
11773old format saves typing.
11774
11775Site-wide Initialization Files
11776==============================
11777
11778In addition to your personal initialization file, Emacs automatically
11779loads various site-wide initialization files, if they exist. These
11780have the same form as your `.emacs' file, but are loaded by everyone.
11781
11782Two site-wide initialization files, `site-load.el' and
11783`site-init.el', are loaded into Emacs and then `dumped' if a `dumped'
11784version of Emacs is created, as is most common. (Dumped copies of
11785Emacs load more quickly. However, once a file is loaded and dumped,
11786a change to it does not lead to a change in Emacs unless you load it
11787yourself or re-dump Emacs. *Note Building Emacs: (elisp)Building
11788Emacs, and the `INSTALL' file.)
11789
11790Three other site-wide initialization files are loaded automatically
11791each time you start Emacs, if they exist. These are `site-start.el',
11792which is loaded _before_ your `.emacs' file, and `default.el', and
11793the terminal type file, which are both loaded _after_ your `.emacs'
11794file.
11795
11796Settings and definitions in your `.emacs' file will overwrite
11797conflicting settings and definitions in a `site-start.el' file, if it
11798exists; but the settings and definitions in a `default.el' or
11799terminal type file will overwrite those in your `.emacs' file. (You
11800can prevent interference from a terminal type file by setting
11801`term-file-prefix' to `nil'. *Note A Simple Extension: Simple
11802Extension.)
11803
11804The `INSTALL' file that comes in the distribution contains
11805descriptions of the `site-init.el' and `site-load.el' files.
11806
11807The `loadup.el', `startup.el', and `loaddefs.el' files control
11808loading. These files are in the `lisp' directory of the Emacs
11809distribution and are worth perusing.
11810
11811The `loaddefs.el' file contains a good many suggestions as to what to
11812put into your own `.emacs' file, or into a site-wide initialization
11813file.
11814
11815Specifying Variables using `defcustom'
11816======================================
11817
11818You can specify variables using `defcustom' so that you and others
11819can then use Emacs' `customize' feature to set their values. (You
11820cannot use `customize' to write function definitions; but you can
11821write `defuns' in your `.emacs' file. Indeed, you can write any Lisp
11822expression in your `.emacs' file.)
11823
11824The `customize' feature depends on the `defcustom' special form.
11825Although you can use `defvar' or `setq' for variables that users set,
11826the `defcustom' special form is designed for the job.
11827
11828You can use your knowledge of `defvar' for writing the first three
11829arguments for `defcustom'. The first argument to `defcustom' is the
11830name of the variable. The second argument is the variable's initial
11831value, if any; and this value is set only if the value has not
11832already been set. The third argument is the documentation.
11833
11834The fourth and subsequent arguments to `defcustom' specify types and
11835options; these are not featured in `defvar'. (These arguments are
11836optional.)
11837
11838Each of these arguments consists of a keyword followed by a value.
11839Each keyword starts with the character `:'.
11840
11841For example, the customizable user option variable `text-mode-hook'
11842looks like this:
11843
11844 (defcustom text-mode-hook nil
11845 "Normal hook run when entering Text mode and many related modes."
11846 :type 'hook
11847 :options '(turn-on-auto-fill flyspell-mode)
11848 :group 'data)
11849
11850The name of the variable is `text-mode-hook'; it has no default
11851value; and its documentation string tells you what it does.
11852
11853The `:type' keyword tells Emacs what kind of data `text-mode-hook'
11854should be set to and how to display the value in a Customization
11855buffer.
11856
11857The `:options' keyword specifies a suggested list of values for the
11858variable. Currently, you can use `:options' only for a hook. The
11859list is only a suggestion; it is not exclusive; a person who sets the
11860variable may set it to other values; the list shown following the
11861`:options' keyword is intended to offer convenient choices to a user.
11862
11863Finally, the `:group' keyword tells the Emacs Customization command
11864in which group the variable is located. This tells where to find it.
11865
11866For more information, see *Note Writing Customization Definitions:
11867(elisp)Customization.
11868
11869Consider `text-mode-hook' as an example.
11870
11871There are two ways to customize this variable. You can use the
11872customization command or write the appropriate expressions yourself.
11873
11874Using the customization command, you can type:
11875
11876 M-x customize
11877
11878and find that the group for editing files of data is called `data'.
11879Enter that group. Text Mode Hook is the first member. You can click
11880on its various options to set the values. After you click on the
11881button to
11882
11883 Save for Future Sessions
11884
11885Emacs will write an expression into your `.emacs' file. It will look
11886like this:
11887
11888 (custom-set-variables
11889 ;; custom-set-variables was added by Custom --
11890 ;; don't edit or cut/paste it!
11891 ;; Your init file should contain only one such instance.
11892 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
11893
11894(The `text-mode-hook-identify' function tells
11895`toggle-text-mode-auto-fill' which buffers are in Text mode.)
11896
11897In spite of the warning, you certainly may edit, cut, and paste the
11898expression! I do all time. The purpose of the warning is to scare
11899those who do not know what they are doing, so they do not
11900inadvertently generate an error.
11901
11902The `custom-set-variables' works somewhat differently than a `setq'.
11903While I have never learned the differences, I do modify the
11904`custom-set-variables' expressions in my `.emacs' file by hand: I
11905make the changes in what appears to me to be a reasonable manner and
11906have not had any problems. Others prefer to use the Customization
11907command and let Emacs do the work for them.
11908
11909Another `custom-set-...' function is `custom-set-faces'. This
11910function sets the various font faces. Over time, I have set a
11911considerable number of faces. Some of the time, I re-set them using
11912`customize'; other times, I simply edit the `custom-set-faces'
11913expression in my `.emacs' file itself.
11914
11915The second way to customize your `text-mode-hook' is to set it
11916yourself in your `.emacs' file using code that has nothing to do with
11917the `custom-set-...' functions.
11918
11919When you do this, and later use `customize', you will see a message
11920that says
11921
11922 this option has been changed outside the customize buffer.
11923
11924This message is only a warning. If you click on the button to
11925
11926 Save for Future Sessions
11927
11928Emacs will write a `custom-set-...' expression near the end of your
11929`.emacs' file that will be evaluated after your hand-written
11930expression. It will, therefore, overrule your hand-written
11931expression. No harm will be done. When you do this, however, be
11932careful to remember which expression is active; if you forget, you
11933may confuse yourself.
11934
11935So long as you remember where the values are set, you will have no
11936trouble. In any event, the values are always set in your
11937initialization file, which is usually called `.emacs'.
11938
11939I myself use `customize' for hardly anything. Mostly, I write
11940expressions myself.
11941
11942Beginning a `.emacs' File
11943=========================
11944
11945When you start Emacs, it loads your `.emacs' file unless you tell it
11946not to by specifying `-q' on the command line. (The `emacs -q'
11947command gives you a plain, out-of-the-box Emacs.)
11948
11949A `.emacs' file contains Lisp expressions. Often, these are no more
11950than expressions to set values; sometimes they are function
11951definitions.
11952
11953*Note The Init File `~/.emacs': (emacs)Init File, for a short
11954description of initialization files.
11955
11956This chapter goes over some of the same ground, but is a walk among
11957extracts from a complete, long-used `.emacs' file--my own.
11958
11959The first part of the file consists of comments: reminders to myself.
11960By now, of course, I remember these things, but when I started, I did
11961not.
11962
11963 ;;;; Bob's .emacs file
11964 ; Robert J. Chassell
11965 ; 26 September 1985
11966
11967Look at that date! I started this file a long time ago. I have been
11968adding to it ever since.
11969
11970 ; Each section in this file is introduced by a
11971 ; line beginning with four semicolons; and each
11972 ; entry is introduced by a line beginning with
11973 ; three semicolons.
11974
11975This describes the usual conventions for comments in Emacs Lisp.
11976Everything on a line that follows a semicolon is a comment. Two,
11977three, and four semicolons are used as section and subsection
11978markers. (*Note Comments: (elisp)Comments, for more about comments.)
11979
11980 ;;;; The Help Key
11981 ; Control-h is the help key;
11982 ; after typing control-h, type a letter to
11983 ; indicate the subject about which you want help.
11984 ; For an explanation of the help facility,
11985 ; type control-h two times in a row.
11986
11987Just remember: type `C-h' two times for help.
11988
11989 ; To find out about any mode, type control-h m
11990 ; while in that mode. For example, to find out
11991 ; about mail mode, enter mail mode and then type
11992 ; control-h m.
11993
11994`Mode help', as I call this, is very helpful. Usually, it tells you
11995all you need to know.
11996
11997Of course, you don't need to include comments like these in your
11998`.emacs' file. I included them in mine because I kept forgetting
11999about Mode help or the conventions for comments--but I was able to
12000remember to look here to remind myself.
12001
12002Text and Auto Fill Mode
12003=======================
12004
12005Now we come to the part that `turns on' Text mode and Auto Fill mode.
12006
12007 ;;; Text mode and Auto Fill mode
12008 ; The next three lines put Emacs into Text mode
12009 ; and Auto Fill mode, and are for writers who
12010 ; want to start writing prose rather than code.
12011
12012 (setq default-major-mode 'text-mode)
12013 (add-hook 'text-mode-hook 'text-mode-hook-identify)
12014 (add-hook 'text-mode-hook 'turn-on-auto-fill)
12015
12016Here is the first part of this `.emacs' file that does something
12017besides remind a forgetful human!
12018
12019The first of the two lines in parentheses tells Emacs to turn on Text
12020mode when you find a file, _unless_ that file should go into some
12021other mode, such as C mode.
12022
12023When Emacs reads a file, it looks at the extension to the file name,
12024if any. (The extension is the part that comes after a `.'.) If the
12025file ends with a `.c' or `.h' extension then Emacs turns on C mode.
12026Also, Emacs looks at first nonblank line of the file; if the line
12027says `-*- C -*-', Emacs turns on C mode. Emacs possesses a list of
12028extensions and specifications that it uses automatically. In
12029addition, Emacs looks near the last page for a per-buffer, "local
12030variables list", if any.
12031
12032*Note How Major Modes are Chosen: (emacs)Choosing Modes.
12033
12034*Note Local Variables in Files: (emacs)File Variables.
12035
12036Now, back to the `.emacs' file.
12037
12038Here is the line again; how does it work?
12039
12040 (setq default-major-mode 'text-mode)
12041
12042This line is a short, but complete Emacs Lisp expression.
12043
12044We are already familiar with `setq'. It sets the following variable,
12045`default-major-mode', to the subsequent value, which is `text-mode'.
12046The single quote mark before `text-mode' tells Emacs to deal directly
12047with the `text-mode' variable, not with whatever it might stand for.
12048*Note Setting the Value of a Variable: set & setq, for a reminder of
12049how `setq' works. The main point is that there is no difference
12050between the procedure you use to set a value in your `.emacs' file
12051and the procedure you use anywhere else in Emacs.
12052
12053Here are the next two lines:
12054
12055 (add-hook 'text-mode-hook 'text-mode-hook-identify)
12056 (add-hook 'text-mode-hook 'turn-on-auto-fill)
12057
12058In these two lines, the `add-hook' command first adds
12059`text-mode-hook-identify' to the variable called `text-mode-hook' and
12060then adds `turn-on-auto-fill' to the variable.
12061
12062`turn-on-auto-fill' is the name of a program, that, you guessed it!,
12063turns on Auto Fill mode. `text-mode-hook-identify' is a function
12064that tells `toggle-text-mode-auto-fill' which buffers are in Text
12065mode.
12066
12067Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
12068onto Text mode. So every time Emacs turns on Text mode, Emacs also
12069turns on Auto Fill mode.
12070
12071In brief, the first line causes Emacs to enter Text mode when you edit
12072a file, unless the file name extension, first non-blank line, or local
12073variables tell Emacs otherwise.
12074
12075Text mode among other actions, sets the syntax table to work
12076conveniently for writers. In Text mode, Emacs considers an apostrophe
12077as part of a word like a letter; but Emacs does not consider a period
12078or a space as part of a word. Thus, `M-f' moves you over `it's'. On
12079the other hand, in C mode, `M-f' stops just after the `t' of `it's'.
12080
12081The second and third lines causes Emacs to turn on Auto Fill mode when
12082it turns on Text mode. In Auto Fill mode, Emacs automatically breaks
12083a line that is too wide and brings the excessively wide part of the
12084line down to the next line. Emacs breaks lines between words, not
12085within them.
12086
12087When Auto Fill mode is turned off, lines continue to the right as you
12088type them. Depending on how you set the value of `truncate-lines',
12089the words you type either disappear off the right side of the screen,
12090or else are shown, in a rather ugly and unreadable manner, as a
12091continuation line on the screen.
12092
12093In addition, in this part of my `.emacs' file, I tell the Emacs fill
12094commands to insert two spaces after a colon:
12095
12096 (setq colon-double-space t)
12097
12098Mail Aliases
12099============
12100
12101Here is a `setq' that `turns on' mail aliases, along with more
12102reminders.
12103
12104 ;;; Mail mode
12105 ; To enter mail mode, type `C-x m'
12106 ; To enter RMAIL (for reading mail),
12107 ; type `M-x rmail'
12108
12109 (setq mail-aliases t)
12110
12111This `setq' command sets the value of the variable `mail-aliases' to
12112`t'. Since `t' means true, the line says, in effect, "Yes, use mail
12113aliases."
12114
12115Mail aliases are convenient short names for long email addresses or
12116for lists of email addresses. The file where you keep your `aliases'
12117is `~/.mailrc'. You write an alias like this:
12118
12119 alias geo george@foobar.wiz.edu
12120
12121When you write a message to George, address it to `geo'; the mailer
12122will automatically expand `geo' to the full address.
12123
12124Indent Tabs Mode
12125================
12126
12127By default, Emacs inserts tabs in place of multiple spaces when it
12128formats a region. (For example, you might indent many lines of text
12129all at once with the `indent-region' command.) Tabs look fine on a
12130terminal or with ordinary printing, but they produce badly indented
12131output when you use TeX or Texinfo since TeX ignores tabs.
12132
12133The following turns off Indent Tabs mode:
12134
12135 ;;; Prevent Extraneous Tabs
12136 (setq-default indent-tabs-mode nil)
12137
12138Note that this line uses `setq-default' rather than the `setq'
12139command that we have seen before. The `setq-default' command sets
12140values only in buffers that do not have their own local values for
12141the variable.
12142
12143*Note Tabs vs. Spaces: (emacs)Just Spaces.
12144
12145*Note Local Variables in Files: (emacs)File Variables.
12146
12147Some Keybindings
12148================
12149
12150Now for some personal keybindings:
12151
12152 ;;; Compare windows
12153 (global-set-key "\C-cw" 'compare-windows)
12154
12155`compare-windows' is a nifty command that compares the text in your
12156current window with text in the next window. It makes the comparison
12157by starting at point in each window, moving over text in each window
12158as far as they match. I use this command all the time.
12159
12160This also shows how to set a key globally, for all modes.
12161
12162The command is `global-set-key'. It is followed by the keybinding.
12163In a `.emacs' file, the keybinding is written as shown: `\C-c' stands
12164for `control-c', which means `press the control key and the `c' key
12165at the same time'. The `w' means `press the `w' key'. The
12166keybinding is surrounded by double quotation marks. In
12167documentation, you would write this as `C-c w'. (If you were binding
12168a <META> key, such as `M-c', rather than a <CTL> key, you would write
12169`\M-c'. *Note Rebinding Keys in Your Init File: (emacs)Init
12170Rebinding, for details.)
12171
12172The command invoked by the keys is `compare-windows'. Note that
12173`compare-windows' is preceded by a single quote; otherwise, Emacs
12174would first try to evaluate the symbol to determine its value.
12175
12176These three things, the double quotation marks, the backslash before
12177the `C', and the single quote mark are necessary parts of keybinding
12178that I tend to forget. Fortunately, I have come to remember that I
12179should look at my existing `.emacs' file, and adapt what is there.
12180
12181As for the keybinding itself: `C-c w'. This combines the prefix key,
12182`C-c', with a single character, in this case, `w'. This set of keys,
12183`C-c' followed by a single character, is strictly reserved for
12184individuals' own use. (I call these `own' keys, since these are for
12185my own use.) You should always be able to create such a keybinding
12186for your own use without stomping on someone else's keybinding. If
12187you ever write an extension to Emacs, please avoid taking any of
12188these keys for public use. Create a key like `C-c C-w' instead.
12189Otherwise, we will run out of `own' keys.
12190
12191Here is another keybinding, with a comment:
12192
12193 ;;; Keybinding for `occur'
12194 ; I use occur a lot, so let's bind it to a key:
12195 (global-set-key "\C-co" 'occur)
12196
12197The `occur' command shows all the lines in the current buffer that
12198contain a match for a regular expression. Matching lines are shown
12199in a buffer called `*Occur*'. That buffer serves as a menu to jump
12200to occurrences.
12201
12202Here is how to unbind a key, so it does not work:
12203
12204 ;;; Unbind `C-x f'
12205 (global-unset-key "\C-xf")
12206
12207There is a reason for this unbinding: I found I inadvertently typed
12208`C-x f' when I meant to type `C-x C-f'. Rather than find a file, as
12209I intended, I accidentally set the width for filled text, almost
12210always to a width I did not want. Since I hardly ever reset my
12211default width, I simply unbound the key.
12212
12213The following rebinds an existing key:
12214
12215 ;;; Rebind `C-x C-b' for `buffer-menu'
12216 (global-set-key "\C-x\C-b" 'buffer-menu)
12217
12218By default, `C-x C-b' runs the `list-buffers' command. This command
12219lists your buffers in _another_ window. Since I almost always want
12220to do something in that window, I prefer the `buffer-menu' command,
12221which not only lists the buffers, but moves point into that window.
12222
12223Keymaps
12224=======
12225
12226Emacs uses "keymaps" to record which keys call which commands. When
12227you use `global-set-key' to set the keybinding for a single command
12228in all parts of Emacs, you are specifying the keybinding in
12229`current-global-map'.
12230
12231Specific modes, such as C mode or Text mode, have their own keymaps;
12232the mode-specific keymaps override the global map that is shared by
12233all buffers.
12234
12235The `global-set-key' function binds, or rebinds, the global keymap.
12236For example, the following binds the key `C-x C-b' to the function
12237`buffer-menu':
12238
12239 (global-set-key "\C-x\C-b" 'buffer-menu)
12240
12241Mode-specific keymaps are bound using the `define-key' function,
12242which takes a specific keymap as an argument, as well as the key and
12243the command. For example, my `.emacs' file contains the following
12244expression to bind the `texinfo-insert-@group' command to `C-c C-c g':
12245
12246 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@group)
12247
12248The `texinfo-insert-@group' function itself is a little extension to
12249Texinfo mode that inserts `@group' into a Texinfo file. I use this
12250command all the time and prefer to type the three strokes `C-c C-c g'
12251rather than the six strokes `@ g r o u p'. (`@group' and its
12252matching `@end group' are commands that keep all enclosed text
12253together on one page; many multi-line examples in this book are
12254surrounded by `@group ... @end group'.)
12255
12256Here is the `texinfo-insert-@group' function definition:
12257
12258 (defun texinfo-insert-@group ()
12259 "Insert the string @group in a Texinfo buffer."
12260 (interactive)
12261 (beginning-of-line)
12262 (insert "@group\n"))
12263
12264(Of course, I could have used Abbrev mode to save typing, rather than
12265write a function to insert a word; but I prefer key strokes consistent
12266with other Texinfo mode key bindings.)
12267
12268You will see numerous `define-key' expressions in `loaddefs.el' as
12269well as in the various mode libraries, such as `cc-mode.el' and
12270`lisp-mode.el'.
12271
12272*Note Customizing Key Bindings: (emacs)Key Bindings, and *Note
12273Keymaps: (elisp)Keymaps, for more information about keymaps.
12274
12275Loading Files
12276=============
12277
12278Many people in the GNU Emacs community have written extensions to
12279Emacs. As time goes by, these extensions are often included in new
12280releases. For example, the Calendar and Diary packages are now part
12281of the standard GNU Emacs.
12282
12283(Calc, which I consider a vital part of Emacs, would be part of the
12284standard distribution except that it was so large it was packaged
12285separately and no one has changed that.)
12286
12287You can use a `load' command to evaluate a complete file and thereby
12288install all the functions and variables in the file into Emacs. For
12289example:
12290
12291 (load "~/emacs/slowsplit")
12292
12293This evaluates, i.e. loads, the `slowsplit.el' file or if it exists,
12294the faster, byte compiled `slowsplit.elc' file from the `emacs'
12295sub-directory of your home directory. The file contains the function
12296`split-window-quietly', which John Robinson wrote in 1989.
12297
12298The `split-window-quietly' function splits a window with the minimum
12299of redisplay. I installed it in 1989 because it worked well with the
12300slow 1200 baud terminals I was then using. Nowadays, I only
12301occasionally come across such a slow connection, but I continue to use
12302the function because I like the way it leaves the bottom half of a
12303buffer in the lower of the new windows and the top half in the upper
12304window.
12305
12306To replace the key binding for the default `split-window-vertically',
12307you must also unset that key and bind the keys to
12308`split-window-quietly', like this:
12309
12310 (global-unset-key "\C-x2")
12311 (global-set-key "\C-x2" 'split-window-quietly)
12312
12313If you load many extensions, as I do, then instead of specifying the
12314exact location of the extension file, as shown above, you can specify
12315that directory as part of Emacs' `load-path'. Then, when Emacs loads
12316a file, it will search that directory as well as its default list of
12317directories. (The default list is specified in `paths.h' when Emacs
12318is built.)
12319
12320The following command adds your `~/emacs' directory to the existing
12321load path:
12322
12323 ;;; Emacs Load Path
12324 (setq load-path (cons "~/emacs" load-path))
12325
12326Incidentally, `load-library' is an interactive interface to the
12327`load' function. The complete function looks like this:
12328
12329 (defun load-library (library)
12330 "Load the library named LIBRARY.
12331 This is an interface to the function `load'."
12332 (interactive "sLoad library: ")
12333 (load library))
12334
12335The name of the function, `load-library', comes from the use of
12336`library' as a conventional synonym for `file'. The source for the
12337`load-library' command is in the `files.el' library.
12338
12339Another interactive command that does a slightly different job is
12340`load-file'. *Note Libraries of Lisp Code for Emacs: (emacs)Lisp
12341Libraries, for information on the distinction between `load-library'
12342and this command.
12343
12344Autoloading
12345===========
12346
12347Instead of installing a function by loading the file that contains it,
12348or by evaluating the function definition, you can make the function
12349available but not actually install it until it is first called. This
12350is called "autoloading".
12351
12352When you execute an autoloaded function, Emacs automatically evaluates
12353the file that contains the definition, and then calls the function.
12354
12355Emacs starts quicker with autoloaded functions, since their libraries
12356are not loaded right away; but you need to wait a moment when you
12357first use such a function, while its containing file is evaluated.
12358
12359Rarely used functions are frequently autoloaded. The `loaddefs.el'
12360library contains hundreds of autoloaded functions, from
12361`bookmark-set' to `wordstar-mode'. Of course, you may come to use a
12362`rare' function frequently. When you do, you should load that
12363function's file with a `load' expression in your `.emacs' file.
12364
12365In my `.emacs' file for Emacs version 21, I load 12 libraries that
12366contain functions that would otherwise be autoloaded. (Actually, it
12367would have been better to include these files in my `dumped' Emacs
12368when I built it, but I forgot. *Note Building Emacs: (elisp)Building
12369Emacs, and the `INSTALL' file for more about dumping.)
12370
12371You may also want to include autoloaded expressions in your `.emacs'
12372file. `autoload' is a built-in function that takes up to five
12373arguments, the final three of which are optional. The first argument
12374is the name of the function to be autoloaded; the second is the name
12375of the file to be loaded. The third argument is documentation for the
12376function, and the fourth tells whether the function can be called
12377interactively. The fifth argument tells what type of
12378object--`autoload' can handle a keymap or macro as well as a function
12379(the default is a function).
12380
12381Here is a typical example:
12382
12383 (autoload 'html-helper-mode
12384 "html-helper-mode" "Edit HTML documents" t)
12385
12386(`html-helper-mode' is an alternative to `html-mode', which is a
12387standard part of the distribution).
12388
12389This expression autoloads the `html-helper-mode' function. It takes
12390it from the `html-helper-mode.el' file (or from the byte compiled
12391file `html-helper-mode.elc', if it exists.) The file must be located
12392in a directory specified by `load-path'. The documentation says that
12393this is a mode to help you edit documents written in the HyperText
12394Markup Language. You can call this mode interactively by typing `M-x
12395html-helper-mode'. (You need to duplicate the function's regular
12396documentation in the autoload expression because the regular function
12397is not yet loaded, so its documentation is not available.)
12398
12399*Note Autoload: (elisp)Autoload, for more information.
12400
12401A Simple Extension: `line-to-top-of-window'
12402===========================================
12403
12404Here is a simple extension to Emacs that moves the line point is on to
12405the top of the window. I use this all the time, to make text easier
12406to read.
12407
12408You can put the following code into a separate file and then load it
12409from your `.emacs' file, or you can include it within your `.emacs'
12410file.
12411
12412Here is the definition:
12413
12414 ;;; Line to top of window;
12415 ;;; replace three keystroke sequence C-u 0 C-l
12416 (defun line-to-top-of-window ()
12417 "Move the line point is on to top of window."
12418 (interactive)
12419 (recenter 0))
12420
12421Now for the keybinding.
12422
12423Nowadays, function keys as well as mouse button events and non-ASCII
12424characters are written within square brackets, without quotation
12425marks. (In Emacs version 18 and before, you had to write different
12426function key bindings for each different make of terminal.)
12427
12428I bind `line-to-top-of-window' to my <F6> function key like this:
12429
12430 (global-set-key [f6] 'line-to-top-of-window)
12431
12432For more information, see *Note Rebinding Keys in Your Init File:
12433(emacs)Init Rebinding.
12434
12435If you run two versions of GNU Emacs, such as versions 20 and 21, and
12436use one `.emacs' file, you can select which code to evaluate with the
12437following conditional:
12438
12439 (cond
12440 ((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
12441 ;; evaluate version 20 code
12442 ( ... ))
12443 ((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
12444 ;; evaluate version 21 code
12445 ( ... )))
12446
12447For example, in contrast to version 20, version 21 blinks its cursor
12448by default. I hate such blinking, as well as some other features in
12449version 21, so I placed the following in my `.emacs' file(1):
12450
12451 (if (string-equal "21" (substring (emacs-version) 10 12))
12452 (progn
12453 (blink-cursor-mode 0)
12454 ;; Insert newline when you press `C-n' (next-line)
12455 ;; at the end of the buffer
12456 (setq next-line-add-newlines t)
12457 ;; Turn on image viewing
12458 (auto-image-file-mode t)
12459 ;; Turn on menu bar (this bar has text)
12460 ;; (Use numeric argument to turn on)
12461 (menu-bar-mode 1)
12462 ;; Turn off tool bar (this bar has icons)
12463 ;; (Use numeric argument to turn on)
12464 (tool-bar-mode nil)
12465 ;; Turn off tooltip mode for tool bar
12466 ;; (This mode causes icon explanations to pop up)
12467 ;; (Use numeric argument to turn on)
12468 (tooltip-mode nil)
12469 ;; If tooltips turned on, make tips appear promptly
12470 (setq tooltip-delay 0.1) ; default is one second
12471 ))
12472
12473(You will note that instead of typing `(number-to-string 21)', I
12474decided to save typing and wrote `21' as a string, `"21"', rather
12475than convert it from an integer to a string. In this instance, this
12476expression is better than the longer, but more general
12477`(number-to-string 21)'. However, if you do not know ahead of time
12478what type of information will be returned, then the
12479`number-to-string' function will be needed.)
12480
12481---------- Footnotes ----------
12482
12483(1) When I start instances of Emacs that do not load my `.emacs' file
12484or any site file, I also turn off blinking:
12485
12486 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
12487
12488X11 Colors
12489==========
12490
12491You can specify colors when you use Emacs with the MIT X Windowing
12492system.
12493
12494I dislike the default colors and specify my own.
12495
12496Here are the expressions in my `.emacs' file that set values:
12497
12498 ;; Set cursor color
12499 (set-cursor-color "white")
12500
12501 ;; Set mouse color
12502 (set-mouse-color "white")
12503
12504 ;; Set foreground and background
12505 (set-foreground-color "white")
12506 (set-background-color "darkblue")
12507
12508 ;;; Set highlighting colors for isearch and drag
12509 (set-face-foreground 'highlight "white")
12510 (set-face-background 'highlight "blue")
12511
12512 (set-face-foreground 'region "cyan")
12513 (set-face-background 'region "blue")
12514
12515 (set-face-foreground 'secondary-selection "skyblue")
12516 (set-face-background 'secondary-selection "darkblue")
12517
12518 ;; Set calendar highlighting colors
12519 (setq calendar-load-hook
12520 '(lambda ()
12521 (set-face-foreground 'diary-face "skyblue")
12522 (set-face-background 'holiday-face "slate blue")
12523 (set-face-foreground 'holiday-face "white")))
12524
12525The various shades of blue soothe my eye and prevent me from seeing
12526the screen flicker.
12527
12528Alternatively, I could have set my specifications in various X
12529initialization files. For example, I could set the foreground,
12530background, cursor, and pointer (i.e., mouse) colors in my
12531`~/.Xresources' file like this:
12532
12533 Emacs*foreground: white
12534 Emacs*background: darkblue
12535 Emacs*cursorColor: white
12536 Emacs*pointerColor: white
12537
12538In any event, since it is not part of Emacs, I set the root color of
12539my X window in my `~/.xinitrc' file, like this(1):
12540
12541 # I use TWM for window manager.
12542 xsetroot -solid Navy -fg white &
12543
12544---------- Footnotes ----------
12545
12546(1) I occasionally run more modern window managers, such as Sawfish
12547with GNOME, Enlightenment, SCWM, or KDE; in those cases, I often
12548specify an image rather than a plain color.
12549
12550Miscellaneous Settings for a `.emacs' File
12551==========================================
12552
12553Here are a few miscellaneous settings:
12554
12555 - Set the shape and color of the mouse cursor:
12556 ; Cursor shapes are defined in
12557 ; `/usr/include/X11/cursorfont.h';
12558 ; for example, the `target' cursor is number 128;
12559 ; the `top_left_arrow' cursor is number 132.
12560
12561 (let ((mpointer (x-get-resource "*mpointer"
12562 "*emacs*mpointer")))
12563 ;; If you have not set your mouse pointer
12564 ;; then set it, otherwise leave as is:
12565 (if (eq mpointer nil)
12566 (setq mpointer "132")) ; top_left_arrow
12567 (setq x-pointer-shape (string-to-int mpointer))
12568 (set-mouse-color "white"))
12569
12570A Modified Mode Line
12571====================
12572
12573Finally, a feature I really like: a modified mode line.
12574
12575When I work over a network, I forget which machine I am using. Also,
12576I tend to I lose track of where I am, and which line point is on.
12577
12578So I reset my mode line to look like this:
12579
12580 -:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
12581
12582I am visiting a file called `foo.texi', on my machine `rattlesnake'
12583in my `/home/bob' buffer. I am on line 1, in Texinfo mode, and am at
12584the top of the buffer.
12585
12586My `.emacs' file has a section that looks like this:
12587
12588 ;; Set a Mode Line that tells me which machine, which directory,
12589 ;; and which line I am on, plus the other customary information.
12590 (setq default-mode-line-format
12591 (quote
12592 (#("-" 0 1
12593 (help-echo
12594 "mouse-1: select window, mouse-2: delete others ..."))
12595 mode-line-mule-info
12596 mode-line-modified
12597 mode-line-frame-identification
12598 " "
12599 mode-line-buffer-identification
12600 " "
12601 (:eval (substring
12602 (system-name) 0 (string-match "\\..+" (system-name))))
12603 ":"
12604 default-directory
12605 #(" " 0 1
12606 (help-echo
12607 "mouse-1: select window, mouse-2: delete others ..."))
12608 (line-number-mode " Line %l ")
12609 global-mode-string
12610 #(" %[(" 0 6
12611 (help-echo
12612 "mouse-1: select window, mouse-2: delete others ..."))
12613 (:eval (mode-line-mode-name))
12614 mode-line-process
12615 minor-mode-alist
12616 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
12617 ")%] "
12618 (-3 . "%P")
12619 ;; "-%-"
12620 )))
12621
12622Here, I redefine the default mode line. Most of the parts are from
12623the original; but I make a few changes. I set the _default_ mode
12624line format so as to permit various modes, such as Info, to override
12625it.
12626
12627Many elements in the list are self-explanatory: `mode-line-modified'
12628is a variable that tells whether the buffer has been modified,
12629`mode-name' tells the name of the mode, and so on. However, the
12630format looks complicated because of two features we have not
12631discussed.
12632
12633The first string in the mode line is a dash or hyphen, `-'. In the
12634old days, it would have been specified simply as `"-"'. But
12635nowadays, Emacs can add properties to a string, such as highlighting
12636or, as in this case, a help feature. If you place your mouse cursor
12637over the hyphen, some help information appears (By default, you must
12638wait one second before the information appears. You can change that
12639timing by changing the value of `tooltip-delay'.)
12640
12641The new string format has a special syntax:
12642
12643 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
12644
12645The `#(' begins a list. The first element of the list is the string
12646itself, just one `-'. The second and third elements specify the
12647range over which the fourth element applies. A range starts _after_
12648a character, so a zero means the range starts just before the first
12649character; a 1 means that the range ends just after the first
12650character. The third element is the property for the range. It
12651consists of a property list, a property name, in this case,
12652`help-echo', followed by a value, in this case, a string. The
12653second, third, and fourth elements of this new string format can be
12654repeated.
12655
12656*Note Text Properties in String: (elisp)Text Props and Strings, and
12657see *Note Mode Line Format: (elisp)Mode Line Format, for more
12658information.
12659
12660`mode-line-buffer-identification' displays the current buffer name.
12661It is a list beginning `(#("%12b" 0 4 ...'. The `#(' begins the list.
12662
12663The `"%12b"' displays the current buffer name, using the
12664`buffer-name' function with which we are familiar; the `12' specifies
12665the maximum number of characters that will be displayed. When a name
12666has fewer characters, whitespace is added to fill out to this number.
12667(Buffer names can and often should be longer than 12 characters;
12668this length works well in a typical 80 column wide window.)
12669
12670`:eval' is a new feature in GNU Emacs version 21. It says to
12671evaluate the following form and use the result as a string to display.
12672In this case, the expression displays the first component of the full
12673system name. The end of the first component is a `.' (`period'), so
12674I use the `string-match' function to tell me the length of the first
12675component. The substring from the zeroth character to that length is
12676the name of the machine.
12677
12678This is the expression:
12679
12680 (:eval (substring
12681 (system-name) 0 (string-match "\\..+" (system-name))))
12682
12683`%[' and `%]' cause a pair of square brackets to appear for each
12684recursive editing level. `%n' says `Narrow' when narrowing is in
12685effect. `%P' tells you the percentage of the buffer that is above
12686the bottom of the window, or `Top', `Bottom', or `All'. (A lower
12687case `p' tell you the percentage above the _top_ of the window.)
12688`%-' inserts enough dashes to fill out the line.
12689
12690Remember, "You don't have to like Emacs to like it" -- your own Emacs
12691can have different colors, different commands, and different keys
12692than a default Emacs.
12693
12694On the other hand, if you want to bring up a plain `out of the box'
12695Emacs, with no customization, type:
12696
12697 emacs -q
12698
12699This will start an Emacs that does _not_ load your `~/.emacs'
12700initialization file. A plain, default Emacs. Nothing more.
12701
12702Debugging
12703*********
12704
12705GNU Emacs has two debuggers, `debug' and `edebug'. The first is
12706built into the internals of Emacs and is always with you; the second
12707requires that you instrument a function before you can use it.
12708
12709Both debuggers are described extensively in *Note Debugging Lisp
12710Programs: (elisp)Debugging. In this chapter, I will walk through a
12711short example of each.
12712
12713`debug'
12714=======
12715
12716Suppose you have written a function definition that is intended to
12717return the sum of the numbers 1 through a given number. (This is the
12718`triangle' function discussed earlier. *Note Example with
12719Decrementing Counter: Decrementing Example, for a discussion.)
12720
12721However, your function definition has a bug. You have mistyped `1='
12722for `1-'. Here is the broken definition:
12723
12724 (defun triangle-bugged (number)
12725 "Return sum of numbers 1 through NUMBER inclusive."
12726 (let ((total 0))
12727 (while (> number 0)
12728 (setq total (+ total number))
12729 (setq number (1= number))) ; Error here.
12730 total))
12731
12732If you are reading this in Info, you can evaluate this definition in
12733the normal fashion. You will see `triangle-bugged' appear in the
12734echo area.
12735
12736Now evaluate the `triangle-bugged' function with an argument of 4:
12737
12738 (triangle-bugged 4)
12739
12740In GNU Emacs version 21, you will create and enter a `*Backtrace*'
12741buffer that says:
12742
12743 ---------- Buffer: *Backtrace* ----------
12744 Debugger entered--Lisp error: (void-function 1=)
12745 (1= number)
12746 (setq number (1= number))
12747 (while (> number 0) (setq total (+ total number))
12748 (setq number (1= number)))
12749 (let ((total 0)) (while (> number 0) (setq total ...)
12750 (setq number ...)) total)
12751 triangle-bugged(4)
12752 eval((triangle-bugged 4))
12753 eval-last-sexp-1(nil)
12754 eval-last-sexp(nil)
12755 call-interactively(eval-last-sexp)
12756 ---------- Buffer: *Backtrace* ----------
12757
12758(I have reformatted this example slightly; the debugger does not fold
12759long lines. As usual, you can quit the debugger by typing `q' in the
12760`*Backtrace*' buffer.)
12761
12762In practice, for a bug as simple as this, the `Lisp error' line will
12763tell you what you need to know to correct the definition. The
12764function `1=' is `void'.
12765
12766In GNU Emacs 20 and before, you will see:
12767
12768 Symbol's function definition is void: 1=
12769
12770which has the same meaning as the `*Backtrace*' buffer line in
12771version 21.
12772
12773However, suppose you are not quite certain what is going on? You can
12774read the complete backtrace.
12775
12776In this case, you need to run GNU Emacs 21, which automatically starts
12777the debugger that puts you in the `*Backtrace*' buffer; or else, you
12778need to start the debugger manually as described below.
12779
12780Read the `*Backtrace*' buffer from the bottom up; it tells you what
12781Emacs did that led to the error. Emacs made an interactive call to
12782`C-x C-e' (`eval-last-sexp'), which led to the evaluation of the
12783`triangle-bugged' expression. Each line above tells you what the
12784Lisp interpreter evaluated next.
12785
12786The third line from the top of the buffer is
12787
12788 (setq number (1= number))
12789
12790Emacs tried to evaluate this expression; in order to do so, it tried
12791to evaluate the inner expression shown on the second line from the
12792top:
12793
12794 (1= number)
12795
12796This is where the error occurred; as the top line says:
12797
12798 Debugger entered--Lisp error: (void-function 1=)
12799
12800You can correct the mistake, re-evaluate the function definition, and
12801then run your test again.
12802
12803`debug-on-entry'
12804================
12805
12806GNU Emacs 21 starts the debugger automatically when your function has
12807an error. GNU Emacs version 20 and before did not; it simply
12808presented you with an error message. You had to start the debugger
12809manually.
12810
12811You can start the debugger manually for all versions of Emacs; the
12812advantage is that the debugger runs even if you do not have a bug in
12813your code. Sometimes your code will be free of bugs!
12814
12815You can enter the debugger when you call the function by calling
12816`debug-on-entry'.
12817
12818Type:
12819
12820 M-x debug-on-entry RET triangle-bugged RET
12821
12822Now, evaluate the following:
12823
12824 (triangle-bugged 5)
12825
12826All versions of Emacs will create a `*Backtrace*' buffer and tell you
12827that it is beginning to evaluate the `triangle-bugged' function:
12828
12829 ---------- Buffer: *Backtrace* ----------
12830 Debugger entered--entering a function:
12831 * triangle-bugged(5)
12832 eval((triangle-bugged 5))
12833 eval-last-sexp-1(nil)
12834 eval-last-sexp(nil)
12835 call-interactively(eval-last-sexp)
12836 ---------- Buffer: *Backtrace* ----------
12837
12838In the `*Backtrace*' buffer, type `d'. Emacs will evaluate the first
12839expression in `triangle-bugged'; the buffer will look like this:
12840
12841 ---------- Buffer: *Backtrace* ----------
12842 Debugger entered--beginning evaluation of function call form:
12843 * (let ((total 0)) (while (> number 0) (setq total ...)
12844 (setq number ...)) total)
12845 * triangle-bugged(5)
12846 eval((triangle-bugged 5))
12847 eval-last-sexp-1(nil)
12848 eval-last-sexp(nil)
12849 call-interactively(eval-last-sexp)
12850 ---------- Buffer: *Backtrace* ----------
12851
12852Now, type `d' again, eight times, slowly. Each time you type `d',
12853Emacs will evaluate another expression in the function definition.
12854
12855Eventually, the buffer will look like this:
12856
12857 ---------- Buffer: *Backtrace* ----------
12858 Debugger entered--beginning evaluation of function call form:
12859 * (setq number (1= number))
12860 * (while (> number 0) (setq total (+ total number))
12861 (setq number (1= number)))
12862 * (let ((total 0)) (while (> number 0) (setq total ...)
12863 (setq number ...)) total)
12864 * triangle-bugged(5)
12865 eval((triangle-bugged 5))
12866 eval-last-sexp-1(nil)
12867 eval-last-sexp(nil)
12868 call-interactively(eval-last-sexp)
12869 ---------- Buffer: *Backtrace* ----------
12870
12871Finally, after you type `d' two more times, Emacs will reach the
12872error, and the top two lines of the `*Backtrace*' buffer will look
12873like this:
12874
12875 ---------- Buffer: *Backtrace* ----------
12876 Debugger entered--Lisp error: (void-function 1=)
12877 * (1= number)
12878 ...
12879 ---------- Buffer: *Backtrace* ----------
12880
12881By typing `d', you were able to step through the function.
12882
12883You can quit a `*Backtrace*' buffer by typing `q' in it; this quits
12884the trace, but does not cancel `debug-on-entry'.
12885
12886To cancel the effect of `debug-on-entry', call
12887`cancel-debug-on-entry' and the name of the function, like this:
12888
12889 M-x cancel-debug-on-entry RET triangle-bugged RET
12890
12891(If you are reading this in Info, cancel `debug-on-entry' now.)
12892
12893`debug-on-quit' and `(debug)'
12894=============================
12895
12896In addition to setting `debug-on-error' or calling `debug-on-entry',
12897there are two other ways to start `debug'.
12898
12899You can start `debug' whenever you type `C-g' (`keyboard-quit') by
12900setting the variable `debug-on-quit' to `t'. This is useful for
12901debugging infinite loops.
12902
12903Or, you can insert a line that says `(debug)' into your code where
12904you want the debugger to start, like this:
12905
12906 (defun triangle-bugged (number)
12907 "Return sum of numbers 1 through NUMBER inclusive."
12908 (let ((total 0))
12909 (while (> number 0)
12910 (setq total (+ total number))
12911 (debug) ; Start debugger.
12912 (setq number (1= number))) ; Error here.
12913 total))
12914
12915The `debug' function is described in detail in *Note The Lisp
12916Debugger: (elisp)Debugger.
12917
12918The `edebug' Source Level Debugger
12919==================================
12920
12921Edebug is a source level debugger. Edebug normally displays the
12922source of the code you are debugging, with an arrow at the left that
12923shows which line you are currently executing.
12924
12925You can walk through the execution of a function, line by line, or run
12926quickly until reaching a "breakpoint" where execution stops.
12927
12928Edebug is described in *Note Edebug: (elisp)edebug.
12929
12930Here is a bugged function definition for `triangle-recursively'.
12931*Note Recursion in place of a counter: Recursive triangle function,
12932for a review of it.
12933
12934 (defun triangle-recursively-bugged (number)
12935 "Return sum of numbers 1 through NUMBER inclusive.
12936 Uses recursion."
12937 (if (= number 1)
12938 1
12939 (+ number
12940 (triangle-recursively-bugged
12941 (1= number))))) ; Error here.
12942
12943Normally, you would install this definition by positioning your cursor
12944after the function's closing parenthesis and typing `C-x C-e'
12945(`eval-last-sexp') or else by positioning your cursor within the
12946definition and typing `C-M-x' (`eval-defun'). (By default, the
12947`eval-defun' command works only in Emacs Lisp mode or in Lisp
12948Interactive mode.)
12949
12950However, to prepare this function definition for Edebug, you must
12951first "instrument" the code using a different command. You can do
12952this by positioning your cursor within the definition and typing
12953
12954 M-x edebug-defun RET
12955
12956This will cause Emacs to load Edebug automatically if it is not
12957already loaded, and properly instrument the function.
12958
12959After instrumenting the function, place your cursor after the
12960following expression and type `C-x C-e' (`eval-last-sexp'):
12961
12962 (triangle-recursively-bugged 3)
12963
12964You will be jumped back to the source for
12965`triangle-recursively-bugged' and the cursor positioned at the
12966beginning of the `if' line of the function. Also, you will see an
12967arrowhead at the left hand side of that line. The arrowhead marks
12968the line where the function is executing. (In the following examples,
12969we show the arrowhead with `=>'; in a windowing system, you may see
12970the arrowhead as a solid triangle in the window `fringe'.)
12971
12972 =>-!-(if (= number 1)
12973
12974In the example, the location of point is displayed as `-!-' (in a
12975printed book, it is displayed with a five pointed star).
12976
12977If you now press <SPC>, point will move to the next expression to be
12978executed; the line will look like this:
12979
12980 =>(if -!-(= number 1)
12981
12982As you continue to press <SPC>, point will move from expression to
12983expression. At the same time, whenever an expression returns a value,
12984that value will be displayed in the echo area. For example, after you
12985move point past `number', you will see the following:
12986
12987 Result: 3 = C-c
12988
12989This means the value of `number' is 3, which is ASCII `control-c'
12990(the third letter of the alphabet).
12991
12992You can continue moving through the code until you reach the line with
12993the error. Before evaluation, that line looks like this:
12994
12995 => -!-(1= number))))) ; Error here.
12996
12997When you press <SPC> once again, you will produce an error message
12998that says:
12999
13000 Symbol's function definition is void: 1=
13001
13002This is the bug.
13003
13004Press `q' to quit Edebug.
13005
13006To remove instrumentation from a function definition, simply
13007re-evaluate it with a command that does not instrument it. For
13008example, you could place your cursor after the definition's closing
13009parenthesis and type `C-x C-e'.
13010
13011Edebug does a great deal more than walk with you through a function.
13012You can set it so it races through on its own, stopping only at an
13013error or at specified stopping points; you can cause it to display the
13014changing values of various expressions; you can find out how many
13015times a function is called, and more.
13016
13017Edebug is described in *Note Edebug: (elisp)edebug.
13018
13019Debugging Exercises
13020===================
13021
13022 * Install the `count-words-region' function and then cause it to
13023 enter the built-in debugger when you call it. Run the command
13024 on a region containing two words. You will need to press `d' a
13025 remarkable number of times. On your system, is a `hook' called
13026 after the command finishes? (For information on hooks, see
13027 *Note Command Loop Overview: (elisp)Command Overview.)
13028
13029 * Copy `count-words-region' into the `*scratch*' buffer,
13030 instrument the function for Edebug, and walk through its
13031 execution. The function does not need to have a bug, although
13032 you can introduce one if you wish. If the function lacks a bug,
13033 the walk-through completes without problems.
13034
13035 * While running Edebug, type `?' to see a list of all the Edebug
13036 commands. (The `global-edebug-prefix' is usually `C-x X', i.e.
13037 `<CTL>-x' followed by an upper case `X'; use this prefix for
13038 commands made outside of the Edebug debugging buffer.)
13039
13040 * In the Edebug debugging buffer, use the `p'
13041 (`edebug-bounce-point') command to see where in the region the
13042 `count-words-region' is working.
13043
13044 * Move point to some spot further down function and then type the
13045 `h' (`edebug-goto-here') command to jump to that location.
13046
13047 * Use the `t' (`edebug-trace-mode') command to cause Edebug to
13048 walk through the function on its own; use an upper case `T' for
13049 `edebug-Trace-fast-mode'.
13050
13051 * Set a breakpoint, then run Edebug in Trace mode until it reaches
13052 the stopping point.
13053
13054Conclusion
13055**********
13056
13057We have now reached the end of this Introduction. You have now
13058learned enough about programming in Emacs Lisp to set values, to write
13059simple `.emacs' files for yourself and your friends, and write simple
13060customizations and extensions to Emacs.
13061
13062This is a place to stop. Or, if you wish, you can now go onward, and
13063teach yourself.
13064
13065You have learned some of the basic nuts and bolts of programming. But
13066only some. There are a great many more brackets and hinges that are
13067easy to use that we have not touched.
13068
13069A path you can follow right now lies among the sources to GNU Emacs
13070and in *Note The GNU Emacs Lisp Reference Manual: (elisp)Top.
13071
13072The Emacs Lisp sources are an adventure. When you read the sources
13073and come across a function or expression that is unfamiliar, you need
13074to figure out or find out what it does.
13075
13076Go to the Reference Manual. It is a thorough, complete, and fairly
13077easy-to-read description of Emacs Lisp. It is written not only for
13078experts, but for people who know what you know. (The `Reference
13079Manual' comes with the standard GNU Emacs distribution. Like this
13080introduction, it comes as a Texinfo source file, so you can read it
13081on-line and as a typeset, printed book.)
13082
13083Go to the other on-line help that is part of GNU Emacs: the on-line
13084documentation for all functions, and `find-tags', the program that
13085takes you to sources.
13086
13087Here is an example of how I explore the sources. Because of its name,
13088`simple.el' is the file I looked at first, a long time ago. As it
13089happens some of the functions in `simple.el' are complicated, or at
13090least look complicated at first sight. The `open-line' function, for
13091example, looks complicated.
13092
13093You may want to walk through this function slowly, as we did with the
13094`forward-sentence' function. (*Note forward-sentence::.) Or you may
13095want to skip that function and look at another, such as `split-line'.
13096You don't need to read all the functions. According to
13097`count-words-in-defun', the `split-line' function contains 27 words
13098and symbols.
13099
13100Even though it is short, `split-line' contains four expressions we
13101have not studied: `skip-chars-forward', `indent-to', `current-column'
13102and `?\n'.
13103
13104Consider the `skip-chars-forward' function. (It is part of the
13105function definition for `back-to-indentation', which is shown in
13106*Note Review: Review.)
13107
13108In GNU Emacs, you can find out more about `skip-chars-forward' by
13109typing `C-h f' (`describe-function') and the name of the function.
13110This gives you the function documentation.
13111
13112You may be able to guess what is done by a well named function such as
13113`indent-to'; or you can look it up, too. Incidentally, the
13114`describe-function' function itself is in `help.el'; it is one of
13115those long, but decipherable functions. You can look up
13116`describe-function' using the `C-h f' command!
13117
13118In this instance, since the code is Lisp, the `*Help*' buffer
13119contains the name of the library containing the function's source.
13120You can put point over the name of the library and press the RET key,
13121which in this situation is bound to `help-follow', and be taken
13122directly to the source, in the same way as `M-.' (`find-tag').
13123
13124The definition for `describe-function' illustrates how to customize
13125the `interactive' expression without using the standard character
13126codes; and it shows how to create a temporary buffer.
13127
13128(The `indent-to' function is written in C rather than Emacs Lisp; it
13129is a `built-in' function. `help-follow' only provides you with the
13130documentation of a built-in function; it does not take you to the
13131source. But `find-tag' will take you to the source, if properly set
13132up.)
13133
13134You can look at a function's source using `find-tag', which is bound
13135to `M-.' Finally, you can find out what the Reference Manual has to
13136say by visiting the manual in Info, and typing `i' (`Info-index') and
13137the name of the function, or by looking up `skip-chars-forward' in
13138the index to a printed copy of the manual.
13139
13140Similarly, you can find out what is meant by `?\n'. You can try
13141using `Info-index' with `?\n'. It turns out that this action won't
13142help; but don't give up. If you search the index for `\n' without
13143the `?', you will be taken directly to the relevant section of the
13144manual. (*Note Character Type: (elisp)Character Type. `?\n' stands
13145for the newline character.)
13146
13147Other interesting source files include `paragraphs.el',
13148`loaddefs.el', and `loadup.el'. The `paragraphs.el' file includes
13149short, easily understood functions as well as longer ones. The
13150`loaddefs.el' file contains the many standard autoloads and many
13151keymaps. I have never looked at it all; only at parts. `loadup.el'
13152is the file that loads the standard parts of Emacs; it tells you a
13153great deal about how Emacs is built. (*Note Building Emacs:
13154(elisp)Building Emacs, for more about building.)
13155
13156As I said, you have learned some nuts and bolts; however, and very
13157importantly, we have hardly touched major aspects of programming; I
13158have said nothing about how to sort information, except to use the
13159predefined `sort' function; I have said nothing about how to store
13160information, except to use variables and lists; I have said nothing
13161about how to write programs that write programs. These are topics for
13162another, and different kind of book, a different kind of learning.
13163
13164What you have done is learn enough for much practical work with GNU
13165Emacs. What you have done is get started. This is the end of a
13166beginning.
13167
13168The `the-the' Function
13169**********************
13170
13171Sometimes when you you write text, you duplicate words--as with "you
13172you" near the beginning of this sentence. I find that most
13173frequently, I duplicate "the'; hence, I call the function for
13174detecting duplicated words, `the-the'.
13175
13176As a first step, you could use the following regular expression to
13177search for duplicates:
13178
13179 \\(\\w+[ \t\n]+\\)\\1
13180
13181This regexp matches one or more word-constituent characters followed
13182by one or more spaces, tabs, or newlines. However, it does not detect
13183duplicated words on different lines, since the ending of the first
13184word, the end of the line, is different from the ending of the second
13185word, a space. (For more information about regular expressions, see
13186*Note Regular Expression Searches: Regexp Search, as well as *Note
13187Syntax of Regular Expressions: (emacs)Regexps, and *Note Regular
13188Expressions: (elisp)Regular Expressions.)
13189
13190You might try searching just for duplicated word-constituent
13191characters but that does not work since the pattern detects doubles
13192such as the two occurrences of `th' in `with the'.
13193
13194Another possible regexp searches for word-constituent characters
13195followed by non-word-constituent characters, reduplicated. Here,
13196`\\w+' matches one or more word-constituent characters and `\\W*'
13197matches zero or more non-word-constituent characters.
13198
13199 \\(\\(\\w+\\)\\W*\\)\\1
13200
13201Again, not useful.
13202
13203Here is the pattern that I use. It is not perfect, but good enough.
13204`\\b' matches the empty string, provided it is at the beginning or
13205end of a word; `[^@ \n\t]+' matches one or more occurrences of any
13206characters that are _not_ an @-sign, space, newline, or tab.
13207
13208 \\b\\([^@ \n\t]+\\)[ \n\t]+\\1\\b
13209
13210One can write more complicated expressions, but I found that this
13211expression is good enough, so I use it.
13212
13213Here is the `the-the' function, as I include it in my `.emacs' file,
13214along with a handy global key binding:
13215
13216 (defun the-the ()
13217 "Search forward for for a duplicated word."
13218 (interactive)
13219 (message "Searching for for duplicated words ...")
13220 (push-mark)
13221 ;; This regexp is not perfect
13222 ;; but is fairly good over all:
13223 (if (re-search-forward
13224 "\\b\\([^@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
13225 (message "Found duplicated word.")
13226 (message "End of buffer")))
13227
13228 ;; Bind `the-the' to C-c \
13229 (global-set-key "\C-c\\" 'the-the)
13230
13231
13232Here is test text:
13233
13234 one two two three four five
13235 five six seven
13236
13237You can substitute the other regular expressions shown above in the
13238function definition and try each of them on this list.
13239
13240Handling the Kill Ring
13241**********************
13242
13243The kill ring is a list that is transformed into a ring by the
13244workings of the `rotate-yank-pointer' function. The `yank' and
13245`yank-pop' commands use the `rotate-yank-pointer' function. This
13246appendix describes the `rotate-yank-pointer' function as well as both
13247the `yank' and the `yank-pop' commands.
13248
13249The `rotate-yank-pointer' Function
13250==================================
13251
13252The `rotate-yank-pointer' function changes the element in the kill
13253ring to which `kill-ring-yank-pointer' points. For example, it can
13254change `kill-ring-yank-pointer' from pointing to the second element
13255to point to the third element.
13256
13257Here is the code for `rotate-yank-pointer':
13258
13259 (defun rotate-yank-pointer (arg)
13260 "Rotate the yanking point in the kill ring."
13261 (interactive "p")
13262 (let ((length (length kill-ring)))
13263 (if (zerop length)
13264 ;; then-part
13265 (error "Kill ring is empty")
13266 ;; else-part
13267 (setq kill-ring-yank-pointer
13268 (nthcdr (% (+ arg
13269 (- length
13270 (length
13271 kill-ring-yank-pointer)))
13272 length)
13273 kill-ring)))))
13274
13275`rotate-yank-pointer' in Outline
13276--------------------------------
13277
13278The `rotate-yank-pointer' function looks complex, but as usual, it
13279can be understood by taking it apart piece by piece. First look at
13280it in skeletal form:
13281
13282 (defun rotate-yank-pointer (arg)
13283 "Rotate the yanking point in the kill ring."
13284 (interactive "p")
13285 (let VARLIST
13286 BODY...)
13287
13288This function takes one argument, called `arg'. It has a brief
13289documentation string; and it is interactive with a small `p', which
13290means that the argument must be a processed prefix passed to the
13291function as a number.
13292
13293The body of the function definition is a `let' expression, which
13294itself has a body as well as a VARLIST.
13295
13296The `let' expression declares a variable that will be only usable
13297within the bounds of this function. This variable is called `length'
13298and is bound to a value that is equal to the number of items in the
13299kill ring. This is done by using the function called `length'.
13300(Note that this function has the same name as the variable called
13301`length'; but one use of the word is to name the function and the
13302other is to name the variable. The two are quite distinct.
13303Similarly, an English speaker will distinguish between the meanings
13304of the word `ship' when he says: "I must ship this package
13305immediately." and "I must get aboard the ship immediately.")
13306
13307The function `length' tells the number of items there are in a list,
13308so `(length kill-ring)' returns the number of items there are in the
13309kill ring.
13310
13311The Body of `rotate-yank-pointer'
13312---------------------------------
13313
13314The body of `rotate-yank-pointer' is a `let' expression and the body
13315of the `let' expression is an `if' expression.
13316
13317The purpose of the `if' expression is to find out whether there is
13318anything in the kill ring. If the kill ring is empty, the `error'
13319function stops evaluation of the function and prints a message in the
13320echo area. On the other hand, if the kill ring has something in it,
13321the work of the function is done.
13322
13323Here is the if-part and then-part of the `if' expression:
13324
13325 (if (zerop length) ; if-part
13326 (error "Kill ring is empty") ; then-part
13327 ...
13328
13329If there is not anything in the kill ring, its length must be zero and
13330an error message sent to the user: `Kill ring is empty'. The `if'
13331expression uses the function `zerop' which returns true if the value
13332it is testing is zero. When `zerop' tests true, the then-part of the
13333`if' is evaluated. The then-part is a list starting with the
13334function `error', which is a function that is similar to the
13335`message' function (*note message::), in that it prints a one-line
13336message in the echo area. However, in addition to printing a
13337message, `error' also stops evaluation of the function within which
13338it is embedded. This means that the rest of the function will not be
13339evaluated if the length of the kill ring is zero.
13340
13341Digression about the word `error'
13342.................................
13343
13344(In my opinion, it is slightly misleading, at least to humans, to use
13345the term `error' as the name of the `error' function. A better term
13346would be `cancel'. Strictly speaking, of course, you cannot point
13347to, much less rotate a pointer to a list that has no length, so from
13348the point of view of the computer, the word `error' is correct. But
13349a human expects to attempt this sort of thing, if only to find out
13350whether the kill ring is full or empty. This is an act of
13351exploration.
13352
13353(From the human point of view, the act of exploration and discovery is
13354not necessarily an error, and therefore should not be labelled as one,
13355even in the bowels of a computer. As it is, the code in Emacs implies
13356that a human who is acting virtuously, by exploring his or her
13357environment, is making an error. This is bad. Even though the
13358computer takes the same steps as it does when there is an `error', a
13359term such as `cancel' would have a clearer connotation.)
13360
13361The else-part of the `if' expression
13362....................................
13363
13364The else-part of the `if' expression is dedicated to setting the
13365value of `kill-ring-yank-pointer' when the kill ring has something in
13366it. The code looks like this:
13367
13368 (setq kill-ring-yank-pointer
13369 (nthcdr (% (+ arg
13370 (- length
13371 (length kill-ring-yank-pointer)))
13372 length)
13373 kill-ring)))))
13374
13375This needs some examination. Clearly, `kill-ring-yank-pointer' is
13376being set to be equal to some CDR of the kill ring, using the
13377`nthcdr' function that is described in an earlier section. (*Note
13378copy-region-as-kill::.) But exactly how does it do this?
13379
13380Before looking at the details of the code let's first consider the
13381purpose of the `rotate-yank-pointer' function.
13382
13383The `rotate-yank-pointer' function changes what
13384`kill-ring-yank-pointer' points to. If `kill-ring-yank-pointer'
13385starts by pointing to the first element of a list, a call to
13386`rotate-yank-pointer' causes it to point to the second element; and
13387if `kill-ring-yank-pointer' points to the second element, a call to
13388`rotate-yank-pointer' causes it to point to the third element. (And
13389if `rotate-yank-pointer' is given an argument greater than 1, it
13390jumps the pointer that many elements.)
13391
13392The `rotate-yank-pointer' function uses `setq' to reset what the
13393`kill-ring-yank-pointer' points to. If `kill-ring-yank-pointer'
13394points to the first element of the kill ring, then, in the simplest
13395case, the `rotate-yank-pointer' function must cause it to point to
13396the second element. Put another way, `kill-ring-yank-pointer' must
13397be reset to have a value equal to the CDR of the kill ring.
13398
13399That is, under these circumstances,
13400
13401 (setq kill-ring-yank-pointer
13402 ("some text" "a different piece of text" "yet more text"))
13403
13404 (setq kill-ring
13405 ("some text" "a different piece of text" "yet more text"))
13406
13407the code should do this:
13408
13409 (setq kill-ring-yank-pointer (cdr kill-ring))
13410
13411As a result, the `kill-ring-yank-pointer' will look like this:
13412
13413 kill-ring-yank-pointer
13414 => ("a different piece of text" "yet more text"))
13415
13416The actual `setq' expression uses the `nthcdr' function to do the job.
13417
13418As we have seen before (*note nthcdr::), the `nthcdr' function works
13419by repeatedly taking the CDR of a list--it takes the CDR of the CDR
13420of the CDR ...
13421
13422The two following expressions produce the same result:
13423
13424 (setq kill-ring-yank-pointer (cdr kill-ring))
13425
13426 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
13427
13428In the `rotate-yank-pointer' function, however, the first argument to
13429`nthcdr' is a rather complex looking expression with lots of
13430arithmetic inside of it:
13431
13432 (% (+ arg
13433 (- length
13434 (length kill-ring-yank-pointer)))
13435 length)
13436
13437As usual, we need to look at the most deeply embedded expression first
13438and then work our way towards the light.
13439
13440The most deeply embedded expression is `(length
13441kill-ring-yank-pointer)'. This finds the length of the current value
13442of the `kill-ring-yank-pointer'. (Remember that the
13443`kill-ring-yank-pointer' is the name of a variable whose value is a
13444list.)
13445
13446The measurement of the length is inside the expression:
13447
13448 (- length (length kill-ring-yank-pointer))
13449
13450In this expression, the first `length' is the variable that was
13451assigned the length of the kill ring in the `let' statement at the
13452beginning of the function. (One might think this function would be
13453clearer if the variable `length' were named `length-of-kill-ring'
13454instead; but if you look at the text of the whole function, you will
13455see that it is so short that naming this variable `length' is not a
13456bother, unless you are pulling the function apart into very tiny
13457pieces as we are doing here.)
13458
13459So the line `(- length (length kill-ring-yank-pointer))' tells the
13460difference between the length of the kill ring and the length of the
13461list whose name is `kill-ring-yank-pointer'.
13462
13463To see how all this fits into the `rotate-yank-pointer' function,
13464let's begin by analyzing the case where `kill-ring-yank-pointer'
13465points to the first element of the kill ring, just as `kill-ring'
13466does, and see what happens when `rotate-yank-pointer' is called with
13467an argument of 1.
13468
13469The variable `length' and the value of the expression `(length
13470kill-ring-yank-pointer)' will be the same since the variable `length'
13471is the length of the kill ring and the `kill-ring-yank-pointer' is
13472pointing to the whole kill ring. Consequently, the value of
13473
13474 (- length (length kill-ring-yank-pointer))
13475
13476will be zero. Since the value of `arg' will be 1, this will mean
13477that the value of the whole expression
13478
13479 (+ arg (- length (length kill-ring-yank-pointer)))
13480
13481will be 1.
13482
13483Consequently, the argument to `nthcdr' will be found as the result of
13484the expression
13485
13486 (% 1 length)
13487
13488The `%' remainder function
13489..........................
13490
13491To understand `(% 1 length)', we need to understand `%'. According
13492to its documentation (which I just found by typing `C-h f % <RET>'),
13493the `%' function returns the remainder of its first argument divided
13494by its second argument. For example, the remainder of 5 divided by 2
13495is 1. (2 goes into 5 twice with a remainder of 1.)
13496
13497What surprises people who don't often do arithmetic is that a smaller
13498number can be divided by a larger number and have a remainder. In the
13499example we just used, 5 was divided by 2. We can reverse that and
13500ask, what is the result of dividing 2 by 5? If you can use
13501fractions, the answer is obviously 2/5 or .4; but if, as here, you
13502can only use whole numbers, the result has to be something different.
13503Clearly, 5 can go into 2 zero times, but what of the remainder? To
13504see what the answer is, consider a case that has to be familiar from
13505childhood:
13506
13507 * 5 divided by 5 is 1 with a remainder of 0;
13508
13509 * 6 divided by 5 is 1 with a remainder of 1;
13510
13511 * 7 divided by 5 is 1 with a remainder of 2.
13512
13513 * Similarly, 10 divided by 5 is 2 with a remainder of 0;
13514
13515 * 11 divided by 5 is 2 with a remainder of 1;
13516
13517 * 12 divided by 5 is 1 with a remainder of 2.
13518
13519By considering the cases as parallel, we can see that
13520
13521 * zero divided by 5 must be zero with a remainder of zero;
13522
13523 * 1 divided by 5 must be zero with a remainder of 1;
13524
13525 * 2 divided by 5 must be zero with a remainder of 2;
13526
13527and so on.
13528
13529So, in this code, if the value of `length' is 5, then the result of
13530evaluating
13531
13532 (% 1 5)
13533
13534is 1. (I just checked this by placing the cursor after the expression
13535and typing `C-x C-e'. Indeed, 1 is printed in the echo area.)
13536
13537Using `%' in `rotate-yank-pointer'
13538..................................
13539
13540When the `kill-ring-yank-pointer' points to the beginning of the kill
13541ring, and the argument passed to `rotate-yank-pointer' is 1, the `%'
13542expression returns 1:
13543
13544 (- length (length kill-ring-yank-pointer))
13545 => 0
13546
13547therefore,
13548
13549 (+ arg (- length (length kill-ring-yank-pointer)))
13550 => 1
13551
13552and consequently:
13553
13554 (% (+ arg (- length (length kill-ring-yank-pointer)))
13555 length)
13556 => 1
13557
13558regardless of the value of `length'.
13559
13560As a result of this, the `setq kill-ring-yank-pointer' expression
13561simplifies to:
13562
13563 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
13564
13565What it does is now easy to understand. Instead of pointing as it did
13566to the first element of the kill ring, the `kill-ring-yank-pointer'
13567is set to point to the second element.
13568
13569Clearly, if the argument passed to `rotate-yank-pointer' is two, then
13570the `kill-ring-yank-pointer' is set to `(nthcdr 2 kill-ring)'; and so
13571on for different values of the argument.
13572
13573Similarly, if the `kill-ring-yank-pointer' starts out pointing to the
13574second element of the kill ring, its length is shorter than the
13575length of the kill ring by 1, so the computation of the remainder is
13576based on the expression `(% (+ arg 1) length)'. This means that the
13577`kill-ring-yank-pointer' is moved from the second element of the kill
13578ring to the third element if the argument passed to
13579`rotate-yank-pointer' is 1.
13580
13581Pointing to the last element
13582............................
13583
13584The final question is, what happens if the `kill-ring-yank-pointer'
13585is set to the _last_ element of the kill ring? Will a call to
13586`rotate-yank-pointer' mean that nothing more can be taken from the
13587kill ring? The answer is no. What happens is different and useful.
13588The `kill-ring-yank-pointer' is set to point to the beginning of the
13589kill ring instead.
13590
13591Let's see how this works by looking at the code, assuming the length
13592of the kill ring is 5 and the argument passed to
13593`rotate-yank-pointer' is 1. When the `kill-ring-yank-pointer' points
13594to the last element of the kill ring, its length is 1. The code
13595looks like this:
13596
13597 (% (+ arg (- length (length kill-ring-yank-pointer))) length)
13598
13599When the variables are replaced by their numeric values, the
13600expression looks like this:
13601
13602 (% (+ 1 (- 5 1)) 5)
13603
13604This expression can be evaluated by looking at the most embedded inner
13605expression first and working outwards: The value of `(- 5 1)' is 4;
13606the sum of `(+ 1 4)' is 5; and the remainder of dividing 5 by 5 is
13607zero. So what `rotate-yank-pointer' will do is
13608
13609 (setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
13610
13611which will set the `kill-ring-yank-pointer' to point to the beginning
13612of the kill ring.
13613
13614So what happens with successive calls to `rotate-yank-pointer' is that
13615it moves the `kill-ring-yank-pointer' from element to element in the
13616kill ring until it reaches the end; then it jumps back to the
13617beginning. And this is why the kill ring is called a ring, since by
13618jumping back to the beginning, it is as if the list has no end! (And
13619what is a ring, but an entity with no end?)
13620
13621`yank'
13622======
13623
13624After learning about `rotate-yank-pointer', the code for the `yank'
13625function is almost easy. It has only one tricky part, which is the
13626computation of the argument to be passed to `rotate-yank-pointer'.
13627
13628The code looks like this:
13629
13630 (defun yank (&optional arg)
13631 "Reinsert the last stretch of killed text.
13632 More precisely, reinsert the stretch of killed text most
13633 recently killed OR yanked.
13634 With just C-U as argument, same but put point in front
13635 (and mark at end). With argument n, reinsert the nth
13636 most recently killed stretch of killed text.
13637 See also the command \\[yank-pop]."
13638
13639 (interactive "*P")
13640 (rotate-yank-pointer (if (listp arg) 0
13641 (if (eq arg '-) -1
13642 (1- arg))))
13643 (push-mark (point))
13644 (insert (car kill-ring-yank-pointer))
13645 (if (consp arg)
13646 (exchange-point-and-mark)))
13647
13648Glancing over this code, we can understand the last few lines readily
13649enough. The mark is pushed, that is, remembered; then the first
13650element (the CAR) of what the `kill-ring-yank-pointer' points to is
13651inserted; and then, if the argument passed the function is a `cons',
13652point and mark are exchanged so the point is put in the front of the
13653inserted text rather than at the end. This option is explained in
13654the documentation. The function itself is interactive with `"*P"'.
13655This means it will not work on a read-only buffer, and that the
13656unprocessed prefix argument is passed to the function.
13657
13658Passing the argument
13659....................
13660
13661The hard part of `yank' is understanding the computation that
13662determines the value of the argument passed to `rotate-yank-pointer'.
13663Fortunately, it is not so difficult as it looks at first sight.
13664
13665What happens is that the result of evaluating one or both of the `if'
13666expressions will be a number and that number will be the argument
13667passed to `rotate-yank-pointer'.
13668
13669Laid out with comments, the code looks like this:
13670
13671 (if (listp arg) ; if-part
13672 0 ; then-part
13673 (if (eq arg '-) ; else-part, inner if
13674 -1 ; inner if's then-part
13675 (1- arg)))) ; inner if's else-part
13676
13677This code consists of two `if' expression, one the else-part of the
13678other.
13679
13680The first or outer `if' expression tests whether the argument passed
13681to `yank' is a list. Oddly enough, this will be true if `yank' is
13682called without an argument--because then it will be passed the value
13683of `nil' for the optional argument and an evaluation of `(listp nil)'
13684returns true! So, if no argument is passed to `yank', the argument
13685passed to `rotate-yank-pointer' inside of `yank' is zero. This means
13686the pointer is not moved and the first element to which
13687`kill-ring-yank-pointer' points is inserted, as we expect.
13688Similarly, if the argument for `yank' is `C-u', this will be read as
13689a list, so again, a zero will be passed to `rotate-yank-pointer'.
13690(`C-u' produces an unprocessed prefix argument of `(4)', which is a
13691list of one element.) At the same time, later in the function, this
13692argument will be read as a `cons' so point will be put in the front
13693and mark at the end of the insertion. (The `P' argument to
13694`interactive' is designed to provide these values for the case when
13695an optional argument is not provided or when it is `C-u'.)
13696
13697The then-part of the outer `if' expression handles the case when
13698there is no argument or when it is `C-u'. The else-part handles the
13699other situations. The else-part is itself another `if' expression.
13700
13701The inner `if' expression tests whether the argument is a minus sign.
13702(This is done by pressing the <META> and `-' keys at the same time,
13703or the <ESC> key and then the `-' key). In this case, the
13704`rotate-yank-pointer' function is passed `-1' as an argument. This
13705moves the `kill-ring-yank-pointer' backwards, which is what is
13706desired.
13707
13708If the true-or-false-test of the inner `if' expression is false (that
13709is, if the argument is not a minus sign), the else-part of the
13710expression is evaluated. This is the expression `(1- arg)'. Because
13711of the two `if' expressions, it will only occur when the argument is
13712a positive number or when it is a negative number (not just a minus
13713sign on its own). What `(1- arg)' does is decrement the number and
13714return it. (The `1-' function subtracts one from its argument.)
13715This means that if the argument to `rotate-yank-pointer' is 1, it is
13716reduced to zero, which means the first element to which
13717`kill-ring-yank-pointer' points is yanked back, as you would expect.
13718
13719Passing a negative argument
13720...........................
13721
13722Finally, the question arises, what happens if either the remainder
13723function, `%', or the `nthcdr' function is passed a negative
13724argument, as they quite well may?
13725
13726The answers can be found by a quick test. When `(% -1 5)' is
13727evaluated, a negative number is returned; and if `nthcdr' is called
13728with a negative number, it returns the same value as if it were
13729called with a first argument of zero. This can be seen by evaluating
13730the following code.
13731
13732Here the `=>' points to the result of evaluating the code preceding
13733it. This was done by positioning the cursor after the code and
13734typing `C-x C-e' (`eval-last-sexp') in the usual fashion. You can do
13735this if you are reading this in Info inside of GNU Emacs.
13736
13737 (% -1 5)
13738 => -1
13739
13740 (setq animals '(cats dogs elephants))
13741 => (cats dogs elephants)
13742
13743 (nthcdr 1 animals)
13744 => (dogs elephants)
13745
13746 (nthcdr 0 animals)
13747 => (cats dogs elephants)
13748
13749 (nthcdr -1 animals)
13750 => (cats dogs elephants)
13751
13752So, if a minus sign or a negative number is passed to `yank', the
13753`kill-ring-yank-point' is rotated backwards until it reaches the
13754beginning of the list. Then it stays there. Unlike the other case,
13755when it jumps from the end of the list to the beginning of the list,
13756making a ring, it stops. This makes sense. You often want to get
13757back to the most recently clipped out piece of text, but you don't
13758usually want to insert text from as many as thirty kill commands ago.
13759So you need to work through the ring to get to the end, but won't
13760cycle around it inadvertently if you are trying to come back to the
13761beginning.
13762
13763Incidentally, any number passed to `yank' with a minus sign preceding
13764it will be treated as -1. This is evidently a simplification for
13765writing the program. You don't need to jump back towards the
13766beginning of the kill ring more than one place at a time and doing
13767this is easier than writing a function to determine the magnitude of
13768the number that follows the minus sign.
13769
13770`yank-pop'
13771==========
13772
13773After understanding `yank', the `yank-pop' function is easy. Leaving
13774out the documentation to save space, it looks like this:
13775
13776 (defun yank-pop (arg)
13777 (interactive "*p")
13778 (if (not (eq last-command 'yank))
13779 (error "Previous command was not a yank"))
13780 (setq this-command 'yank)
13781 (let ((before (< (point) (mark))))
13782 (delete-region (point) (mark))
13783 (rotate-yank-pointer arg)
13784 (set-mark (point))
13785 (insert (car kill-ring-yank-pointer))
13786 (if before (exchange-point-and-mark))))
13787
13788The function is interactive with a small `p' so the prefix argument
13789is processed and passed to the function. The command can only be
13790used after a previous yank; otherwise an error message is sent. This
13791check uses the variable `last-command' which is discussed elsewhere.
13792(*Note copy-region-as-kill::.)
13793
13794The `let' clause sets the variable `before' to true or false
13795depending whether point is before or after mark and then the region
13796between point and mark is deleted. This is the region that was just
13797inserted by the previous yank and it is this text that will be
13798replaced. Next the `kill-ring-yank-pointer' is rotated so that the
13799previously inserted text is not reinserted yet again. Mark is set at
13800the beginning of the place the new text will be inserted and then the
13801first element to which `kill-ring-yank-pointer' points is inserted.
13802This leaves point after the new text. If in the previous yank, point
13803was left before the inserted text, point and mark are now exchanged
13804so point is again left in front of the newly inserted text. That is
13805all there is to it!
13806
13807A Graph with Labelled Axes
13808**************************
13809
13810Printed axes help you understand a graph. They convey scale. In an
13811earlier chapter (*note Readying a Graph: Readying a Graph.), we wrote
13812the code to print the body of a graph. Here we write the code for
13813printing and labelling vertical and horizontal axes, along with the
13814body itself.
13815
13816Labelled Example Graph
13817======================
13818
13819Since insertions fill a buffer to the right and below point, the new
13820graph printing function should first print the Y or vertical axis,
13821then the body of the graph, and finally the X or horizontal axis.
13822This sequence lays out for us the contents of the function:
13823
13824 1. Set up code.
13825
13826 2. Print Y axis.
13827
13828 3. Print body of graph.
13829
13830 4. Print X axis.
13831
13832Here is an example of how a finished graph should look:
13833
13834 10 -
13835 *
13836 * *
13837 * **
13838 * ***
13839 5 - * *******
13840 * *** *******
13841 *************
13842 ***************
13843 1 - ****************
13844 | | | |
13845 1 5 10 15
13846
13847In this graph, both the vertical and the horizontal axes are labelled
13848with numbers. However, in some graphs, the horizontal axis is time
13849and would be better labelled with months, like this:
13850
13851 5 - *
13852 * ** *
13853 *******
13854 ********** **
13855 1 - **************
13856 | ^ |
13857 Jan June Jan
13858
13859Indeed, with a little thought, we can easily come up with a variety of
13860vertical and horizontal labelling schemes. Our task could become
13861complicated. But complications breed confusion. Rather than permit
13862this, it is better choose a simple labelling scheme for our first
13863effort, and to modify or replace it later.
13864
13865These considerations suggest the following outline for the
13866`print-graph' function:
13867
13868 (defun print-graph (numbers-list)
13869 "DOCUMENTATION..."
13870 (let ((height ...
13871 ...))
13872 (print-Y-axis height ... )
13873 (graph-body-print numbers-list)
13874 (print-X-axis ... )))
13875
13876We can work on each part of the `print-graph' function definition in
13877turn.
13878
13879The `print-graph' Varlist
13880=========================
13881
13882In writing the `print-graph' function, the first task is to write the
13883varlist in the `let' expression. (We will leave aside for the moment
13884any thoughts about making the function interactive or about the
13885contents of its documentation string.)
13886
13887The varlist should set several values. Clearly, the top of the label
13888for the vertical axis must be at least the height of the graph, which
13889means that we must obtain this information here. Note that the
13890`print-graph-body' function also requires this information. There is
13891no reason to calculate the height of the graph in two different
13892places, so we should change `print-graph-body' from the way we
13893defined it earlier to take advantage of the calculation.
13894
13895Similarly, both the function for printing the X axis labels and the
13896`print-graph-body' function need to learn the value of the width of
13897each symbol. We can perform the calculation here and change the
13898definition for `print-graph-body' from the way we defined it in the
13899previous chapter.
13900
13901The length of the label for the horizontal axis must be at least as
13902long as the graph. However, this information is used only in the
13903function that prints the horizontal axis, so it does not need to be
13904calculated here.
13905
13906These thoughts lead us directly to the following form for the varlist
13907in the `let' for `print-graph':
13908
13909 (let ((height (apply 'max numbers-list)) ; First version.
13910 (symbol-width (length graph-blank)))
13911
13912As we shall see, this expression is not quite right.
13913
13914The `print-Y-axis' Function
13915===========================
13916
13917The job of the `print-Y-axis' function is to print a label for the
13918vertical axis that looks like this:
13919
13920 10 -
13921
13922
13923
13924
13925 5 -
13926
13927
13928
13929 1 -
13930
13931The function should be passed the height of the graph, and then should
13932construct and insert the appropriate numbers and marks.
13933
13934It is easy enough to see in the figure what the Y axis label should
13935look like; but to say in words, and then to write a function
13936definition to do the job is another matter. It is not quite true to
13937say that we want a number and a tic every five lines: there are only
13938three lines between the `1' and the `5' (lines 2, 3, and 4), but four
13939lines between the `5' and the `10' (lines 6, 7, 8, and 9). It is
13940better to say that we want a number and a tic mark on the base line
13941(number 1) and then that we want a number and a tic on the fifth line
13942from the bottom and on every line that is a multiple of five.
13943
13944What height should the label be?
13945--------------------------------
13946
13947The next issue is what height the label should be? Suppose the
13948maximum height of tallest column of the graph is seven. Should the
13949highest label on the Y axis be `5 -', and should the graph stick up
13950above the label? Or should the highest label be `7 -', and mark the
13951peak of the graph? Or should the highest label be `10 -', which is a
13952multiple of five, and be higher than the topmost value of the graph?
13953
13954The latter form is preferred. Most graphs are drawn within rectangles
13955whose sides are an integral number of steps long--5, 10, 15, and so
13956on for a step distance of five. But as soon as we decide to use a
13957step height for the vertical axis, we discover that the simple
13958expression in the varlist for computing the height is wrong. The
13959expression is `(apply 'max numbers-list)'. This returns the precise
13960height, not the maximum height plus whatever is necessary to round up
13961to the nearest multiple of five. A more complex expression is
13962required.
13963
13964As usual in cases like this, a complex problem becomes simpler if it
13965is divided into several smaller problems.
13966
13967First, consider the case when the highest value of the graph is an
13968integral multiple of five--when it is 5, 10, 15 ,or some higher
13969multiple of five. We can use this value as the Y axis height.
13970
13971A fairly simply way to determine whether a number is a multiple of
13972five is to divide it by five and see if the division results in a
13973remainder. If there is no remainder, the number is a multiple of
13974five. Thus, seven divided by five has a remainder of two, and seven
13975is not an integral multiple of five. Put in slightly different
13976language, more reminiscent of the classroom, five goes into seven
13977once, with a remainder of two. However, five goes into ten twice,
13978with no remainder: ten is an integral multiple of five.
13979
13980Side Trip: Compute a Remainder
13981------------------------------
13982
13983In Lisp, the function for computing a remainder is `%'. The function
13984returns the remainder of its first argument divided by its second
13985argument. As it happens, `%' is a function in Emacs Lisp that you
13986cannot discover using `apropos': you find nothing if you type `M-x
13987apropos <RET> remainder <RET>'. The only way to learn of the
13988existence of `%' is to read about it in a book such as this or in the
13989Emacs Lisp sources. The `%' function is used in the code for
13990`rotate-yank-pointer', which is described in an appendix. (*Note The
13991Body of `rotate-yank-pointer': rotate-yk-ptr body.)
13992
13993You can try the `%' function by evaluating the following two
13994expressions:
13995
13996 (% 7 5)
13997
13998 (% 10 5)
13999
14000The first expression returns 2 and the second expression returns 0.
14001
14002To test whether the returned value is zero or some other number, we
14003can use the `zerop' function. This function returns `t' if its
14004argument, which must be a number, is zero.
14005
14006 (zerop (% 7 5))
14007 => nil
14008
14009 (zerop (% 10 5))
14010 => t
14011
14012Thus, the following expression will return `t' if the height of the
14013graph is evenly divisible by five:
14014
14015 (zerop (% height 5))
14016
14017(The value of `height', of course, can be found from `(apply 'max
14018numbers-list)'.)
14019
14020On the other hand, if the value of `height' is not a multiple of
14021five, we want to reset the value to the next higher multiple of five.
14022This is straightforward arithmetic using functions with which we are
14023already familiar. First, we divide the value of `height' by five to
14024determine how many times five goes into the number. Thus, five goes
14025into twelve twice. If we add one to this quotient and multiply by
14026five, we will obtain the value of the next multiple of five that is
14027larger than the height. Five goes into twelve twice. Add one to two,
14028and multiply by five; the result is fifteen, which is the next
14029multiple of five that is higher than twelve. The Lisp expression for
14030this is:
14031
14032 (* (1+ (/ height 5)) 5)
14033
14034For example, if you evaluate the following, the result is 15:
14035
14036 (* (1+ (/ 12 5)) 5)
14037
14038All through this discussion, we have been using `five' as the value
14039for spacing labels on the Y axis; but we may want to use some other
14040value. For generality, we should replace `five' with a variable to
14041which we can assign a value. The best name I can think of for this
14042variable is `Y-axis-label-spacing'.
14043
14044Using this term, and an `if' expression, we produce the following:
14045
14046 (if (zerop (% height Y-axis-label-spacing))
14047 height
14048 ;; else
14049 (* (1+ (/ height Y-axis-label-spacing))
14050 Y-axis-label-spacing))
14051
14052This expression returns the value of `height' itself if the height is
14053an even multiple of the value of the `Y-axis-label-spacing' or else
14054it computes and returns a value of `height' that is equal to the next
14055higher multiple of the value of the `Y-axis-label-spacing'.
14056
14057We can now include this expression in the `let' expression of the
14058`print-graph' function (after first setting the value of
14059`Y-axis-label-spacing'):
14060
14061 (defvar Y-axis-label-spacing 5
14062 "Number of lines from one Y axis label to next.")
14063
14064 ...
14065 (let* ((height (apply 'max numbers-list))
14066 (height-of-top-line
14067 (if (zerop (% height Y-axis-label-spacing))
14068 height
14069 ;; else
14070 (* (1+ (/ height Y-axis-label-spacing))
14071 Y-axis-label-spacing)))
14072 (symbol-width (length graph-blank))))
14073 ...
14074
14075(Note use of the `let*' function: the initial value of height is
14076computed once by the `(apply 'max numbers-list)' expression and then
14077the resulting value of `height' is used to compute its final value.
14078*Note The `let*' expression: fwd-para let, for more about `let*'.)
14079
14080Construct a Y Axis Element
14081--------------------------
14082
14083When we print the vertical axis, we want to insert strings such as
14084`5 -' and `10 - ' every five lines. Moreover, we want the numbers
14085and dashes to line up, so shorter numbers must be padded with leading
14086spaces. If some of the strings use two digit numbers, the strings
14087with single digit numbers must include a leading blank space before
14088the number.
14089
14090To figure out the length of the number, the `length' function is
14091used. But the `length' function works only with a string, not with a
14092number. So the number has to be converted from being a number to
14093being a string. This is done with the `number-to-string' function.
14094For example,
14095
14096 (length (number-to-string 35))
14097 => 2
14098
14099 (length (number-to-string 100))
14100 => 3
14101
14102(`number-to-string' is also called `int-to-string'; you will see this
14103alternative name in various sources.)
14104
14105In addition, in each label, each number is followed by a string such
14106as ` - ', which we will call the `Y-axis-tic' marker. This variable
14107is defined with `defvar':
14108
14109 (defvar Y-axis-tic " - "
14110 "String that follows number in a Y axis label.")
14111
14112The length of the Y label is the sum of the length of the Y axis tic
14113mark and the length of the number of the top of the graph.
14114
14115 (length (concat (number-to-string height) Y-axis-tic)))
14116
14117This value will be calculated by the `print-graph' function in its
14118varlist as `full-Y-label-width' and passed on. (Note that we did not
14119think to include this in the varlist when we first proposed it.)
14120
14121To make a complete vertical axis label, a tic mark is concatenated
14122with a number; and the two together may be preceded by one or more
14123spaces depending on how long the number is. The label consists of
14124three parts: the (optional) leading spaces, the number, and the tic
14125mark. The function is passed the value of the number for the specific
14126row, and the value of the width of the top line, which is calculated
14127(just once) by `print-graph'.
14128
14129 (defun Y-axis-element (number full-Y-label-width)
14130 "Construct a NUMBERed label element.
14131 A numbered element looks like this ` 5 - ',
14132 and is padded as needed so all line up with
14133 the element for the largest number."
14134 (let* ((leading-spaces
14135 (- full-Y-label-width
14136 (length
14137 (concat (number-to-string number)
14138 Y-axis-tic)))))
14139 (concat
14140 (make-string leading-spaces ? )
14141 (number-to-string number)
14142 Y-axis-tic)))
14143
14144The `Y-axis-element' function concatenates together the leading
14145spaces, if any; the number, as a string; and the tic mark.
14146
14147To figure out how many leading spaces the label will need, the
14148function subtracts the actual length of the label--the length of the
14149number plus the length of the tic mark--from the desired label width.
14150
14151Blank spaces are inserted using the `make-string' function. This
14152function takes two arguments: the first tells it how long the string
14153will be and the second is a symbol for the character to insert, in a
14154special format. The format is a question mark followed by a blank
14155space, like this, `? '. *Note Character Type: (elisp)Character Type,
14156for a description of the syntax for characters.
14157
14158The `number-to-string' function is used in the concatenation
14159expression, to convert the number to a string that is concatenated
14160with the leading spaces and the tic mark.
14161
14162Create a Y Axis Column
14163----------------------
14164
14165The preceding functions provide all the tools needed to construct a
14166function that generates a list of numbered and blank strings to insert
14167as the label for the vertical axis:
14168
14169 (defun Y-axis-column (height width-of-label)
14170 "Construct list of Y axis labels and blank strings.
14171 For HEIGHT of line above base and WIDTH-OF-LABEL."
14172 (let (Y-axis)
14173 (while (> height 1)
14174 (if (zerop (% height Y-axis-label-spacing))
14175 ;; Insert label.
14176 (setq Y-axis
14177 (cons
14178 (Y-axis-element height width-of-label)
14179 Y-axis))
14180 ;; Else, insert blanks.
14181 (setq Y-axis
14182 (cons
14183 (make-string width-of-label ? )
14184 Y-axis)))
14185 (setq height (1- height)))
14186 ;; Insert base line.
14187 (setq Y-axis
14188 (cons (Y-axis-element 1 width-of-label) Y-axis))
14189 (nreverse Y-axis)))
14190
14191In this function, we start with the value of `height' and
14192repetitively subtract one from its value. After each subtraction, we
14193test to see whether the value is an integral multiple of the
14194`Y-axis-label-spacing'. If it is, we construct a numbered label
14195using the `Y-axis-element' function; if not, we construct a blank
14196label using the `make-string' function. The base line consists of
14197the number one followed by a tic mark.
14198
14199The Not Quite Final Version of `print-Y-axis'
14200---------------------------------------------
14201
14202The list constructed by the `Y-axis-column' function is passed to the
14203`print-Y-axis' function, which inserts the list as a column.
14204
14205 (defun print-Y-axis (height full-Y-label-width)
14206 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
14207 Height must be the maximum height of the graph.
14208 Full width is the width of the highest label element."
14209 ;; Value of height and full-Y-label-width
14210 ;; are passed by `print-graph'.
14211 (let ((start (point)))
14212 (insert-rectangle
14213 (Y-axis-column height full-Y-label-width))
14214 ;; Place point ready for inserting graph.
14215 (goto-char start)
14216 ;; Move point forward by value of full-Y-label-width
14217 (forward-char full-Y-label-width)))
14218
14219The `print-Y-axis' uses the `insert-rectangle' function to insert the
14220Y axis labels created by the `Y-axis-column' function. In addition,
14221it places point at the correct position for printing the body of the
14222graph.
14223
14224You can test `print-Y-axis':
14225
14226 1. Install
14227
14228 Y-axis-label-spacing
14229 Y-axis-tic
14230 Y-axis-element
14231 Y-axis-column
14232 print-Y-axis
14233
14234 2. Copy the following expression:
14235
14236 (print-Y-axis 12 5)
14237
14238 3. Switch to the `*scratch*' buffer and place the cursor where you
14239 want the axis labels to start.
14240
14241 4. Type `M-:' (`eval-expression').
14242
14243 5. Yank the `graph-body-print' expression into the minibuffer with
14244 `C-y' (`yank)'.
14245
14246 6. Press <RET> to evaluate the expression.
14247
14248Emacs will print labels vertically, the top one being `10 - '. (The
14249`print-graph' function will pass the value of `height-of-top-line',
14250which in this case would end up as 15.)
14251
14252The `print-X-axis' Function
14253===========================
14254
14255X axis labels are much like Y axis labels, except that the tics are
14256on a line above the numbers. Labels should look like this:
14257
14258 | | | |
14259 1 5 10 15
14260
14261The first tic is under the first column of the graph and is preceded
14262by several blank spaces. These spaces provide room in rows above for
14263the Y axis labels. The second, third, fourth, and subsequent tics
14264are all spaced equally, according to the value of
14265`X-axis-label-spacing'.
14266
14267The second row of the X axis consists of numbers, preceded by several
14268blank spaces and also separated according to the value of the variable
14269`X-axis-label-spacing'.
14270
14271The value of the variable `X-axis-label-spacing' should itself be
14272measured in units of `symbol-width', since you may want to change the
14273width of the symbols that you are using to print the body of the
14274graph without changing the ways the graph is labelled.
14275
14276Similarities and differences
14277----------------------------
14278
14279The `print-X-axis' function is constructed in more or less the same
14280fashion as the `print-Y-axis' function except that it has two lines:
14281the line of tic marks and the numbers. We will write a separate
14282function to print each line and then combine them within the
14283`print-X-axis' function.
14284
14285This is a three step process:
14286
14287 1. Write a function to print the X axis tic marks,
14288 `print-X-axis-tic-line'.
14289
14290 2. Write a function to print the X numbers,
14291 `print-X-axis-numbered-line'.
14292
14293 3. Write a function to print both lines, the `print-X-axis'
14294 function, using `print-X-axis-tic-line' and
14295 `print-X-axis-numbered-line'.
14296
14297X Axis Tic Marks
14298----------------
14299
14300The first function should print the X axis tic marks. We must specify
14301the tic marks themselves and their spacing:
14302
14303 (defvar X-axis-label-spacing
14304 (if (boundp 'graph-blank)
14305 (* 5 (length graph-blank)) 5)
14306 "Number of units from one X axis label to next.")
14307
14308(Note that the value of `graph-blank' is set by another `defvar'.
14309The `boundp' predicate checks whether it has already been set;
14310`boundp' returns `nil' if it has not. If `graph-blank' were unbound
14311and we did not use this conditional construction, in GNU Emacs 21, we
14312would enter the debugger and see an error message saying
14313`Debugger entered--Lisp error: (void-variable graph-blank)'.)
14314
14315Here is the `defvar' for `X-axis-tic-symbol':
14316
14317 (defvar X-axis-tic-symbol "|"
14318 "String to insert to point to a column in X axis.")
14319
14320The goal is to make a line that looks like this:
14321
14322 | | | |
14323
14324The first tic is indented so that it is under the first column, which
14325is indented to provide space for the Y axis labels.
14326
14327A tic element consists of the blank spaces that stretch from one tic
14328to the next plus a tic symbol. The number of blanks is determined by
14329the width of the tic symbol and the `X-axis-label-spacing'.
14330
14331The code looks like this:
14332
14333 ;;; X-axis-tic-element
14334 ...
14335 (concat
14336 (make-string
14337 ;; Make a string of blanks.
14338 (- (* symbol-width X-axis-label-spacing)
14339 (length X-axis-tic-symbol))
14340 ? )
14341 ;; Concatenate blanks with tic symbol.
14342 X-axis-tic-symbol)
14343 ...
14344
14345Next, we determine how many blanks are needed to indent the first tic
14346mark to the first column of the graph. This uses the value of
14347`full-Y-label-width' passed it by the `print-graph' function.
14348
14349The code to make `X-axis-leading-spaces' looks like this:
14350
14351 ;; X-axis-leading-spaces
14352 ...
14353 (make-string full-Y-label-width ? )
14354 ...
14355
14356We also need to determine the length of the horizontal axis, which is
14357the length of the numbers list, and the number of tics in the
14358horizontal axis:
14359
14360 ;; X-length
14361 ...
14362 (length numbers-list)
14363
14364 ;; tic-width
14365 ...
14366 (* symbol-width X-axis-label-spacing)
14367
14368 ;; number-of-X-tics
14369 (if (zerop (% (X-length tic-width)))
14370 (/ (X-length tic-width))
14371 (1+ (/ (X-length tic-width))))
14372
14373All this leads us directly to the function for printing the X axis
14374tic line:
14375
14376 (defun print-X-axis-tic-line
14377 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
14378 "Print tics for X axis."
14379 (insert X-axis-leading-spaces)
14380 (insert X-axis-tic-symbol) ; Under first column.
14381 ;; Insert second tic in the right spot.
14382 (insert (concat
14383 (make-string
14384 (- (* symbol-width X-axis-label-spacing)
14385 ;; Insert white space up to second tic symbol.
14386 (* 2 (length X-axis-tic-symbol)))
14387 ? )
14388 X-axis-tic-symbol))
14389 ;; Insert remaining tics.
14390 (while (> number-of-X-tics 1)
14391 (insert X-axis-tic-element)
14392 (setq number-of-X-tics (1- number-of-X-tics))))
14393
14394The line of numbers is equally straightforward:
14395
14396First, we create a numbered element with blank spaces before each
14397number:
14398
14399 (defun X-axis-element (number)
14400 "Construct a numbered X axis element."
14401 (let ((leading-spaces
14402 (- (* symbol-width X-axis-label-spacing)
14403 (length (number-to-string number)))))
14404 (concat (make-string leading-spaces ? )
14405 (number-to-string number))))
14406
14407Next, we create the function to print the numbered line, starting with
14408the number "1" under the first column:
14409
14410 (defun print-X-axis-numbered-line
14411 (number-of-X-tics X-axis-leading-spaces)
14412 "Print line of X-axis numbers"
14413 (let ((number X-axis-label-spacing))
14414 (insert X-axis-leading-spaces)
14415 (insert "1")
14416 (insert (concat
14417 (make-string
14418 ;; Insert white space up to next number.
14419 (- (* symbol-width X-axis-label-spacing) 2)
14420 ? )
14421 (number-to-string number)))
14422 ;; Insert remaining numbers.
14423 (setq number (+ number X-axis-label-spacing))
14424 (while (> number-of-X-tics 1)
14425 (insert (X-axis-element number))
14426 (setq number (+ number X-axis-label-spacing))
14427 (setq number-of-X-tics (1- number-of-X-tics)))))
14428
14429Finally, we need to write the `print-X-axis' that uses
14430`print-X-axis-tic-line' and `print-X-axis-numbered-line'.
14431
14432The function must determine the local values of the variables used by
14433both `print-X-axis-tic-line' and `print-X-axis-numbered-line', and
14434then it must call them. Also, it must print the carriage return that
14435separates the two lines.
14436
14437The function consists of a varlist that specifies five local
14438variables, and calls to each of the two line printing functions:
14439
14440 (defun print-X-axis (numbers-list)
14441 "Print X axis labels to length of NUMBERS-LIST."
14442 (let* ((leading-spaces
14443 (make-string full-Y-label-width ? ))
14444 ;; symbol-width is provided by graph-body-print
14445 (tic-width (* symbol-width X-axis-label-spacing))
14446 (X-length (length numbers-list))
14447 (X-tic
14448 (concat
14449 (make-string
14450 ;; Make a string of blanks.
14451 (- (* symbol-width X-axis-label-spacing)
14452 (length X-axis-tic-symbol))
14453 ? )
14454 ;; Concatenate blanks with tic symbol.
14455 X-axis-tic-symbol))
14456 (tic-number
14457 (if (zerop (% X-length tic-width))
14458 (/ X-length tic-width)
14459 (1+ (/ X-length tic-width)))))
14460 (print-X-axis-tic-line tic-number leading-spaces X-tic)
14461 (insert "\n")
14462 (print-X-axis-numbered-line tic-number leading-spaces)))
14463
14464You can test `print-X-axis':
14465
14466 1. Install `X-axis-tic-symbol', `X-axis-label-spacing',
14467 `print-X-axis-tic-line', as well as `X-axis-element',
14468 `print-X-axis-numbered-line', and `print-X-axis'.
14469
14470 2. Copy the following expression:
14471
14472 (progn
14473 (let ((full-Y-label-width 5)
14474 (symbol-width 1))
14475 (print-X-axis
14476 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
14477
14478 3. Switch to the `*scratch*' buffer and place the cursor where you
14479 want the axis labels to start.
14480
14481 4. Type `M-:' (`eval-expression').
14482
14483 5. Yank the test expression into the minibuffer with `C-y' (`yank)'.
14484
14485 6. Press <RET> to evaluate the expression.
14486
14487Emacs will print the horizontal axis like this:
14488
14489 | | | | |
14490 1 5 10 15 20
14491
14492Printing the Whole Graph
14493========================
14494
14495Now we are nearly ready to print the whole graph.
14496
14497The function to print the graph with the proper labels follows the
14498outline we created earlier (*note A Graph with Labelled Axes: Full
14499Graph.), but with additions.
14500
14501Here is the outline:
14502
14503 (defun print-graph (numbers-list)
14504 "DOCUMENTATION..."
14505 (let ((height ...
14506 ...))
14507 (print-Y-axis height ... )
14508 (graph-body-print numbers-list)
14509 (print-X-axis ... )))
14510
14511Changes for the Final Version
14512-----------------------------
14513
14514The final version is different from what we planned in two ways:
14515first, it contains additional values calculated once in the varlist;
14516second, it carries an option to specify the labels' increment per row.
14517This latter feature turns out to be essential; otherwise, a graph may
14518have more rows than fit on a display or on a sheet of paper.
14519
14520This new feature requires a change to the `Y-axis-column' function,
14521to add `vertical-step' to it. The function looks like this:
14522
14523 ;;; Final version.
14524 (defun Y-axis-column
14525 (height width-of-label &optional vertical-step)
14526 "Construct list of labels for Y axis.
14527 HEIGHT is maximum height of graph.
14528 WIDTH-OF-LABEL is maximum width of label.
14529 VERTICAL-STEP, an option, is a positive integer
14530 that specifies how much a Y axis label increments
14531 for each line. For example, a step of 5 means
14532 that each line is five units of the graph."
14533 (let (Y-axis
14534 (number-per-line (or vertical-step 1)))
14535 (while (> height 1)
14536 (if (zerop (% height Y-axis-label-spacing))
14537 ;; Insert label.
14538 (setq Y-axis
14539 (cons
14540 (Y-axis-element
14541 (* height number-per-line)
14542 width-of-label)
14543 Y-axis))
14544 ;; Else, insert blanks.
14545 (setq Y-axis
14546 (cons
14547 (make-string width-of-label ? )
14548 Y-axis)))
14549 (setq height (1- height)))
14550 ;; Insert base line.
14551 (setq Y-axis (cons (Y-axis-element
14552 (or vertical-step 1)
14553 width-of-label)
14554 Y-axis))
14555 (nreverse Y-axis)))
14556
14557The values for the maximum height of graph and the width of a symbol
14558are computed by `print-graph' in its `let' expression; so
14559`graph-body-print' must be changed to accept them.
14560
14561 ;;; Final version.
14562 (defun graph-body-print (numbers-list height symbol-width)
14563 "Print a bar graph of the NUMBERS-LIST.
14564 The numbers-list consists of the Y-axis values.
14565 HEIGHT is maximum height of graph.
14566 SYMBOL-WIDTH is number of each column."
14567 (let (from-position)
14568 (while numbers-list
14569 (setq from-position (point))
14570 (insert-rectangle
14571 (column-of-graph height (car numbers-list)))
14572 (goto-char from-position)
14573 (forward-char symbol-width)
14574 ;; Draw graph column by column.
14575 (sit-for 0)
14576 (setq numbers-list (cdr numbers-list)))
14577 ;; Place point for X axis labels.
14578 (forward-line height)
14579 (insert "\n")))
14580
14581Finally, the code for the `print-graph' function:
14582
14583 ;;; Final version.
14584 (defun print-graph
14585 (numbers-list &optional vertical-step)
14586 "Print labelled bar graph of the NUMBERS-LIST.
14587 The numbers-list consists of the Y-axis values.
14588
14589 Optionally, VERTICAL-STEP, a positive integer,
14590 specifies how much a Y axis label increments for
14591 each line. For example, a step of 5 means that
14592 each row is five units."
14593 (let* ((symbol-width (length graph-blank))
14594 ;; `height' is both the largest number
14595 ;; and the number with the most digits.
14596 (height (apply 'max numbers-list))
14597 (height-of-top-line
14598 (if (zerop (% height Y-axis-label-spacing))
14599 height
14600 ;; else
14601 (* (1+ (/ height Y-axis-label-spacing))
14602 Y-axis-label-spacing)))
14603 (vertical-step (or vertical-step 1))
14604 (full-Y-label-width
14605 (length
14606 (concat
14607 (number-to-string
14608 (* height-of-top-line vertical-step))
14609 Y-axis-tic))))
14610
14611 (print-Y-axis
14612 height-of-top-line full-Y-label-width vertical-step)
14613 (graph-body-print
14614 numbers-list height-of-top-line symbol-width)
14615 (print-X-axis numbers-list)))
14616
14617Testing `print-graph'
14618---------------------
14619
14620We can test the `print-graph' function with a short list of numbers:
14621
14622 1. Install the final versions of `Y-axis-column',
14623 `graph-body-print', and `print-graph' (in addition to the rest
14624 of the code.)
14625
14626 2. Copy the following expression:
14627
14628 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
14629
14630 3. Switch to the `*scratch*' buffer and place the cursor where you
14631 want the axis labels to start.
14632
14633 4. Type `M-:' (`eval-expression').
14634
14635 5. Yank the test expression into the minibuffer with `C-y' (`yank)'.
14636
14637 6. Press <RET> to evaluate the expression.
14638
14639Emacs will print a graph that looks like this:
14640
14641 10 -
14642
14643
14644 *
14645 ** *
14646 5 - **** *
14647 **** ***
14648 * *********
14649 ************
14650 1 - *************
14651
14652 | | | |
14653 1 5 10 15
14654
14655On the other hand, if you pass `print-graph' a `vertical-step' value
14656of 2, by evaluating this expression:
14657
14658 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
14659
14660The graph looks like this:
14661
14662 20 -
14663
14664
14665 *
14666 ** *
14667 10 - **** *
14668 **** ***
14669 * *********
14670 ************
14671 2 - *************
14672
14673 | | | |
14674 1 5 10 15
14675
14676(A question: is the `2' on the bottom of the vertical axis a bug or a
14677feature? If you think it is a bug, and should be a `1' instead, (or
14678even a `0'), you can modify the sources.)
14679
14680Graphing Numbers of Words and Symbols
14681-------------------------------------
14682
14683Now for the graph for which all this code was written: a graph that
14684shows how many function definitions contain fewer than 10 words and
14685symbols, how many contain between 10 and 19 words and symbols, how
14686many contain between 20 and 29 words and symbols, and so on.
14687
14688This is a multi-step process. First make sure you have loaded all the
14689requisite code.
14690
14691It is a good idea to reset the value of `top-of-ranges' in case you
14692have set it to some different value. You can evaluate the following:
14693
14694 (setq top-of-ranges
14695 '(10 20 30 40 50
14696 60 70 80 90 100
14697 110 120 130 140 150
14698 160 170 180 190 200
14699 210 220 230 240 250
14700 260 270 280 290 300)
14701
14702Next create a list of the number of words and symbols in each range.
14703
14704Evaluate the following:
14705
14706 (setq list-for-graph
14707 (defuns-per-range
14708 (sort
14709 (recursive-lengths-list-many-files
14710 (directory-files "/usr/local/emacs/lisp"
14711 t ".+el$"))
14712 '<)
14713 top-of-ranges))
14714
14715On my machine, this takes about an hour. It looks though 303 Lisp
14716files in my copy of Emacs version 19.23. After all that computing,
14717the `list-for-graph' has this value:
14718
14719 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
14720 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
14721
14722This means that my copy of Emacs has 537 function definitions with
14723fewer than 10 words or symbols in them, 1,027 function definitions
14724with 10 to 19 words or symbols in them, 955 function definitions with
1472520 to 29 words or symbols in them, and so on.
14726
14727Clearly, just by looking at this list we can see that most function
14728definitions contain ten to thirty words and symbols.
14729
14730Now for printing. We do _not_ want to print a graph that is 1,030
14731lines high ... Instead, we should print a graph that is fewer than
14732twenty-five lines high. A graph that height can be displayed on
14733almost any monitor, and easily printed on a sheet of paper.
14734
14735This means that each value in `list-for-graph' must be reduced to
14736one-fiftieth its present value.
14737
14738Here is a short function to do just that, using two functions we have
14739not yet seen, `mapcar' and `lambda'.
14740
14741 (defun one-fiftieth (full-range)
14742 "Return list, each number one-fiftieth of previous."
14743 (mapcar '(lambda (arg) (/ arg 50)) full-range))
14744
14745A `lambda' Expression: Useful Anonymity
14746---------------------------------------
14747
14748`lambda' is the symbol for an anonymous function, a function without
14749a name. Every time you use an anonymous function, you need to
14750include its whole body.
14751
14752Thus,
14753
14754 (lambda (arg) (/ arg 50))
14755
14756is a function definition that says `return the value resulting from
14757dividing whatever is passed to me as `arg' by 50'.
14758
14759Earlier, for example, we had a function `multiply-by-seven'; it
14760multiplied its argument by 7. This function is similar, except it
14761divides its argument by 50; and, it has no name. The anonymous
14762equivalent of `multiply-by-seven' is:
14763
14764 (lambda (number) (* 7 number))
14765
14766(*Note The `defun' Special Form: defun.)
14767
14768If we want to multiply 3 by 7, we can write:
14769
14770 (multiply-by-seven 3)
14771 \_______________/ ^
14772 | |
14773 function argument
14774
14775
14776
14777This expression returns 21.
14778
14779Similarly, we can write:
14780
14781 ((lambda (number) (* 7 number)) 3)
14782 \____________________________/ ^
14783 | |
14784 anonymous function argument
14785
14786
14787
14788If we want to divide 100 by 50, we can write:
14789
14790 ((lambda (arg) (/ arg 50)) 100)
14791 \______________________/ \_/
14792 | |
14793 anonymous function argument
14794
14795
14796
14797This expression returns 2. The 100 is passed to the function, which
14798divides that number by 50.
14799
14800*Note Lambda Expressions: (elisp)Lambda Expressions, for more about
14801`lambda'. Lisp and lambda expressions derive from the Lambda
14802Calculus.
14803
14804The `mapcar' Function
14805---------------------
14806
14807`mapcar' is a function that calls its first argument with each
14808element of its second argument, in turn. The second argument must be
14809a sequence.
14810
14811The `map' part of the name comes from the mathematical phrase,
14812`mapping over a domain', meaning to apply a function to each of the
14813elements in a domain. The mathematical phrase is based on the
14814metaphor of a surveyor walking, one step at a time, over an area he is
14815mapping. And `car', of course, comes from the Lisp notion of the
14816first of a list.
14817
14818For example,
14819
14820 (mapcar '1+ '(2 4 6))
14821 => (3 5 7)
14822
14823The function `1+' which adds one to its argument, is executed on
14824_each_ element of the list, and a new list is returned.
14825
14826Contrast this with `apply', which applies its first argument to all
14827the remaining. (*Note Readying a Graph: Readying a Graph, for a
14828explanation of `apply'.)
14829
14830In the definition of `one-fiftieth', the first argument is the
14831anonymous function:
14832
14833 (lambda (arg) (/ arg 50))
14834
14835and the second argument is `full-range', which will be bound to
14836`list-for-graph'.
14837
14838The whole expression looks like this:
14839
14840 (mapcar '(lambda (arg) (/ arg 50)) full-range))
14841
14842*Note Mapping Functions: (elisp)Mapping Functions, for more about
14843`mapcar'.
14844
14845Using the `one-fiftieth' function, we can generate a list in which
14846each element is one-fiftieth the size of the corresponding element in
14847`list-for-graph'.
14848
14849 (setq fiftieth-list-for-graph
14850 (one-fiftieth list-for-graph))
14851
14852The resulting list looks like this:
14853
14854 (10 20 19 15 11 9 6 5 4 3 3 2 2
14855 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
14856
14857This, we are almost ready to print! (We also notice the loss of
14858information: many of the higher ranges are 0, meaning that fewer than
1485950 defuns had that many words or symbols--but not necessarily meaning
14860that none had that many words or symbols.)
14861
14862Another Bug ... Most Insidious
14863------------------------------
14864
14865I said `almost ready to print'! Of course, there is a bug in the
14866`print-graph' function ... It has a `vertical-step' option, but not
14867a `horizontal-step' option. The `top-of-range' scale goes from 10 to
14868300 by tens. But the `print-graph' function will print only by ones.
14869
14870This is a classic example of what some consider the most insidious
14871type of bug, the bug of omission. This is not the kind of bug you can
14872find by studying the code, for it is not in the code; it is an omitted
14873feature. Your best actions are to try your program early and often;
14874and try to arrange, as much as you can, to write code that is easy to
14875understand and easy to change. Try to be aware, whenever you can,
14876that whatever you have written, _will_ be rewritten, if not soon,
14877eventually. A hard maxim to follow.
14878
14879It is the `print-X-axis-numbered-line' function that needs the work;
14880and then the `print-X-axis' and the `print-graph' functions need to
14881be adapted. Not much needs to be done; there is one nicety: the
14882numbers ought to line up under the tic marks. This takes a little
14883thought.
14884
14885Here is the corrected `print-X-axis-numbered-line':
14886
14887 (defun print-X-axis-numbered-line
14888 (number-of-X-tics X-axis-leading-spaces
14889 &optional horizontal-step)
14890 "Print line of X-axis numbers"
14891 (let ((number X-axis-label-spacing)
14892 (horizontal-step (or horizontal-step 1)))
14893 (insert X-axis-leading-spaces)
14894 ;; Delete extra leading spaces.
14895 (delete-char
14896 (- (1-
14897 (length (number-to-string horizontal-step)))))
14898 (insert (concat
14899 (make-string
14900 ;; Insert white space.
14901 (- (* symbol-width
14902 X-axis-label-spacing)
14903 (1-
14904 (length
14905 (number-to-string horizontal-step)))
14906 2)
14907 ? )
14908 (number-to-string
14909 (* number horizontal-step))))
14910 ;; Insert remaining numbers.
14911 (setq number (+ number X-axis-label-spacing))
14912 (while (> number-of-X-tics 1)
14913 (insert (X-axis-element
14914 (* number horizontal-step)))
14915 (setq number (+ number X-axis-label-spacing))
14916 (setq number-of-X-tics (1- number-of-X-tics)))))
14917
14918If you are reading this in Info, you can see the new versions of
14919`print-X-axis' `print-graph' and evaluate them. If you are reading
14920this in a printed book, you can see the changed lines here (the full
14921text is too much to print).
14922
14923 (defun print-X-axis (numbers-list horizontal-step)
14924 "Print X axis labels to length of NUMBERS-LIST.
14925 Optionally, HORIZONTAL-STEP, a positive integer,
14926 specifies how much an X axis label increments for
14927 each column."
14928 ;; Value of symbol-width and full-Y-label-width
14929 ;; are passed by `print-graph'.
14930 (let* ((leading-spaces
14931 (make-string full-Y-label-width ? ))
14932 ;; symbol-width is provided by graph-body-print
14933 (tic-width (* symbol-width X-axis-label-spacing))
14934 (X-length (length numbers-list))
14935 (X-tic
14936 (concat
14937 (make-string
14938 ;; Make a string of blanks.
14939 (- (* symbol-width X-axis-label-spacing)
14940 (length X-axis-tic-symbol))
14941 ? )
14942 ;; Concatenate blanks with tic symbol.
14943 X-axis-tic-symbol))
14944 (tic-number
14945 (if (zerop (% X-length tic-width))
14946 (/ X-length tic-width)
14947 (1+ (/ X-length tic-width)))))
14948
14949 (print-X-axis-tic-line
14950 tic-number leading-spaces X-tic)
14951 (insert "\n")
14952 (print-X-axis-numbered-line
14953 tic-number leading-spaces horizontal-step)))
14954
14955 (defun print-graph
14956 (numbers-list &optional vertical-step horizontal-step)
14957 "Print labelled bar graph of the NUMBERS-LIST.
14958 The numbers-list consists of the Y-axis values.
14959
14960 Optionally, VERTICAL-STEP, a positive integer,
14961 specifies how much a Y axis label increments for
14962 each line. For example, a step of 5 means that
14963 each row is five units.
14964
14965 Optionally, HORIZONTAL-STEP, a positive integer,
14966 specifies how much an X axis label increments for
14967 each column."
14968 (let* ((symbol-width (length graph-blank))
14969 ;; `height' is both the largest number
14970 ;; and the number with the most digits.
14971 (height (apply 'max numbers-list))
14972 (height-of-top-line
14973 (if (zerop (% height Y-axis-label-spacing))
14974 height
14975 ;; else
14976 (* (1+ (/ height Y-axis-label-spacing))
14977 Y-axis-label-spacing)))
14978 (vertical-step (or vertical-step 1))
14979 (full-Y-label-width
14980 (length
14981 (concat
14982 (number-to-string
14983 (* height-of-top-line vertical-step))
14984 Y-axis-tic))))
14985 (print-Y-axis
14986 height-of-top-line full-Y-label-width vertical-step)
14987 (graph-body-print
14988 numbers-list height-of-top-line symbol-width)
14989 (print-X-axis numbers-list horizontal-step)))
14990
14991The Printed Graph
14992-----------------
14993
14994When made and installed, you can call the `print-graph' command like
14995this:
14996
14997 (print-graph fiftieth-list-for-graph 50 10)
14998
14999Here is the graph:
15000
15001
15002
15003 1000 - *
15004 **
15005 **
15006 **
15007 **
15008 750 - ***
15009 ***
15010 ***
15011 ***
15012 ****
15013 500 - *****
15014 ******
15015 ******
15016 ******
15017 *******
15018 250 - ********
15019 ********* *
15020 *********** *
15021 ************* *
15022 50 - ***************** * *
15023 | | | | | | | |
15024 10 50 100 150 200 250 300 350
15025
15026
15027
15028The largest group of functions contain 10 - 19 words and symbols each.
15029
15030GNU Free Documentation License
15031******************************
15032
15033 Version 1.1, March 2000
15034 Copyright (C) 2000 Free Software Foundation, Inc.
15035 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
15036
15037 Everyone is permitted to copy and distribute verbatim copies
15038 of this license document, but changing it is not allowed.
15039
15040 0. PREAMBLE
15041
15042 The purpose of this License is to make a manual, textbook, or
15043 other written document "free" in the sense of freedom: to assure
15044 everyone the effective freedom to copy and redistribute it, with
15045 or without modifying it, either commercially or noncommercially.
15046 Secondarily, this License preserves for the author and
15047 publisher a way to get credit for their work, while not being
15048 considered responsible for modifications made by others.
15049
15050 This License is a kind of "copyleft", which means that derivative
15051 works of the document must themselves be free in the same sense.
15052 It complements the GNU General Public License, which is a
15053 copyleft license designed for free software.
15054
15055 We have designed this License in order to use it for manuals for
15056 free software, because free software needs free documentation: a
15057 free program should come with manuals providing the same
15058 freedoms that the software does. But this License is not
15059 limited to software manuals; it can be used for any textual
15060 work, regardless of subject matter or whether it is published as
15061 a printed book. We recommend this License principally for works
15062 whose purpose is instruction or reference.
15063
15064 1. APPLICABILITY AND DEFINITIONS
15065
15066 This License applies to any manual or other work that contains a
15067 notice placed by the copyright holder saying it can be
15068 distributed under the terms of this License. The "Document",
15069 below, refers to any such manual or work. Any member of the
15070 public is a licensee, and is addressed as "you".
15071
15072 A "Modified Version" of the Document means any work containing
15073 the Document or a portion of it, either copied verbatim, or with
15074 modifications and/or translated into another language.
15075
15076 A "Secondary Section" is a named appendix or a front-matter
15077 section of the Document that deals exclusively with the
15078 relationship of the publishers or authors of the Document to the
15079 Document's overall subject (or to related matters) and contains
15080 nothing that could fall directly within that overall subject.
15081 (For example, if the Document is in part a textbook of
15082 mathematics, a Secondary Section may not explain any
15083 mathematics.) The relationship could be a matter of historical
15084 connection with the subject or with related matters, or of legal,
15085 commercial, philosophical, ethical or political position
15086 regarding them.
15087
15088 The "Invariant Sections" are certain Secondary Sections whose
15089 titles are designated, as being those of Invariant Sections, in
15090 the notice that says that the Document is released under this
15091 License.
15092
15093 The "Cover Texts" are certain short passages of text that are
15094 listed, as Front-Cover Texts or Back-Cover Texts, in the notice
15095 that says that the Document is released under this License.
15096
15097 A "Transparent" copy of the Document means a machine-readable
15098 copy, represented in a format whose specification is available
15099 to the general public, whose contents can be viewed and edited
15100 directly and straightforwardly with generic text editors or (for
15101 images composed of pixels) generic paint programs or (for
15102 drawings) some widely available drawing editor, and that is
15103 suitable for input to text formatters or for automatic
15104 translation to a variety of formats suitable for input to text
15105 formatters. A copy made in an otherwise Transparent file format
15106 whose markup has been designed to thwart or discourage
15107 subsequent modification by readers is not Transparent. A copy
15108 that is not "Transparent" is called "Opaque".
15109
15110 Examples of suitable formats for Transparent copies include plain
15111 ASCII without markup, Texinfo input format, LaTeX input format,
15112 SGML or XML using a publicly available DTD, and
15113 standard-conforming simple HTML designed for human modification.
15114 Opaque formats include PostScript, PDF, proprietary formats
15115 that can be read and edited only by proprietary word processors,
15116 SGML or XML for which the DTD and/or processing tools are not
15117 generally available, and the machine-generated HTML produced by
15118 some word processors for output purposes only.
15119
15120 The "Title Page" means, for a printed book, the title page
15121 itself, plus such following pages as are needed to hold,
15122 legibly, the material this License requires to appear in the
15123 title page. For works in formats which do not have any title
15124 page as such, "Title Page" means the text near the most
15125 prominent appearance of the work's title, preceding the
15126 beginning of the body of the text.
15127
15128 2. VERBATIM COPYING
15129
15130 You may copy and distribute the Document in any medium, either
15131 commercially or noncommercially, provided that this License, the
15132 copyright notices, and the license notice saying this License
15133 applies to the Document are reproduced in all copies, and that
15134 you add no other conditions whatsoever to those of this License.
15135 You may not use technical measures to obstruct or control the
15136 reading or further copying of the copies you make or distribute.
15137 However, you may accept compensation in exchange for copies.
15138 If you distribute a large enough number of copies you must also
15139 follow the conditions in section 3.
15140
15141 You may also lend copies, under the same conditions stated
15142 above, and you may publicly display copies.
15143
15144 3. COPYING IN QUANTITY
15145
15146 If you publish printed copies of the Document numbering more
15147 than 100, and the Document's license notice requires Cover
15148 Texts, you must enclose the copies in covers that carry, clearly
15149 and legibly, all these Cover Texts: Front-Cover Texts on the
15150 front cover, and Back-Cover Texts on the back cover. Both
15151 covers must also clearly and legibly identify you as the
15152 publisher of these copies. The front cover must present the
15153 full title with all words of the title equally prominent and
15154 visible. You may add other material on the covers in addition.
15155 Copying with changes limited to the covers, as long as they
15156 preserve the title of the Document and satisfy these conditions,
15157 can be treated as verbatim copying in other respects.
15158
15159 If the required texts for either cover are too voluminous to fit
15160 legibly, you should put the first ones listed (as many as fit
15161 reasonably) on the actual cover, and continue the rest onto
15162 adjacent pages.
15163
15164 If you publish or distribute Opaque copies of the Document
15165 numbering more than 100, you must either include a
15166 machine-readable Transparent copy along with each Opaque copy,
15167 or state in or with each Opaque copy a publicly-accessible
15168 computer-network location containing a complete Transparent copy
15169 of the Document, free of added material, which the general
15170 network-using public has access to download anonymously at no
15171 charge using public-standard network protocols. If you use the
15172 latter option, you must take reasonably prudent steps, when you
15173 begin distribution of Opaque copies in quantity, to ensure that
15174 this Transparent copy will remain thus accessible at the stated
15175 location until at least one year after the last time you
15176 distribute an Opaque copy (directly or through your agents or
15177 retailers) of that edition to the public.
15178
15179 It is requested, but not required, that you contact the authors
15180 of the Document well before redistributing any large number of
15181 copies, to give them a chance to provide you with an updated
15182 version of the Document.
15183
15184 4. MODIFICATIONS
15185
15186 You may copy and distribute a Modified Version of the Document
15187 under the conditions of sections 2 and 3 above, provided that
15188 you release the Modified Version under precisely this License,
15189 with the Modified Version filling the role of the Document, thus
15190 licensing distribution and modification of the Modified Version
15191 to whoever possesses a copy of it. In addition, you must do
15192 these things in the Modified Version:
15193
15194 A. Use in the Title Page (and on the covers, if any) a title
15195 distinct from that of the Document, and from those of
15196 previous versions (which should, if there were any, be
15197 listed in the History section of the Document). You may
15198 use the same title as a previous version if the original
15199 publisher of that version gives permission.
15200
15201 B. List on the Title Page, as authors, one or more persons or
15202 entities responsible for authorship of the modifications in
15203 the Modified Version, together with at least five of the
15204 principal authors of the Document (all of its principal
15205 authors, if it has less than five).
15206
15207 C. State on the Title page the name of the publisher of the
15208 Modified Version, as the publisher.
15209
15210 D. Preserve all the copyright notices of the Document.
15211
15212 E. Add an appropriate copyright notice for your modifications
15213 adjacent to the other copyright notices.
15214
15215 F. Include, immediately after the copyright notices, a license
15216 notice giving the public permission to use the Modified
15217 Version under the terms of this License, in the form shown
15218 in the Addendum below.
15219
15220 G. Preserve in that license notice the full lists of Invariant
15221 Sections and required Cover Texts given in the Document's
15222 license notice.
15223
15224 H. Include an unaltered copy of this License.
15225
15226 I. Preserve the section entitled "History", and its title, and
15227 add to it an item stating at least the title, year, new
15228 authors, and publisher of the Modified Version as given on
15229 the Title Page. If there is no section entitled "History"
15230 in the Document, create one stating the title, year,
15231 authors, and publisher of the Document as given on its
15232 Title Page, then add an item describing the Modified
15233 Version as stated in the previous sentence.
15234
15235 J. Preserve the network location, if any, given in the
15236 Document for public access to a Transparent copy of the
15237 Document, and likewise the network locations given in the
15238 Document for previous versions it was based on. These may
15239 be placed in the "History" section. You may omit a network
15240 location for a work that was published at least four years
15241 before the Document itself, or if the original publisher of
15242 the version it refers to gives permission.
15243
15244 K. In any section entitled "Acknowledgments" or "Dedications",
15245 preserve the section's title, and preserve in the section
15246 all the substance and tone of each of the contributor
15247 acknowledgments and/or dedications given therein.
15248
15249 L. Preserve all the Invariant Sections of the Document,
15250 unaltered in their text and in their titles. Section
15251 numbers or the equivalent are not considered part of the
15252 section titles.
15253
15254 M. Delete any section entitled "Endorsements". Such a section
15255 may not be included in the Modified Version.
15256
15257 N. Do not retitle any existing section as "Endorsements" or to
15258 conflict in title with any Invariant Section.
15259
15260 If the Modified Version includes new front-matter sections or
15261 appendices that qualify as Secondary Sections and contain no
15262 material copied from the Document, you may at your option
15263 designate some or all of these sections as invariant. To do
15264 this, add their titles to the list of Invariant Sections in the
15265 Modified Version's license notice. These titles must be
15266 distinct from any other section titles.
15267
15268 You may add a section entitled "Endorsements", provided it
15269 contains nothing but endorsements of your Modified Version by
15270 various parties--for example, statements of peer review or that
15271 the text has been approved by an organization as the
15272 authoritative definition of a standard.
15273
15274 You may add a passage of up to five words as a Front-Cover Text,
15275 and a passage of up to 25 words as a Back-Cover Text, to the end
15276 of the list of Cover Texts in the Modified Version. Only one
15277 passage of Front-Cover Text and one of Back-Cover Text may be
15278 added by (or through arrangements made by) any one entity. If
15279 the Document already includes a cover text for the same cover,
15280 previously added by you or by arrangement made by the same
15281 entity you are acting on behalf of, you may not add another; but
15282 you may replace the old one, on explicit permission from the
15283 previous publisher that added the old one.
15284
15285 The author(s) and publisher(s) of the Document do not by this
15286 License give permission to use their names for publicity for or
15287 to assert or imply endorsement of any Modified Version.
15288
15289 5. COMBINING DOCUMENTS
15290
15291 You may combine the Document with other documents released under
15292 this License, under the terms defined in section 4 above for
15293 modified versions, provided that you include in the combination
15294 all of the Invariant Sections of all of the original documents,
15295 unmodified, and list them all as Invariant Sections of your
15296 combined work in its license notice.
15297
15298 The combined work need only contain one copy of this License, and
15299 multiple identical Invariant Sections may be replaced with a
15300 single copy. If there are multiple Invariant Sections with the
15301 same name but different contents, make the title of each such
15302 section unique by adding at the end of it, in parentheses, the
15303 name of the original author or publisher of that section if
15304 known, or else a unique number. Make the same adjustment to the
15305 section titles in the list of Invariant Sections in the license
15306 notice of the combined work.
15307
15308 In the combination, you must combine any sections entitled
15309 "History" in the various original documents, forming one section
15310 entitled "History"; likewise combine any sections entitled
15311 "Acknowledgments", and any sections entitled "Dedications". You
15312 must delete all sections entitled "Endorsements."
15313
15314 6. COLLECTIONS OF DOCUMENTS
15315
15316 You may make a collection consisting of the Document and other
15317 documents released under this License, and replace the
15318 individual copies of this License in the various documents with
15319 a single copy that is included in the collection, provided that
15320 you follow the rules of this License for verbatim copying of
15321 each of the documents in all other respects.
15322
15323 You may extract a single document from such a collection, and
15324 distribute it individually under this License, provided you
15325 insert a copy of this License into the extracted document, and
15326 follow this License in all other respects regarding verbatim
15327 copying of that document.
15328
15329 7. AGGREGATION WITH INDEPENDENT WORKS
15330
15331 A compilation of the Document or its derivatives with other
15332 separate and independent documents or works, in or on a volume
15333 of a storage or distribution medium, does not as a whole count
15334 as a Modified Version of the Document, provided no compilation
15335 copyright is claimed for the compilation. Such a compilation is
15336 called an "aggregate", and this License does not apply to the
15337 other self-contained works thus compiled with the Document, on
15338 account of their being thus compiled, if they are not themselves
15339 derivative works of the Document.
15340
15341 If the Cover Text requirement of section 3 is applicable to these
15342 copies of the Document, then if the Document is less than one
15343 quarter of the entire aggregate, the Document's Cover Texts may
15344 be placed on covers that surround only the Document within the
15345 aggregate. Otherwise they must appear on covers around the
15346 whole aggregate.
15347
15348 8. TRANSLATION
15349
15350 Translation is considered a kind of modification, so you may
15351 distribute translations of the Document under the terms of
15352 section 4. Replacing Invariant Sections with translations
15353 requires special permission from their copyright holders, but
15354 you may include translations of some or all Invariant Sections
15355 in addition to the original versions of these Invariant
15356 Sections. You may include a translation of this License
15357 provided that you also include the original English version of
15358 this License. In case of a disagreement between the translation
15359 and the original English version of this License, the original
15360 English version will prevail.
15361
15362 9. TERMINATION
15363
15364 You may not copy, modify, sublicense, or distribute the Document
15365 except as expressly provided for under this License. Any other
15366 attempt to copy, modify, sublicense or distribute the Document
15367 is void, and will automatically terminate your rights under this
15368 License. However, parties who have received copies, or rights,
15369 from you under this License will not have their licenses
15370 terminated so long as such parties remain in full compliance.
15371
15372 10. FUTURE REVISIONS OF THIS LICENSE
15373
15374 The Free Software Foundation may publish new, revised versions
15375 of the GNU Free Documentation License from time to time. Such
15376 new versions will be similar in spirit to the present version,
15377 but may differ in detail to address new problems or concerns.
15378 See `http://www.gnu.org/copyleft/'.
15379
15380 Each version of the License is given a distinguishing version
15381 number. If the Document specifies that a particular numbered
15382 version of this License "or any later version" applies to it,
15383 you have the option of following the terms and conditions either
15384 of that specified version or of any later version that has been
15385 published (not as a draft) by the Free Software Foundation. If
15386 the Document does not specify a version number of this License,
15387 you may choose any version ever published (not as a draft) by
15388 the Free Software Foundation.
15389
15390Index
15391*****
15392
15393% (remainder function):
15394 See ``Side Trip: Compute a Remainder''.
15395(debug) in code:
15396 See ```debug-on-quit' and `(debug)'''.
15397* (multiplication):
15398 See ``The `defun' Special Form''.
15399* for read-only buffer:
15400 See ``A Read-only Buffer''.
15401*scratch* buffer:
15402 See ``An Example: `print-elements-of-list'''.
15403.emacs file:
15404 See ``Your `.emacs' File''.
15405.emacs file, beginning of:
15406 See ``Beginning a `.emacs' File''.
15407/ (division):
15408 See ``What happens in a large buffer''.
15409<= (less than or equal):
15410 See ``The parts of the function definition''.
15411> (greater than):
15412 See ```if' in more detail''.
15413Accumulate, type of recursive pattern:
15414 See ``Recursive Pattern: _accumulate_''.
15415add-hook:
15416 See ``Text and Auto Fill Mode''.
15417and <1>:
15418 See ``The `let*' expression''.
15419and:
15420 See ``The `kill-new' function''.
15421and, introduced:
15422 See ``The `kill-new' function''.
15423Anonymous function:
15424 See ``A `lambda' Expression: Useful Anonymity''.
15425append-to-buffer:
15426 See ``The Definition of `append-to-buffer'''.
15427apply:
15428 See ``Printing the Columns of a Graph''.
15429apropos:
15430 See ``Printing the Columns of a Graph''.
15431Argument as local variable:
15432 See ``Putting the function definition together''.
15433argument defined:
15434 See ``Arguments''.
15435argument list defined:
15436 See ``The `defun' Special Form''.
15437Argument, wrong type of:
15438 See ``Using the Wrong Type Object as an Argument''.
15439Arguments:
15440 See ``Arguments''.
15441Arguments' data types:
15442 See ``Arguments' Data Types''.
15443Arguments, variable number of:
15444 See ``Variable Number of Arguments''.
15445Asterisk for read-only buffer:
15446 See ``A Read-only Buffer''.
15447Auto Fill mode turned on:
15448 See ``Text and Auto Fill Mode''.
15449autoload:
15450 See ``Autoloading''.
15451Automatic mode selection:
15452 See ``Text and Auto Fill Mode''.
15453Axis, print horizontal:
15454 See ``The `print-X-axis' Function''.
15455Axis, print vertical:
15456 See ``The `print-Y-axis' Function''.
15457beginning-of-buffer:
15458 See ``Complete Definition of `beginning-of-buffer'''.
15459bind defined:
15460 See ``Setting the Value of a Variable''.
15461body defined:
15462 See ``The `defun' Special Form''.
15463Body of graph:
15464 See ``Readying a Graph''.
15465Buffer size:
15466 See ``Buffer Size and the Location of Point''.
15467Buffer, history of word:
15468 See ``Buffer Names''.
15469buffer-file-name:
15470 See ``Buffer Names''.
15471buffer-menu, bound to key:
15472 See ``Some Keybindings''.
15473buffer-name:
15474 See ``Buffer Names''.
15475Bug, most insidious type:
15476 See ``Another Bug ... Most Insidious''.
15477Building robots:
15478 See ``Building Robots: Extending the Metaphor''.
15479Building Tags in the Emacs sources:
15480 See ``Create Your Own `TAGS' File''.
15481Byte compiling:
15482 See ``Byte Compiling''.
15483C language primitives:
15484 See ``An Aside about Primitive Functions''.
15485C, a digression into:
15486 See ``Digression into C''.
15487call defined:
15488 See ``Switching Buffers''.
15489cancel-debug-on-entry:
15490 See ```debug-on-entry'''.
15491car, introduced:
15492 See ```car', `cdr', `cons': Fundamental Functions''.
15493cdr, introduced:
15494 See ```car', `cdr', `cons': Fundamental Functions''.
15495Changing a function definition:
15496 See ``Change a Function Definition''.
15497Chest of Drawers, metaphor for a symbol:
15498 See ``Symbols as a Chest of Drawers''.
15499Clipping text:
15500 See ``Cutting and Storing Text''.
15501Code installation:
15502 See ``Install Code Permanently''.
15503command defined:
15504 See ``How to Evaluate''.
15505Comments in Lisp code:
15506 See ``Change a Function Definition''.
15507Common Lisp:
15508 See ``Lisp History''.
15509compare-windows:
15510 See ``Some Keybindings''.
15511concat:
15512 See ``Arguments' Data Types''.
15513cond:
15514 See ``Recursion Example Using `cond'''.
15515condition-case:
15516 See ```condition-case'''.
15517Conditional 'twixt two versions of Emacs:
15518 See ``A Simple Extension: `line-to-top-of-window'''.
15519Conditional with if:
15520 See ``The `if' Special Form''.
15521cons, example:
15522 See ``The `kill-new' function''.
15523cons, introduced:
15524 See ```cons'''.
15525copy-region-as-kill:
15526 See ```copy-region-as-kill'''.
15527copy-to-buffer:
15528 See ``The Definition of `copy-to-buffer'''.
15529Count words recursively:
15530 See ``Count Words Recursively''.
15531count-words-in-defun:
15532 See ``The `count-words-in-defun' Function''.
15533count-words-region:
15534 See ``The `count-words-region' Function''.
15535Counting:
15536 See ``Counting''.
15537Counting words in a defun <1>:
15538 See ``The `count-words-in-defun' Function''.
15539Counting words in a defun:
15540 See ``Counting Words in a `defun'''.
15541current-buffer:
15542 See ``Getting Buffers''.
15543Customizing your .emacs file:
15544 See ``Your `.emacs' File''.
15545Cutting and storing text:
15546 See ``Cutting and Storing Text''.
15547Data types:
15548 See ``Arguments' Data Types''.
15549debug:
15550 See ```debug'''.
15551debug-on-entry:
15552 See ```debug-on-entry'''.
15553debug-on-quit:
15554 See ```debug-on-quit' and `(debug)'''.
15555debugging:
15556 See ``Debugging''.
15557default-mode-line-format:
15558 See ``A Modified Mode Line''.
15559default.el init file:
15560 See ``Site-wide Initialization Files''.
15561defcustom:
15562 See ``Specifying Variables using `defcustom'''.
15563Deferment in recursion:
15564 See ``Recursion without Deferments''.
15565Defermentless solution:
15566 See ``No Deferment Solution''.
15567Definition installation:
15568 See ``Install a Function Definition''.
15569Definition writing:
15570 See ``How To Write Function Definitions''.
15571Definition, how to change:
15572 See ``Change a Function Definition''.
15573defun:
15574 See ``The `defun' Special Form''.
15575defvar:
15576 See ``Initializing a Variable with `defvar'''.
15577defvar for a user customizable variable:
15578 See ```defvar' and an asterisk''.
15579defvar with an asterisk:
15580 See ```defvar' and an asterisk''.
15581delete-and-extract-region <1>:
15582 See ``Digression into C''.
15583delete-and-extract-region:
15584 See ```delete-and-extract-region'''.
15585Deleting text:
15586 See ``Cutting and Storing Text''.
15587describe-function:
15588 See ``A Simplified `beginning-of-buffer' Definition''.
15589describe-function, introduced:
15590 See ``Finding More Information''.
15591Digression into C:
15592 See ``Digression into C''.
15593directory-files:
15594 See ``Making a List of Files''.
15595Division:
15596 See ``What happens in a large buffer''.
15597dolist:
15598 See ``The `dolist' Macro''.
15599dotimes:
15600 See ``The `dotimes' Macro''.
15601Drawers, Chest of, metaphor for a symbol:
15602 See ``Symbols as a Chest of Drawers''.
15603Duplicated words function:
15604 See ``The `the-the' Function''.
15605edebug:
15606 See ``The `edebug' Source Level Debugger''.
15607edit-options:
15608 See ```defvar' and an asterisk''.
15609Else:
15610 See ``If-then-else Expressions''.
15611Emacs version, choosing:
15612 See ``A Simple Extension: `line-to-top-of-window'''.
15613empty list defined:
15614 See ``Lisp Atoms''.
15615empty string defined:
15616 See ``Review''.
15617eobp:
15618 See ``Between paragraphs''.
15619eq:
15620 See ``Review''.
15621eq (example of use):
15622 See ```last-command' and `this-command'''.
15623equal:
15624 See ``Review''.
15625Erasing text:
15626 See ``Cutting and Storing Text''.
15627error:
15628 See ``The Body of `rotate-yank-pointer'''.
15629Error for symbol without function:
15630 See ``Error Message for a Symbol Without a Function''.
15631Error for symbol without value:
15632 See ``Error Message for a Symbol Without a Value''.
15633Error message generation:
15634 See ``Generate an Error Message''.
15635etags:
15636 See ``Create Your Own `TAGS' File''.
15637evaluate defined:
15638 See ``Run a Program''.
15639Evaluating inner lists:
15640 See ``Evaluating Inner Lists''.
15641Evaluation:
15642 See ``Evaluation''.
15643Evaluation practice:
15644 See ``Practicing Evaluation''.
15645Every, type of recursive pattern:
15646 See ``Recursive Pattern: _every_''.
15647Example variable, fill-column:
15648 See ```fill-column', an Example Variable''.
15649expression defined:
15650 See ``Lisp Atoms''.
15651Falsehood and truth in Emacs Lisp:
15652 See ``Truth and Falsehood in Emacs Lisp''.
15653FDL, GNU Free Documentation License:
15654 See ``GNU Free Documentation License''.
15655files-in-below-directory:
15656 See ``Making a List of Files''.
15657fill-column, an example variable:
15658 See ```fill-column', an Example Variable''.
15659Find a File:
15660 See ``Find a File''.
15661Find function documentation:
15662 See ``Finding More Information''.
15663Find source of function:
15664 See ``Finding More Information''.
15665find-tags:
15666 See ``Finding More Information''.
15667Flowers in a field:
15668 See ``Lisp Lists''.
15669Focusing attention (narrowing):
15670 See ``Narrowing and Widening''.
15671form defined:
15672 See ``Lisp Atoms''.
15673Formatting convention:
15674 See ```save-excursion' in `append-to-buffer'''.
15675Formatting help:
15676 See ``GNU Emacs Helps You Type Lists''.
15677forward-paragraph:
15678 See ```forward-paragraph': a Goldmine of Functions''.
15679forward-sentence:
15680 See ```forward-sentence'''.
15681function defined:
15682 See ``Generate an Error Message''.
15683function definition defined:
15684 See ``The `defun' Special Form''.
15685Function definition installation:
15686 See ``Install a Function Definition''.
15687Function definition writing:
15688 See ``How To Write Function Definitions''.
15689Function definition, how to change:
15690 See ``Change a Function Definition''.
15691Functions, primitive:
15692 See ``An Aside about Primitive Functions''.
15693Generate an error message:
15694 See ``Generate an Error Message''.
15695Getting a buffer:
15696 See ``Getting Buffers''.
15697Global set key:
15698 See ``Some Keybindings''.
15699global-set-key:
15700 See ``Some Keybindings''.
15701global-unset-key:
15702 See ``Some Keybindings''.
15703Graph prototype:
15704 See ``Readying a Graph''.
15705Graph, printing all:
15706 See ``Printing the Whole Graph''.
15707graph-body-print:
15708 See ``The `graph-body-print' Function''.
15709graph-body-print Final version.:
15710 See ``Changes for the Final Version''.
15711Handling the kill ring:
15712 See ``Handling the Kill Ring''.
15713Help typing lists:
15714 See ``GNU Emacs Helps You Type Lists''.
15715Horizontal axis printing:
15716 See ``The `print-X-axis' Function''.
15717if:
15718 See ``The `if' Special Form''.
15719if-part defined:
15720 See ```if' in more detail''.
15721indent-tabs-mode:
15722 See ``Indent Tabs Mode''.
15723Indentation for formatting:
15724 See ```save-excursion' in `append-to-buffer'''.
15725Initialization file:
15726 See ``Your `.emacs' File''.
15727Initializing a variable:
15728 See ``Initializing a Variable with `defvar'''.
15729Inner list evaluation:
15730 See ``Evaluating Inner Lists''.
15731insert-buffer:
15732 See ``The Definition of `insert-buffer'''.
15733insert-buffer-substring:
15734 See ``An Overview of `append-to-buffer'''.
15735Insidious type of bug:
15736 See ``Another Bug ... Most Insidious''.
15737Install a Function Definition:
15738 See ``Install a Function Definition''.
15739Install code permanently:
15740 See ``Install Code Permanently''.
15741interactive:
15742 See ``Make a Function Interactive''.
15743interactive function defined:
15744 See ``How to Evaluate''.
15745Interactive functions:
15746 See ``Make a Function Interactive''.
15747Interactive options:
15748 See ``Different Options for `interactive'''.
15749interactive, example use of:
15750 See ``The Interactive Expression in `insert-buffer'''.
15751Interpreter, Lisp, explained:
15752 See ``Run a Program''.
15753Interpreter, what it does:
15754 See ``The Lisp Interpreter''.
15755Keep, type of recursive pattern:
15756 See ``Recursive Pattern: _keep_''.
15757Key setting globally:
15758 See ``Some Keybindings''.
15759Key unbinding:
15760 See ``Some Keybindings''.
15761Keymaps:
15762 See ``Keymaps''.
15763Keyword:
15764 See ``Optional Arguments''.
15765Kill ring handling:
15766 See ``Handling the Kill Ring''.
15767Kill ring overview:
15768 See ``Kill Ring Overview''.
15769kill-append:
15770 See ``The `kill-append' function''.
15771kill-new:
15772 See ``The `kill-new' function''.
15773kill-region:
15774 See ```kill-region'''.
15775Killing text:
15776 See ``Cutting and Storing Text''.
15777lambda:
15778 See ``A `lambda' Expression: Useful Anonymity''.
15779length:
15780 See ``Find the Length of a List: `length'''.
15781lengths-list-file:
15782 See ```lengths-list-file' in Detail''.
15783lengths-list-many-files:
15784 See ``Determine the lengths of `defuns'''.
15785let:
15786 See ```let'''.
15787let expression sample:
15788 See ``Sample `let' Expression''.
15789let expression, parts of:
15790 See ``The Parts of a `let' Expression''.
15791let variables uninitialized:
15792 See ``Uninitialized Variables in a `let' Statement''.
15793Library, as term for `file':
15794 See ``Finding More Information''.
15795line-to-top-of-window:
15796 See ``A Simple Extension: `line-to-top-of-window'''.
15797Lisp Atoms:
15798 See ``Lisp Atoms''.
15799Lisp history:
15800 See ``Lisp History''.
15801Lisp interpreter, explained:
15802 See ``Run a Program''.
15803Lisp interpreter, what it does:
15804 See ``The Lisp Interpreter''.
15805Lisp Lists:
15806 See ``Lisp Lists''.
15807Lisp macro:
15808 See ```delete-and-extract-region'''.
15809list-buffers, rebound:
15810 See ``Some Keybindings''.
15811Lists in a computer:
15812 See ``How Lists are Implemented''.
15813load-library:
15814 See ``Loading Files''.
15815load-path:
15816 See ``Loading Files''.
15817Loading files:
15818 See ``Loading Files''.
15819local variable defined:
15820 See ```let' Prevents Confusion''.
15821Local variables list, per-buffer,:
15822 See ``Text and Auto Fill Mode''.
15823Location of point:
15824 See ``Buffer Size and the Location of Point''.
15825looking-at:
15826 See ``Between paragraphs''.
15827Loops:
15828 See ```while'''.
15829Loops and recursion:
15830 See ``Loops and Recursion''.
15831Maclisp:
15832 See ``Lisp History''.
15833Macro, lisp:
15834 See ```delete-and-extract-region'''.
15835Mail aliases:
15836 See ``Mail Aliases''.
15837make tags:
15838 See ``Create Your Own `TAGS' File''.
15839make-string:
15840 See ``Construct a Y Axis Element''.
15841mapcar:
15842 See ``The `mapcar' Function''.
15843mark:
15844 See ```save-excursion'''.
15845mark-whole-buffer:
15846 See ``The Definition of `mark-whole-buffer'''.
15847match-beginning:
15848 See ``No fill prefix''.
15849max:
15850 See ``Printing the Columns of a Graph''.
15851message:
15852 See ``The `message' Function''.
15853min:
15854 See ``Printing the Columns of a Graph''.
15855Mode line format:
15856 See ``A Modified Mode Line''.
15857Mode selection, automatic:
15858 See ``Text and Auto Fill Mode''.
15859Motion by sentence and paragraph:
15860 See ``Regular Expression Searches''.
15861Narrowing:
15862 See ``Narrowing and Widening''.
15863narrowing defined:
15864 See ``Buffer Size and the Location of Point''.
15865nil:
15866 See ``Truth and Falsehood in Emacs Lisp''.
15867nil, history of word:
15868 See ``Buffer Names''.
15869No deferment solution:
15870 See ``No Deferment Solution''.
15871nreverse:
15872 See ``Counting function definitions''.
15873nth:
15874 See ```nth'''.
15875nthcdr <1>:
15876 See ```copy-region-as-kill'''.
15877nthcdr:
15878 See ```nthcdr'''.
15879nthcdr, example:
15880 See ``The `kill-new' function''.
15881number-to-string:
15882 See ``Construct a Y Axis Element''.
15883occur:
15884 See ``Some Keybindings''.
15885optional:
15886 See ``Optional Arguments''.
15887Optional arguments:
15888 See ``Optional Arguments''.
15889Options for interactive:
15890 See ``Different Options for `interactive'''.
15891or:
15892 See ``The `or' in the Body''.
15893other-buffer:
15894 See ``Getting Buffers''.
15895Paragraphs, movement by:
15896 See ``Regular Expression Searches''.
15897Parts of a Recursive Definition:
15898 See ``The Parts of a Recursive Definition''.
15899Parts of let expression:
15900 See ``The Parts of a `let' Expression''.
15901Passing information to functions:
15902 See ``Arguments''.
15903Pasting text:
15904 See ``Yanking Text Back''.
15905Patterns, searching for:
15906 See ``Regular Expression Searches''.
15907Per-buffer, local variables list:
15908 See ``Text and Auto Fill Mode''.
15909Permanent code installation:
15910 See ``Install Code Permanently''.
15911point:
15912 See ```save-excursion'''.
15913point defined:
15914 See ``Buffer Size and the Location of Point''.
15915Point location:
15916 See ``Buffer Size and the Location of Point''.
15917Point, mark, buffer preservation:
15918 See ```save-excursion'''.
15919Practicing evaluation:
15920 See ``Practicing Evaluation''.
15921Preserving point, mark, and buffer:
15922 See ```save-excursion'''.
15923Primitive functions:
15924 See ``An Aside about Primitive Functions''.
15925Primitives written in C:
15926 See ``An Aside about Primitive Functions''.
15927Print horizontal axis:
15928 See ``The `print-X-axis' Function''.
15929Print vertical axis:
15930 See ``The `print-Y-axis' Function''.
15931print-elements-of-list:
15932 See ``An Example: `print-elements-of-list'''.
15933print-elements-recursively:
15934 See ``Recursion with a List''.
15935print-graph Final version.:
15936 See ``Changes for the Final Version''.
15937print-graph varlist:
15938 See ``The `print-graph' Varlist''.
15939print-X-axis:
15940 See ``X Axis Tic Marks''.
15941print-X-axis-numbered-line:
15942 See ``X Axis Tic Marks''.
15943print-X-axis-tic-line:
15944 See ``X Axis Tic Marks''.
15945print-Y-axis:
15946 See ``The Not Quite Final Version of `print-Y-axis'''.
15947Printing the whole graph:
15948 See ``Printing the Whole Graph''.
15949prog1:
15950 See ``Between paragraphs''.
15951progn:
15952 See ``The `progn' Special Form''.
15953Program, running one:
15954 See ``Run a Program''.
15955Prototype graph:
15956 See ``Readying a Graph''.
15957re-search-forward:
15958 See ``The `re-search-forward' Function''.
15959Read-only buffer:
15960 See ``A Read-only Buffer''.
15961Readying a graph:
15962 See ``Readying a Graph''.
15963Rebinding keys:
15964 See ``Keymaps''.
15965Recursion:
15966 See ``Recursion''.
15967Recursion and loops:
15968 See ``Loops and Recursion''.
15969Recursion without Deferments:
15970 See ``Recursion without Deferments''.
15971Recursive Definition Parts:
15972 See ``The Parts of a Recursive Definition''.
15973Recursive pattern: accumulate:
15974 See ``Recursive Pattern: _accumulate_''.
15975Recursive pattern: every:
15976 See ``Recursive Pattern: _every_''.
15977Recursive pattern: keep:
15978 See ``Recursive Pattern: _keep_''.
15979Recursive Patterns:
15980 See ``Recursive Patterns''.
15981recursive-count-words:
15982 See ``Count Words Recursively''.
15983recursive-graph-body-print:
15984 See ``The `recursive-graph-body-print' Function''.
15985recursive-lengths-list-many-files:
15986 See ``Recursively Count Words in Different Files''.
15987Recursively counting words:
15988 See ``Count Words Recursively''.
15989regexp-quote:
15990 See ``The `let*' expression''.
15991Region, what it is:
15992 See ```save-excursion'''.
15993Regular expression searches:
15994 See ``Regular Expression Searches''.
15995Regular expressions for word counting:
15996 See ``Counting: Repetition and Regexps''.
15997Remainder function, %:
15998 See ``Side Trip: Compute a Remainder''.
15999Repetition (loops):
16000 See ``Loops and Recursion''.
16001Repetition for word counting:
16002 See ``Counting: Repetition and Regexps''.
16003Retrieving text:
16004 See ``Yanking Text Back''.
16005reverse:
16006 See ``Counting function definitions''.
16007Ring, making a list like a:
16008 See ``Handling the Kill Ring''.
16009Robots, building:
16010 See ``Building Robots: Extending the Metaphor''.
16011rotate-yank-pointer <1>:
16012 See ``The `rotate-yank-pointer' Function''.
16013rotate-yank-pointer:
16014 See ``Yanking Text Back''.
16015Run a program:
16016 See ``Run a Program''.
16017Sample let expression:
16018 See ``Sample `let' Expression''.
16019save-excursion:
16020 See ```save-excursion'''.
16021save-restriction:
16022 See ``The `save-restriction' Special Form''.
16023search-forward:
16024 See ``The `search-forward' Function''.
16025Searches, illustrating:
16026 See ``Regular Expression Searches''.
16027sentence-end:
16028 See ``The Regular Expression for `sentence-end'''.
16029Sentences, movement by:
16030 See ``Regular Expression Searches''.
16031set:
16032 See ``Using `set'''.
16033set-buffer:
16034 See ``Switching Buffers''.
16035setcar:
16036 See ```setcar'''.
16037setcdr:
16038 See ```setcdr'''.
16039setcdr, example:
16040 See ``The `kill-new' function''.
16041setq:
16042 See ``Using `setq'''.
16043Setting a key globally:
16044 See ``Some Keybindings''.
16045Setting value of variable:
16046 See ``Setting the Value of a Variable''.
16047side effect defined:
16048 See ``Evaluation''.
16049Simple extension in .emacs file:
16050 See ``A Simple Extension: `line-to-top-of-window'''.
16051simplified-beginning-of-buffer:
16052 See ``A Simplified `beginning-of-buffer' Definition''.
16053site-init.el init file:
16054 See ``Site-wide Initialization Files''.
16055site-load.el init file:
16056 See ``Site-wide Initialization Files''.
16057Size of buffer:
16058 See ``Buffer Size and the Location of Point''.
16059Solution without deferment:
16060 See ``No Deferment Solution''.
16061sort:
16062 See ``Sorting Lists''.
16063Source level debugger:
16064 See ``The `edebug' Source Level Debugger''.
16065Special form:
16066 See ``Complications''.
16067Special form of defun:
16068 See ``The `defun' Special Form''.
16069Storing and cutting text:
16070 See ``Cutting and Storing Text''.
16071string defined:
16072 See ``Lisp Atoms''.
16073switch-to-buffer:
16074 See ``Switching Buffers''.
16075Switching to a buffer:
16076 See ``Switching Buffers''.
16077Symbol names:
16078 See ``Symbol Names and Function Definitions''.
16079Symbol without function error:
16080 See ``Error Message for a Symbol Without a Function''.
16081Symbol without value error:
16082 See ``Error Message for a Symbol Without a Value''.
16083Symbolic expressions, introduced:
16084 See ``Lisp Atoms''.
16085Symbols as a Chest of Drawers:
16086 See ``Symbols as a Chest of Drawers''.
16087Syntax categories and tables:
16088 See ``What Constitutes a Word or Symbol?''.
16089Tabs, preventing:
16090 See ``Indent Tabs Mode''.
16091TAGS file, create own:
16092 See ``Create Your Own `TAGS' File''.
16093Tags in the Emacs sources:
16094 See ``Create Your Own `TAGS' File''.
16095TAGS table, specifying:
16096 See ``Finding More Information''.
16097Text between double quotation marks:
16098 See ``Lisp Atoms''.
16099Text Mode turned on:
16100 See ``Text and Auto Fill Mode''.
16101Text retrieval:
16102 See ``Yanking Text Back''.
16103the-the:
16104 See ``The `the-the' Function''.
16105then-part defined:
16106 See ```if' in more detail''.
16107top-of-ranges:
16108 See ``Counting function definitions''.
16109triangle-bugged:
16110 See ```debug'''.
16111triangle-recursively:
16112 See ``Recursion in Place of a Counter''.
16113Truth and falsehood in Emacs Lisp:
16114 See ``Truth and Falsehood in Emacs Lisp''.
16115Types of data:
16116 See ``Arguments' Data Types''.
16117Unbinding key:
16118 See ``Some Keybindings''.
16119Uninitialized let variables:
16120 See ``Uninitialized Variables in a `let' Statement''.
16121Variable initialization:
16122 See ``Initializing a Variable with `defvar'''.
16123Variable number of arguments:
16124 See ``Variable Number of Arguments''.
16125Variable, example of, fill-column:
16126 See ```fill-column', an Example Variable''.
16127Variable, setting value:
16128 See ``Setting the Value of a Variable''.
16129Variables:
16130 See ``Variables''.
16131varlist defined:
16132 See ``The Parts of a `let' Expression''.
16133Version of Emacs, choosing:
16134 See ``A Simple Extension: `line-to-top-of-window'''.
16135Vertical axis printing:
16136 See ``The `print-Y-axis' Function''.
16137what-line:
16138 See ```what-line'''.
16139while:
16140 See ```while'''.
16141Whitespace in lists:
16142 See ``Whitespace in Lists''.
16143Whole graph printing:
16144 See ``Printing the Whole Graph''.
16145Widening:
16146 See ``Narrowing and Widening''.
16147Widening, example of:
16148 See ```what-line'''.
16149Word counting in a defun:
16150 See ``Counting Words in a `defun'''.
16151Words and symbols in defun:
16152 See ``What to Count?''.
16153Words, counted recursively:
16154 See ``Count Words Recursively''.
16155Words, duplicated:
16156 See ``The `the-the' Function''.
16157Writing a function definition:
16158 See ``How To Write Function Definitions''.
16159Wrong type of argument:
16160 See ``Using the Wrong Type Object as an Argument''.
16161X axis printing:
16162 See ``The `print-X-axis' Function''.
16163X-axis-element:
16164 See ``X Axis Tic Marks''.
16165Y axis printing:
16166 See ``The `print-Y-axis' Function''.
16167Y-axis-column:
16168 See ``Create a Y Axis Column''.
16169Y-axis-column Final version.:
16170 See ``Changes for the Final Version''.
16171Y-axis-label-spacing:
16172 See ``Side Trip: Compute a Remainder''.
16173Y-axis-tic:
16174 See ``Construct a Y Axis Element''.
16175yank <1>:
16176 See ```yank'''.
16177yank:
16178 See ``Yanking Text Back''.
16179yank-pop:
16180 See ```yank-pop'''.
16181zap-to-char:
16182 See ```zap-to-char'''.
16183zerop:
16184 See ``The Body of `rotate-yank-pointer'''.
16185About the Author
16186****************
16187
16188 Robert J. Chassell has worked with GNU Emacs since 1985. He
16189 writes and edits, teaches Emacs and Emacs Lisp, and speaks
16190 throughout the world on software freedom. Chassell was a
16191 founding Director and Treasurer of the Free Software Foundation,
16192 Inc. He is co-author of the `Texinfo' manual, and has edited
16193 more than a dozen other books. He graduated from Cambridge
16194 University, in England. He has an abiding interest in social
16195 and economic history and flies his own airplane.
16196
16197